From fa9f154e1b4e3b678e19a9d867b65dc4d0d6f0ef Mon Sep 17 00:00:00 2001 From: nikalezah <67012982+nikalezah@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:02:37 +0500 Subject: [PATCH 001/255] fix(web): the Cite button appears when a selection ends on a file chip's icon in Firefox (#41949) Co-authored-by: Julius Marminge --- apps/web/src/index.css | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4441b65f8143f..aac51580dd887 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2084,6 +2084,17 @@ code { vertical-align: -0.125em; } +/* Firefox resolves a drag over the sprite icon's to the shared and collapses the + selection there, or snaps an unselectable icon's point into the text before it. Passing the + pointer to the chip lands the selection at its label. Chromium keeps triple-click line + selection only without user-select: none here. */ +@supports (-moz-appearance: none) { + .chat-markdown-file-link > svg { + pointer-events: none; + user-select: none; + } +} + .chat-markdown-file-link > [data-slot="context-chip-label"] { display: inline; } From f516cf9de87763d146b363ee752cc2cc69f6f08e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:07:53 -0800 Subject: [PATCH 002/255] fix(opencode): project skills show in the / menu from the first snapshot on OpenCode 2 (#42080) --- .../provider-opencode/src/server/driver.ts | 59 ++++++++++--------- .../src/server/status.test.ts | 30 +++------- .../provider-opencode/src/server/status.ts | 41 ++++++++++--- 3 files changed, 72 insertions(+), 58 deletions(-) diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index 10af4aeffa908..cc1977325c0ea 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -38,6 +38,7 @@ import { readOpenCodeGoUsageLimits } from "./usageLimits.ts"; import { loadOpenCode2Catalog, loadOpenCode2DirectoryCatalog } from "./openCode2Catalog.ts"; import { checkOpenCodeProviderStatus, + followOpenCode2Scans, loadOpenCode2Workspace, makeOpenCode2CatalogWatch, makeOpenCode2ModelLoader, @@ -411,10 +412,25 @@ export const OpenCodeDriver: ProviderDriver< connection.events, loadOpenCode2DirectoryCatalog(connection.client, machineDirectory(connection)), ); + // Locations whose scan T3 saw end on the current server; a scan is announced only once. + let scans = { url: "", scanned: new Set() }; + const followScans = (connection: OpenCode2Server.OpenCode2Connection) => + Effect.suspend(() => { + const scanned = new Set(); + scans = { url: connection.url, scanned }; + return connection.events.pipe( + Effect.flatMap((events) => + followOpenCode2Scans(events, (directory) => Effect.sync(() => scanned.add(directory))), + ), + Effect.scoped, + Effect.ignore, + Effect.forkScoped, + ); + }); // A session or text generation can start the server too, and reads no catalog when it does. - yield* Stream.runForEach(openCode2Server.connections, followMachineCatalog).pipe( - Effect.forkScoped, - ); + yield* Stream.runForEach(openCode2Server.connections, (connection) => + followScans(connection).pipe(Effect.andThen(followMachineCatalog(connection))), + ).pipe(Effect.forkScoped); const loadOpenCode2Models = yield* makeOpenCode2ModelLoader( openCode2Server.withConnection((connection) => followMachineCatalog(connection).pipe( @@ -424,29 +440,23 @@ export const OpenCodeDriver: ProviderDriver< processEnv, ); const listOpenCode2Workspace = (cwd: string) => - openCode2Server.withConnection(({ client, events }) => + openCode2Server.withConnection(({ client, events, url }) => Effect.gen(function* () { // OpenCode names a location by its resolved path (no trailing slash or `..`). const directory = pathService.resolve(cwd); const location = { directory }; + if (scans.url !== url) scans = { url, scanned: new Set() }; + const { scanned: seen } = scans; const scanned = yield* Deferred.make(); - const pending = new Set(["command.updated", "skill.updated"]); const stream = yield* events.pipe(Effect.option); if (stream._tag === "Some") { - yield* stream.value.pipe( - Stream.runForEach((event) => - "location" in event && - event.location?.directory === directory && - pending.delete(event.type) && - pending.size === 0 - ? Deferred.succeed(scanned, undefined) - : Effect.void, - ), - Effect.ignore, - Effect.forkScoped, - ); + yield* followOpenCode2Scans(stream.value, (scannedDirectory) => + scannedDirectory === directory + ? Deferred.succeed(scanned, undefined).pipe(Effect.asVoid) + : Effect.void, + ).pipe(Effect.forkScoped); } - return yield* loadOpenCode2Workspace( + const workspace = yield* loadOpenCode2Workspace( Effect.all( { skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)), @@ -456,17 +466,12 @@ export const OpenCodeDriver: ProviderDriver< ), Deferred.await(scanned), // Without events no scan can be awaited, so trust the first read as before. - stream._tag === "None" - ? Effect.succeed(true) - : client.debug.location.list().pipe( - Effect.map((loaded) => loaded.some((entry) => entry.directory === directory)), - Effect.timeout("2 seconds"), - Effect.orElseSucceed(() => true), - ), - // OpenCode answers provider.list for a location only once its skill scan has ended. - client.provider.list({ location }).pipe(Effect.timeout("10 seconds"), Effect.ignore), + stream._tag === "None" || seen.has(directory), processEnv, ); + // A location loaded before T3 watched never announces its scan; wait for it only once. + seen.add(directory); + return workspace; }).pipe(Effect.scoped), ); const serverOwner = yield* OpenCodeServerOwner.make({ diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index bac2b31047176..c378c9ec8b848 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -1254,15 +1254,18 @@ const scanned: OpenCode2Workspace = { }; it.effect( - "reads a loaded OpenCode 2 directory listing no commands again once its scan has ended", + "waits for the scan of an OpenCode 2 directory that lists built-ins before T3 saw its scan end", () => Effect.gen(function* () { - const reads: Array = [{ commands: [], skills: [] }, scanned]; + const reads: Array = [ + { commands: builtinCommands, skills: builtinSkills }, + scanned, + ]; const scanEnded = yield* Deferred.make(); const load = yield* loadOpenCode2Workspace( Effect.sync(() => reads.shift()!), Deferred.await(scanEnded), - Effect.succeed(true), + false, ).pipe(Effect.forkChild); yield* Effect.yieldNow; NodeAssert.equal(reads.length, 1); @@ -1271,30 +1274,13 @@ it.effect( }), ); -it.effect("waits for the scan of a cold OpenCode 2 directory that first lists only built-ins", () => - Effect.gen(function* () { - const calls: Array = []; - const reads: Array = [ - { commands: builtinCommands, skills: builtinSkills }, - scanned, - ]; - const workspace = yield* loadOpenCode2Workspace( - Effect.sync(() => (calls.push("read"), reads.shift()!)), - Effect.sync(() => void calls.push("scanned")), - Effect.sync(() => (calls.push("loaded"), false)), - ); - NodeAssert.deepEqual(workspace, scanned); - NodeAssert.deepEqual(calls, ["loaded", "read", "scanned", "read"]); - }), -); - -it.effect("reads an already loaded OpenCode 2 directory once without waiting for a scan", () => +it.effect("reads an OpenCode 2 directory whose scan T3 saw end once without waiting", () => Effect.gen(function* () { const calls: Array = []; const workspace = yield* loadOpenCode2Workspace( Effect.sync(() => (calls.push("read"), scanned)), Effect.sync(() => void calls.push("scanned")), - Effect.succeed(true), + true, ); NodeAssert.deepEqual(workspace, scanned); NodeAssert.deepEqual(calls, ["read"]); diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.ts index a429ab63aec7e..c29926976ec4b 100644 --- a/packages/provider-opencode/src/server/status.ts +++ b/packages/provider-opencode/src/server/status.ts @@ -819,23 +819,46 @@ export interface OpenCode2Workspace { } /** - * Reading a location the server has not loaded boots its scan, and only reads after the scan's - * `command.updated` plus `skill.updated` are complete; `scanned` must listen before `read`. A - * loaded location listing no commands is still scanning. A location another caller booted - * moments earlier lists as loaded with only built-ins, so `settled` waits out its scan first. + * Runs `onScanned` for each location whose scan ends, which OpenCode announces once, after loading + * the location, as `command.updated` plus `skill.updated`. + */ +export const followOpenCode2Scans = ( + events: Stream.Stream< + { readonly type: string; readonly location?: { readonly directory?: string } | undefined }, + E + >, + onScanned: (directory: string) => Effect.Effect, +) => { + const pending = new Map>(); + return events.pipe( + Stream.runForEach((event) => { + const directory = event.location?.directory; + if (directory === undefined) return Effect.void; + if (event.type !== "command.updated" && event.type !== "skill.updated") return Effect.void; + const seen = pending.get(directory) ?? new Set(); + pending.set(directory, seen.add(event.type)); + if (seen.size < 2) return Effect.void; + pending.delete(directory); + return onScanned(directory); + }), + Effect.ignore, + ); +}; + +/** + * Until its scan ends a location lists only built-ins, even once the server lists it as loaded, + * and nothing but the scan's end tells the two apart. Unless the caller saw that scan end, read to + * boot the location, wait for its scan (`scanned` must listen before `read`), and read again. */ export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")( function* ( read: Effect.Effect, scanned: Effect.Effect, - loaded: Effect.Effect, - settled: Effect.Effect = Effect.void, + sawScan: boolean, environment?: NodeJS.ProcessEnv, ) { - const wasLoaded = yield* loaded; - yield* settled; const first = yield* read; - if (wasLoaded && first.commands.length > 0) return first; + if (sawScan) return first; yield* scanned.pipe( Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, environment)), ); From b28b13bd1f0e10cfb1864fa3d6c37c276dd0031a Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 05:13:23 -0600 Subject: [PATCH 003/255] fix(cli): keep --track folder labels valid when an emoji crosses the name limit (#42083) Co-authored-by: Julius Marminge --- apps/server/src/cli/project.test.ts | 15 +++++++++++++++ apps/server/src/cli/project.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 6dfd723e7084a..6c3469c1eb948 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -143,6 +143,12 @@ it.effect( const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); + // Names are cut to 128 UTF-16 units, never between the halves of an emoji. + const named = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-names-")); + const straddling = NodePath.join(named, `${"a".repeat(127)}🚀`); + const fitting = NodePath.join(named, `${"b".repeat(126)}🚀`); + const padded = NodePath.join(named, `${" ".repeat(127)}🚀`); + for (const folder of [straddling, fitting, padded]) NodeFS.mkdirSync(folder); yield* runCli([ "project", "add", @@ -151,6 +157,12 @@ it.effect( `${shared}${NodePath.sep}`, "--track", `~/${NodePath.basename(homeShared)}`, + "--track", + straddling, + "--track", + fitting, + "--track", + padded, "--base-dir", baseDir, ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); @@ -158,6 +170,9 @@ it.effect( { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, { path: homeShared, name: NodePath.basename(homeShared) }, + { path: straddling, name: "a".repeat(127) }, + { path: fitting, name: `${"b".repeat(126)}🚀` }, + { path: padded, name: "🚀" }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 1fa7cc0f3f264..fb11ade0c75dd 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -8,6 +8,7 @@ import { ProjectId, } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -401,9 +402,10 @@ const projectAddCommand = Command.make("add", { const named = flags.track .map((folder) => { const resolved = path.resolve(expandHomePath(folder, home)); + const name = (path.basename(resolved) || resolved).trimStart(); return { path: resolved, - name: (path.basename(resolved) || resolved).slice(0, 128).trim(), + name: name.slice(0, splitsSurrogatePair(name, 128) ? 127 : 128).trim(), }; }) .filter( From 30bda7ede9d2bd02c6ff6a0aa04fff7945ded813 Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Tue, 24 Nov 2026 12:13:44 +0100 Subject: [PATCH 004/255] fix(server): resolve project favicon links with URL fragments (#42082) Co-authored-by: geezoria <25051260+geezoria@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/project/ProjectFaviconResolver.test.ts | 4 ++-- apps/server/src/project/ProjectFaviconResolver.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 00ac4e5d17ef3..5de818cbeea9d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -202,7 +202,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { - + `, ); yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); @@ -306,7 +306,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { links: [ { rel: "stylesheet", href: "/app.css" }, { rel: "icon", href: "https://cdn.example.com/icon.svg" }, - { rel: "icon shortcut", href: "/brand/logo.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg#mark" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index b2df7e0f53eb3..85930064d033d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -83,7 +83,7 @@ const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])| const HTML_ATTRIBUTE_RE = /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); -const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; +const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?#]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( "ProjectFaviconResolutionError", @@ -144,7 +144,7 @@ function* extractIconHrefs(source: string): Generator { const href = attributes.get("href"); // An unquoted `{...}` is a JSX expression, not a path. if (!href || (!href.quoted && href.value.startsWith("{"))) continue; - const path = href.value.split("?")[0]; + const path = href.value.split(/[?#]/, 1)[0]; if (path) yield path; } for (const run of source.split("}")) { From 0a7864c887821d109b9b2da4257a2f5efaefd51e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:15:45 -0800 Subject: [PATCH 005/255] fix(web): a run finishing in a background window stays unread (#42084) --- .../ThreadVisitWatermark.browser.test.tsx | 48 +++++++++++++++++++ .../components/chat/ThreadVisitWatermark.tsx | 13 +++++ .../client-runtime/src/state/threadVisits.ts | 12 ++++- 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx index 3e35d2fcc0cb9..5283fb8feb3d4 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx @@ -59,6 +59,7 @@ it("records the visit of the next thread at once after switching threads", async mocks.visitRun.mockReturnValue(Effect.void); setShell(threadA, "2026-01-02T00:00:00.000Z"); setShell(threadB, "2026-01-03T00:00:00.000Z"); + using _focus = vi.spyOn(document, "hasFocus").mockReturnValue(true); using _timers = fakeTimers(); vi.setSystemTime(NOW); // A palette pick already sent B's open with its query, so B's visit is a plain watermark advance. @@ -81,3 +82,50 @@ it("records the visit of the next thread at once after switching threads", async // within the throttle window would otherwise keep it unread. expect(visitedThreadIds()).toEqual(["a", "b"]); }); + +it("does not mark a run that finishes in a background window as seen", async () => { + mocks.visitRun.mockReset(); + mocks.visitRun.mockReturnValue(Effect.void); + const threadC: ScopedThreadRef = { environmentId: ENVIRONMENT, threadId: ThreadId.make("c") }; + setShell(threadC, "2026-01-02T00:00:00.000Z"); + let focused = true; + let visibility: DocumentVisibilityState = "visible"; + using _focus = vi.spyOn(document, "hasFocus").mockImplementation(() => focused); + using _visibility = vi + .spyOn(document, "visibilityState", "get") + .mockImplementation(() => visibility); + using _timers = fakeTimers(); + vi.setSystemTime(NOW); + + await using _screen = await render( + + + , + ); + expect(visitedThreadIds()).toEqual(["c"]); + + // The user switches to another app while the run is still working. + focused = false; + visibility = "hidden"; + window.dispatchEvent(new Event("blur")); + document.dispatchEvent(new Event("visibilitychange")); + + const completedAt = "2026-01-03T00:00:00.000Z"; + appAtomRegistry.set(shellAtom(shellKey(threadC)), { + environmentId: threadC.environmentId, + id: threadC.threadId, + updatedAt: completedAt, + lastVisitedAt: "2026-01-02T00:00:00.000Z", + latestRun: { completedAt }, + }); + vi.advanceTimersByTime(60_000); + + expect(visitedThreadIds()).toEqual(["c"]); + + focused = true; + visibility = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + window.dispatchEvent(new Event("focus")); + + expect(visitedThreadIds()).toEqual(["c", "c"]); +}); diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.tsx index a60147aed86af..387c78b16e0a0 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.tsx @@ -2,17 +2,30 @@ import { useAtomMount } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits"; import { type ScopedThreadRef } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { environmentCatalog } from "../../connection/catalog"; +import { getDocumentActivity, subscribeDocumentActivity } from "../../lib/documentActivity"; import { useUiStateStore } from "../../uiStateStore"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; +const isDocumentViewed = () => { + const activity = getDocumentActivity(); + return activity.visible && activity.focused; +}; + +const documentViewedAtom = Atom.make((get) => { + get.addFinalizer(subscribeDocumentActivity(() => get.setSelf(isDocumentViewed()))); + return isDocumentViewed(); +}).pipe(Atom.withLabel("document-viewed")); + const threadVisitTracker = createThreadVisitTracker({ threadShellAtom: environmentThreadShells.threadShellAtom, sessionGenerationAtom: environmentCatalog.sessionGenerationAtom, visit: threadEnvironment.visit, markLocalVisit: (ref, visitedAt) => useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt), + viewingAtom: documentViewedAtom, }); // The visit watermark is the one part of the chat view that follows the diff --git a/packages/client-runtime/src/state/threadVisits.ts b/packages/client-runtime/src/state/threadVisits.ts index 4d71a1960fd67..04bb8322dffe8 100644 --- a/packages/client-runtime/src/state/threadVisits.ts +++ b/packages/client-runtime/src/state/threadVisits.ts @@ -44,10 +44,15 @@ export interface ThreadVisitTrackerOptions { * that keeps its own watermark for them records the visit here instead. */ readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void; + /** + * Whether the user can see the thread right now. While false, nothing is + * recorded; the open and the watermark catch up when it turns true. + */ + readonly viewingAtom?: Atom.Atom; } /** - * While mounted, a tracker counts as the user viewing the thread: mounting it + * While mounted and `viewingAtom` holds, a tracker counts as the user viewing the thread: mounting it * records one open (which also feeds search ranking), and every shell update * after that advances the visit watermark, throttled while a run streams. */ @@ -129,6 +134,7 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { const onShell = (shell: VisitedShell | null) => { clearTimer(); if (shell === null) return; + if (options.viewingAtom && !registry.get(options.viewingAtom)) return; const shellUpdatedAtMs = Date.parse(shell.updatedAt); if (Number.isNaN(shellUpdatedAtMs)) return; @@ -203,6 +209,10 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { get.subscribe(sessionGenerationAtom, () => onShell(registry.get(options.threadShellAtom(ref))), ); + if (options.viewingAtom) + get.subscribe(options.viewingAtom, () => + onShell(registry.get(options.threadShellAtom(ref))), + ); }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`)); }); return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref))); From 15afd7f9c85946e4ac918949984b8a54f85e59cf Mon Sep 17 00:00:00 2001 From: lryoooow <153452545+lryoooow@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:15:58 +0800 Subject: [PATCH 006/255] fix(server): treat remote delegated tasks as app-owned on stop and restart (#42069) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 4 ++- .../RestartContinuation.test.ts | 36 +++++++++++++++++++ .../orchestration-v2/RestartContinuation.ts | 6 +++- apps/server/src/peer/RemoteDelegation.test.ts | 33 ++++++++++++++++- 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ac80a4d957aed..5cd22bc42c1ce 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14654,7 +14654,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const stopDelegatedTasks = command.stopDelegatedTasks === false || !projection.subagents.some( - (task) => task.origin === "app_owned" && task.childThreadId !== null, + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), ) ? Effect.void : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 77af7d2680e05..e86cc9dfd4982 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -1479,3 +1479,39 @@ it.effect("skips restart discovery when no project enables continuation", () => yield* recovery.prepareForShutdown; }), ); + +it("does not continue a settled run whose only open subagent is a remote delegated task", () => { + const base = makeProjection(); + for (const status of ["completed", "waiting"] as const) { + const projection = { + ...base, + runs: [{ ...base.runs[0]!, status }], + providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }], + turnItems: [ + { + id: "item:remote-delegated", + threadId, + runId, + nodeId: NodeId.make("task:remote"), + providerThreadId, + type: "subagent", + subagentId: NodeId.make("task:remote"), + origin: "app_owned", + driver, + providerInstanceId: instanceId, + childThreadId: null, + remoteChild: { + environmentId: "env:box", + threadId: ThreadId.make("thread:remote-child"), + label: "Box", + }, + status: "running", + title: "Remote task", + prompt: "Check remote tests", + result: null, + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + assert.isUndefined(restartContinuationRun(projection, now), status); + } +}); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 21d70c62f920e..806f17c20c197 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -144,7 +144,11 @@ function hasOpenAwaitedWork( const openItem = projection.turnItems.some((item) => { if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting") return false; - if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null) + if ( + item.type === "subagent" && + item.origin === "app_owned" && + (item.childThreadId !== null || item.remoteChild !== undefined) + ) return false; const work = cancelledTurnItemWork(item); return ( diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 3c14fb427fc2e..d075c44ef9ff2 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -37,7 +37,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as TestClock from "effect/testing/TestClock"; -import type * as SqlClient from "effect/sql/SqlClient"; +import * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; @@ -2079,6 +2079,37 @@ it.effect("stopping the parent stops its task there", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("the parent's Stop queues stopping a task that runs only there", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + + yield* delegateToBox(a); + yield* a.orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("command:thread-stop:remote-only"), + threadId: parentThreadId, + reason: "User stopped", + }); + const sql = Context.get(database, SqlClient.SqlClient); + const outbox = yield* sql<{ readonly effect_type: string }>` + SELECT effect_type + FROM orchestration_v2_effect_outbox + WHERE thread_id = ${parentThreadId} + `; + expect(outbox.some((row) => row.effect_type === "delegated-tasks.stop")).toBe(true); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + /** A follower retry schedule the test steps: each failed attempt is offered, then waits for `retry`. */ const steppedRetries = Effect.gen(function* () { const failed = yield* Queue.unbounded(); From 59fe770e01e14c6675783ff14e7370e6841fe0cb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:20:07 -0800 Subject: [PATCH 007/255] fix(web): pull request review drafts survive a reload (#42090) --- .../pullRequestReviewStore.test.ts | 31 ++++- .../pullRequest/pullRequestReviewStore.ts | 119 ++++++++++++------ 2 files changed, 108 insertions(+), 42 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts index 2ba71f34eb080..f3a2cf3d1dc7b 100644 --- a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "vite-plus/test"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { ProjectId } from "@t3tools/contracts"; import { @@ -6,6 +6,7 @@ import { pullRequestReviewKey, usePullRequestReviewStore, } from "./pullRequestReviewStore"; +import { createMemoryStorage } from "../../lib/storage"; function comment(id: string, body = id): PendingReviewComment { return { id, body, path: "src/app.ts", position: { kind: "added", newLine: 1 } }; @@ -62,4 +63,32 @@ describe("pull request review drafts", () => { expect(usePullRequestReviewStore.getState().summaries["review-a"]).toBe("Revised body"); }); + + // regression: #42078 line comments and the summary were lost when the window reloaded + it("keeps unsubmitted line comments and the summary across a reload", async () => { + vi.stubGlobal("localStorage", createMemoryStorage()); + vi.useFakeTimers(); + vi.resetModules(); + try { + const before = await import("./pullRequestReviewStore"); + before.usePullRequestReviewStore.getState().addComment("review-a", comment("drafted")); + before.usePullRequestReviewStore.getState().setSummary("review-a", "Drafted summary"); + await vi.runAllTimersAsync(); + + vi.resetModules(); + const after = await import("./pullRequestReviewStore"); + await vi.runAllTimersAsync(); + + expect(after.usePullRequestReviewStore.getState().drafts["review-a"]).toEqual([ + comment("drafted"), + ]); + expect(after.usePullRequestReviewStore.getState().summaries["review-a"]).toBe( + "Drafted summary", + ); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.ts index d48695ed8f5a2..dd89d149076c1 100644 --- a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts +++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.ts @@ -1,14 +1,16 @@ -import type { PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts"; +import { type PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; -export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string }; +import { resolveStorage } from "../../lib/storage"; +import { randomUUID } from "../../lib/utils"; -// Content-derived ids can collide across comments; use a counter. -let pendingCommentSequence = 0; +export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string }; +// Content-derived ids can collide across comments, and a counter restarts below persisted ids. export function nextPendingReviewCommentId(): string { - pendingCommentSequence += 1; - return `pending-review-comment-${pendingCommentSequence}`; + return `pending-review-comment-${randomUUID()}`; } export function pullRequestReviewKey(reference: PullRequestRef): string { @@ -33,42 +35,77 @@ interface PullRequestReviewStoreState { const EMPTY: ReadonlyArray = []; -export const usePullRequestReviewStore = create()((set) => ({ - drafts: {}, - summaries: {}, - addComment: (key, comment) => - set((state) => ({ - drafts: { ...state.drafts, [key]: [...(state.drafts[key] ?? EMPTY), comment] }, - })), - removeComment: (key, commentId) => - set((state) => { - const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => entry.id !== commentId); - if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - removeComments: (key, commentIds) => - set((state) => { - const submitted = new Set(commentIds); - const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => !submitted.has(entry.id)); - if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - clear: (key) => - set((state) => { - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - setSummary: (key, body) => set((state) => ({ summaries: { ...state.summaries, [key]: body } })), - clearSummary: (key, submittedBody) => - set((state) => { - // Keep summary edits made during submission; the textarea stays editable. - if (state.summaries[key] !== submittedBody) return state; - const { [key]: _removed, ...rest } = state.summaries; - return { summaries: rest }; +const isCommentDraft = Schema.is(PullRequestReviewCommentDraft); +const isPendingComment = (entry: unknown): entry is PendingReviewComment => + isCommentDraft(entry) && typeof (entry as { id?: unknown }).id === "string"; + +type PersistedReviewDrafts = Pick; + +function restoreReviewDrafts(persisted: unknown): PersistedReviewDrafts { + const candidate = persisted as Partial> | null; + const drafts: Record> = {}; + for (const [key, comments] of Object.entries(candidate?.drafts ?? {})) { + const valid = Array.isArray(comments) ? comments.filter(isPendingComment) : []; + if (valid.length > 0) drafts[key] = valid; + } + const summaries: Record = {}; + for (const [key, body] of Object.entries(candidate?.summaries ?? {})) { + if (typeof body === "string") summaries[key] = body; + } + return { drafts, summaries }; +} + +export const usePullRequestReviewStore = create()( + persist( + (set) => ({ + drafts: {}, + summaries: {}, + addComment: (key, comment) => + set((state) => ({ + drafts: { ...state.drafts, [key]: [...(state.drafts[key] ?? EMPTY), comment] }, + })), + removeComment: (key, commentId) => + set((state) => { + const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => entry.id !== commentId); + if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + removeComments: (key, commentIds) => + set((state) => { + const submitted = new Set(commentIds); + const remaining = (state.drafts[key] ?? EMPTY).filter( + (entry) => !submitted.has(entry.id), + ); + if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + clear: (key) => + set((state) => { + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + setSummary: (key, body) => + set((state) => ({ summaries: { ...state.summaries, [key]: body } })), + clearSummary: (key, submittedBody) => + set((state) => { + // Keep summary edits made during submission; the textarea stays editable. + if (state.summaries[key] !== submittedBody) return state; + const { [key]: _removed, ...rest } = state.summaries; + return { summaries: rest }; + }), }), -})); + { + name: "t3code:pull-request-review-drafts:v1", + storage: createJSONStorage(() => + resolveStorage(typeof localStorage !== "undefined" ? localStorage : undefined), + ), + partialize: ({ drafts, summaries }) => ({ drafts, summaries }), + merge: (persisted, current) => ({ ...current, ...restoreReviewDrafts(persisted) }), + }, + ), +); export function usePendingReviewComments( reference: PullRequestRef, From 2cc8e73014d4059752efe717aea960dd5fac8368 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:27:43 -0800 Subject: [PATCH 008/255] fix(server): a message steered in after a self-settle request keeps the thread open (#42092) --- .../ThreadManagementService.test.ts | 55 +++++++++++++++++++ .../ThreadManagementService.ts | 15 +++++ 2 files changed, 70 insertions(+) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 42a8d7eae9cff..631f9089049c0 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -907,6 +907,7 @@ it.effect.each([ ({ thread: { id: threadId, projectId, deletedAt: null }, runs: raced ? [...runs, nextRun] : runs, + turnItems: [], messages: [ { id: MessageId.make("original"), runId, role: "user" as const }, { @@ -1000,6 +1001,60 @@ it.effect.each([ }), ); +// The agent reads a message steered in after it asked to settle and ends on a question. +it.effect.each(["steer", "promoted_queued_to_steer"] as const)( + "settleAfterRun keeps the thread open after a %s read once the settle was requested", + (inputIntent) => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:settle-after-steer"); + const threadId = ThreadId.make("thread:thread-management:settle-after-steer"); + const runId = RunId.make("run:thread-management:settle-after-steer"); + yield* TestClock.adjust(Duration.millis(60_000)); + const dispatched: Array = []; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + streamStoredEventsFrom: () => Stream.empty, + getThreadRecords: () => + Effect.succeed({ + thread: { id: threadId, projectId, deletedAt: null }, + runs: [{ id: runId, ordinal: 1, status: "completed", userMessageId: "original" }], + messages: [ + { id: "original", runId, role: "user" }, + { id: "steered", runId, role: "user" }, + ], + turnItems: [ + { + runId, + type: "user_message", + inputIntent, + status: "completed", + createdAt: "1970-01-01T00:01:30.000Z", + completedAt: "1970-01-01T00:01:30.000Z", + }, + ], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command.type); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + yield* service.settleAfterRun({ projectId, threadId, runId }); + expect(dispatched).toEqual([]); + }), +); + it.effect.each([ { name: "kills the thread's own agent and ends its turn", diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 0c8879cfe18a5..e3bc51179ed10 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1251,6 +1251,21 @@ const make = Effect.gen(function* () { const requestedAt = yield* DateTime.now; const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS }); if (run?.status !== "completed") return; + // A message steered into this run and read after the request supersedes it. + const { turnItems } = yield* getProjectThreadRecords(input, ["turnItems"], { + turnItemRunIds: [run.id], + turnItemTypes: ["user_message"], + }); + if ( + turnItems.some( + (item) => + item.type === "user_message" && + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer") && + item.completedAt !== null && + !DateTime.isLessThan(DateTime.makeUnsafe(item.completedAt), requestedAt), + ) + ) + return; const afterSequence = yield* orchestrator.getThreadEventSequence(input.threadId); const trySettle = Effect.gen(function* () { const sequence = yield* orchestrator.getThreadEventSequence(input.threadId); From 75443857dcaa17913379836245fc50146c56202a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:37:26 -0800 Subject: [PATCH 009/255] fix(web): Settings text typed before Navigation: Back is saved (#42085) --- .../components/AppRouteModal.browser.test.tsx | 28 +++++++++++++++++++ apps/web/src/components/AppRouteModal.tsx | 27 ++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index 814cb87f946b0..429e76b3bab69 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -1,3 +1,4 @@ +import { redirect, useLocation } from "@tanstack/react-router"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -27,6 +28,33 @@ describe("AppRouteModal", () => { expect(onCommit).toHaveBeenCalledWith("Keep titles short"); }); + // regression: #42075. Navigation: Back (mod+[) leaves the Settings route without closing the dialog. + it("commits a focused field when the route goes back", async () => { + const onCommit = vi.fn(); + function SettingsRoute() { + const pathname = useLocation({ select: (location) => location.pathname }); + return pathname.startsWith("/settings") ? ( + + + + ) : null; + } + await using screen = await render(, { router: "/" }); + // The app redirects /settings, and the router skips onBeforeNavigate after a redirect. + screen.router!.routeTree.update({ + beforeLoad: ({ location }: { location: { pathname: string } }) => { + if (location.pathname === "/settings") throw redirect({ to: "/settings/general" }); + }, + }); + await screen.router!.navigate({ to: "/settings" }); + + await page.getByRole("textbox", { name: "Instructions" }).fill("Keep titles short"); + screen.router!.history.back(); + + await expect.element(page.getByRole("dialog", { name: "Settings" })).not.toBeInTheDocument(); + expect(onCommit).toHaveBeenCalledWith("Keep titles short"); + }); + it("returns focus to the opener when Esc closes it", async () => { const opener = ; await using screen = await render(opener, { router: "/" }); diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 1414b198afdc4..95effddf3698c 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -1,7 +1,8 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; -import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useRouter } from "@tanstack/react-router"; +import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; @@ -35,6 +36,22 @@ export function AppRouteModal({ label, children }: { label: string; children: Re // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its // 1.5rem inset is shorter than the strip. const nativeTitlebarHeight = useNativeTitlebarHeight(); + const router = useRouter(); + // Leaving the page without closing (Navigation: Back) unmounts a focused field during a + // commit, when React no longer delivers its blur, so commit-on-blur rows would drop what was + // typed. Blur text fields before the navigation renders; other controls keep their focus. + // Not onBeforeNavigate: the router skips it while a past redirect is still recorded. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- router listener that blurs a field before navigation unmounts it + useEffect( + () => + router.subscribe("onBeforeLoad", ({ pathChanged }) => { + const focused = document.activeElement; + if (pathChanged && focused?.matches("input, textarea, [contenteditable]")) { + blurFocusedWithin(popupRef.current); + } + }), + [router], + ); return ( { @@ -116,6 +132,11 @@ export function AppRouteModal({ label, children }: { label: string; children: Re ); } +function blurFocusedWithin(container: HTMLElement | null) { + const focused = document.activeElement; + if (focused instanceof HTMLElement && container?.contains(focused)) focused.blur(); +} + export function AppRouteModalClose() { const gt = useGT(); return ( From b51399fb3899e35aebbcdd56d1c63eca5672fac2 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 05:38:02 -0600 Subject: [PATCH 010/255] fix(web): a held Esc or a search of spaces no longer closes Settings (#42093) Co-authored-by: Julius Marminge --- ...ngsSidebarNav.composition.browser.test.tsx | 37 +++++++++++++++++++ .../settings/SettingsSidebarNav.tsx | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 338c4ff0fa111..88aafbd568600 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -2,6 +2,7 @@ import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; +import { AppRouteModal } from "../AppRouteModal"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; @@ -12,6 +13,7 @@ vi.mock("./useAvailableSettingsSearchItems", () => ({ ], useHasSecretProvidersEnvironment: () => false, })); +vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); it("ignores composing keys in the search", async () => { await using screen = await render( @@ -45,6 +47,41 @@ it("ignores composing keys in the search", async () => { ); }); +it("Esc clears a search of spaces and a held Esc keeps Settings open", async () => { + await using _screen = await render( + + + + + , + { router: "/settings/general" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + const search = page.getByRole("combobox", { name: "Search settings" }); + await expect.element(settings).toHaveFocus(); + + for (const text of ["theme", " "]) { + await search.fill(text); + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + await act(() => + search.element().dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + repeat: true, + bubbles: true, + cancelable: true, + }), + ), + ); + await expect.element(settings).toHaveAttribute("data-open"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); +}); + function renderNav() { return render( diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 10bc07c123dd8..3c0c506ef9912 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -234,7 +234,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const handleSearchKeyDown = (event: KeyboardEvent) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Escape" && isSearching) { + if (event.key === "Escape" && (query || event.repeat)) { event.preventDefault(); event.stopPropagation(); clearSearch(); From 6f6b9786675968e318b82083888bbe2c428920d4 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 011/255] =?UTF-8?q?fix(web):=20image=20preview=20closes=20?= =?UTF-8?q?with=20an=20=C3=97=20again=20instead=20of=20a=20Back=20button?= =?UTF-8?q?=20(#41963)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 --- .../chat/ExpandedImageDialog.browser.test.tsx | 8 ++------ .../components/chat/ExpandedImageDialog.tsx | 19 ++++++------------- .../chat/QueuedRunsControl.browser.test.tsx | 2 +- .../AttachmentFilePreview.browser.test.tsx | 2 +- apps/web/src/i18n/translations/de.json | 4 ++-- apps/web/src/i18n/translations/en.json | 4 ++-- apps/web/src/i18n/translations/es.json | 4 ++-- apps/web/src/i18n/translations/fr.json | 4 ++-- apps/web/src/i18n/translations/ja.json | 4 ++-- apps/web/src/i18n/translations/ko.json | 4 ++-- apps/web/src/i18n/translations/pt-BR.json | 4 ++-- apps/web/src/i18n/translations/ru.json | 4 ++-- apps/web/src/i18n/translations/sv.json | 4 ++-- apps/web/src/i18n/translations/zh.json | 4 ++-- 14 files changed, 30 insertions(+), 41 deletions(-) diff --git a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx index 915ed5f929538..7287547df71fc 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx @@ -53,9 +53,7 @@ describe("ExpandedImageDialog", () => { await userEvent.keyboard("{Tab}"); await userEvent.keyboard("{Enter}"); } - await expect - .element(page.getByRole("button", { name: "Back, close image preview" })) - .toHaveFocus(); + await expect.element(page.getByRole("button", { name: "Close image preview" })).toHaveFocus(); await userEvent.keyboard("{Escape}"); await expect.element(opener).toHaveFocus(); expect(opener.element().matches(":focus-visible")).toBe(c.focusVisible); @@ -116,9 +114,7 @@ describe("ExpandedImageDialog", () => { expect(onClose).not.toHaveBeenCalled(); // Focus returns to the popup's trigger and opens its tooltip; leave it for a plain control. - ( - screen.getByRole("button", { name: "Back, close image preview" }).element() as HTMLElement - ).focus(); + (screen.getByRole("button", { name: "Close image preview" }).element() as HTMLElement).focus(); await userEvent.keyboard("{Escape}"); await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce()); }); diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 0f278c408d487..0d6f1b812de69 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -1,13 +1,7 @@ import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react"; import { flushSync } from "react-dom"; -import { T, useGT } from "gt-react"; -import { - ArrowLeftIcon, - ChevronLeftIcon, - ChevronRightIcon, - ImageIcon, - TextIcon, -} from "lucide-react"; +import { useGT } from "gt-react"; +import { ChevronLeftIcon, ChevronRightIcon, ImageIcon, TextIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview"; @@ -200,14 +194,13 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ {preview.images.length > 1 && ( ) : null} ); From 4c31da157b6096713c0b790f3b0333fb5c3ea568 Mon Sep 17 00:00:00 2001 From: Georgi Todorov <68182763+jorotodorovv@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:19:18 +0200 Subject: [PATCH 033/255] fix(server): Linux agent CLIs spawned via ProcessLauncher no longer show in Servers (#42151) Co-authored-by: Julius Marminge --- apps/server/src/preview/PortScanner.test.ts | 93 +++++++++++++++++++-- apps/server/src/preview/PortScanner.ts | 50 +++++++++-- apps/server/src/process/ProcessLauncher.ts | 23 ++++- apps/server/src/processRunner.test.ts | 17 ++-- 4 files changed, 155 insertions(+), 28 deletions(-) diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 3bf974e58c373..2f9ea973261f9 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -23,6 +23,7 @@ import { expect, vi } from "vite-plus/test"; import { FetchHttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "./PortScanner.ts"; @@ -1023,12 +1024,17 @@ effectIt.effect.each(["linux", "darwin"] as const)( effectIt.effect("stops only a job's own process group", () => Effect.sync(() => { const serverPid = 100; + const launcherPid = 150; const rows = [ { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job { pid: serverPid, ppid: 10, pgid: 10 }, - { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI + { pid: launcherPid, ppid: serverPid, pgid: 10 }, // Linux ProcessLauncher worker + { pid: 200, ppid: serverPid, pgid: 200 }, // direct agent CLI { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own + { pid: 250, ppid: launcherPid, pgid: 250 }, // launcher-spawned agent CLI (e.g. agy acp) + { pid: 260, ppid: 250, pgid: 250 }, // a server in the launcher-spawned agent CLI's group + { pid: 270, ppid: 250, pgid: 270 }, // a job started by the launcher-spawned agent CLI { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &` { pid: 401, ppid: 400, pgid: 400 }, @@ -1036,10 +1042,11 @@ effectIt.effect("stops only a job's own process group", () => { pid: 600, ppid: 500, pgid: 600 }, // terminal job ]; const table = new Map(rows.map((row) => [row.pid, row])); - expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400); - expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600); - for (const pid of [20, 210, 500, 999]) { - expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull(); + expect(PortScanner.stoppableProcessGroup(table, 401, serverPid, launcherPid)).toBe(400); + expect(PortScanner.stoppableProcessGroup(table, 600, serverPid, launcherPid)).toBe(600); + expect(PortScanner.stoppableProcessGroup(table, 270, serverPid, launcherPid)).toBe(270); + for (const pid of [20, 150, 210, 250, 260, 500, 999]) { + expect(PortScanner.stoppableProcessGroup(table, pid, serverPid, launcherPid)).toBeNull(); } // The tool shell is the command; its `npm run dev &` job only inherited the name. const variables = new Map([ @@ -1055,6 +1062,82 @@ effectIt.effect("stops only a job's own process group", () => }), ); +effectIt.effect( + "excludes Linux agent CLIs spawned through ProcessLauncher (including after restarts) while keeping their dev servers", + () => { + let launcherPid = 9_000; + const firstDevPort = 43_201; + const secondDevPort = 43_202; + let lsofStdout = + `p4300\ncagy\nn127.0.0.1:43200\n` + + `p4301\ncclaude\nn127.0.0.1:43199\n` + + `p4242\ncnode\nn127.0.0.1:${firstDevPort}\n`; + const procFiles: Record = { + "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4300/stat": `4300 (agy) S ${launcherPid} 4300 4300 0`, + "/proc/4301/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-claude\0`, + "/proc/4301/stat": `4301 (claude) S ${process.pid} 4301 4301 0`, + "/proc/4242/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0", + }; + const missing = FileSystem.makeNoop({}); + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: (path) => { + const content = procFiles[path]; + return content === undefined ? missing.readFileString(path) : Effect.succeed(content); + }, + }), + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => + input.command === "lsof" + ? Effect.succeed(processOutput(lsofStdout)) + : Effect.succeed( + processOutput( + `${launcherPid} ${process.pid} ${process.pid}\n` + + `4300 ${launcherPid} 4300\n` + + "4242 4300 4300\n", + ), + ), + }), + Layer.succeed(ProcessLauncher.ProcessLauncher, { + currentPid: Effect.sync(() => launcherPid), + }), + Layer.succeed(HostProcess.Platform, "linux"), + FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))), + ), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + expect(yield* scanner.scan()).toMatchObject([ + { port: firstDevPort, pid: 4242, agent: { threadId: "thread-agy" } }, + ]); + + // Refuses to stop a server sharing the ProcessLauncher-spawned agent CLI's process group. + const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: firstDevPort })); + expect(stop.reason).toBe("shared-group"); + + // After ProcessLauncher restarts with a new helper PID, new agent CLIs are still excluded. + launcherPid = 9_001; + procFiles["/proc/4400/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4400/stat"] = `4400 (agy) S ${launcherPid} 4400 4400 0`; + procFiles["/proc/4401/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4401/stat"] = "4401 (node) S 4400 4401 4401 0"; + lsofStdout = `p4400\ncagy\nn127.0.0.1:43210\np4401\ncnode\nn127.0.0.1:${secondDevPort}\n`; + + expect(yield* scanner.scan()).toMatchObject([ + { port: secondDevPort, pid: 4401, agent: { threadId: "thread-agy-2" } }, + ]); + }).pipe(Effect.provide(layer)); + }, +); + effectIt.effect.each([ { case: "its parent's arguments", diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 794d88e9c6ba2..c48d6a3ad6abe 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -26,6 +26,7 @@ import * as Semaphore from "effect/Semaphore"; import { FetchHttpClient, HttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as WindowsTcpListeners from "../process/windowsTcpListeners.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -388,14 +389,23 @@ const parseProcEnvironThread = (raw: string): ThreadId | null => { }; /** - * A listener with an agent thread in its environment. An agent CLI is a direct child of this - * server and has that environment too, but its own ports are not servers it started. + * A listener with an agent thread in its environment. An agent CLI is spawned directly by this + * server or its Linux process launcher and has that environment too, but its own ports are not + * servers it started. */ interface AgentListener { readonly threadId: ThreadId; readonly isAgentCli: boolean; } +const isServerSpawnedChild = ( + parentPid: number | null, + serverPid: number, + launcherPid?: number, +): boolean => + parentPid !== null && + (parentPid === serverPid || (launcherPid !== undefined && parentPid === launcherPid)); + /** Reads the parent pid from `/proc//stat`, whose command field can hold spaces. */ const parseProcStatParent = (raw: string): number | null => { const parent = Number( @@ -414,6 +424,7 @@ const parseProcStatParent = (raw: string): number | null => { const parsePsEnvironmentThreads = ( raw: string, serverPid: number, + launcherPid?: number, ): ReadonlyMap => { const threads = new Map(); for (const line of raw.split("\n")) { @@ -423,7 +434,10 @@ const parsePsEnvironmentThreads = ( threads.set( Number(match[1]), value && !DEVTOOLS_PORT_ARGUMENT.test(match[3]!) - ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } + ? { + threadId: ThreadId.make(value), + isAgentCli: isServerSpawnedChild(Number(match[2]), serverPid, launcherPid), + } : null, ); } @@ -489,16 +503,19 @@ const parseProcessTable = (raw: string): ReadonlyMap => /** * The process group stopping `pid` signals. Shells with job control and agent tool shells give * every job its own group, so the group is the job. Null when the group also holds this server, - * a direct child of it (agent CLIs and terminal shells), or one of its ancestors. + * a direct child of it or its process launcher (agent CLIs and terminal shells), or one of its + * ancestors. */ export const stoppableProcessGroup = ( table: ReadonlyMap, pid: number, serverPid: number, + launcherPid?: number, ): number | null => { const group = table.get(pid)?.pgid; if (group === undefined || group <= 1) return null; const guarded = new Set([serverPid]); + if (launcherPid !== undefined) guarded.add(launcherPid); for ( let parent = table.get(serverPid)?.ppid; parent !== undefined && parent > 1 && !guarded.has(parent); @@ -507,7 +524,12 @@ export const stoppableProcessGroup = ( guarded.add(parent); } for (const row of table.values()) { - if (row.pgid === group && (guarded.has(row.pid) || row.ppid === serverPid)) return null; + if ( + row.pgid === group && + (guarded.has(row.pid) || isServerSpawnedChild(row.ppid, serverPid, launcherPid)) + ) { + return null; + } } return group; }; @@ -551,6 +573,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0"; const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope); const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const processLauncher = yield* ProcessLauncher.ProcessLauncher; const stateRef = yield* Ref.make({ listeners: new Map(), terminalProcesses: new Map(), @@ -581,6 +604,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ) { const cached = yield* Ref.get(agentThreadsRef); const unread = pids.filter((pid) => !cached.has(pid)); + const launcherPid = unread.length === 0 ? undefined : yield* processLauncher.currentPid; const readProcListener = Effect.fnUntraced(function* (pid: number) { const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe( Effect.map(parseProcEnvironThread), @@ -596,7 +620,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { Effect.map(parseProcStatParent), Effect.orElseSucceed(() => null), ); - return [pid, { threadId, isAgentCli: parent === process.pid }] as const; + return [ + pid, + { threadId, isAgentCli: isServerSpawnedChild(parent, process.pid, launcherPid) }, + ] as const; }); const read: ReadonlyMap = unread.length === 0 @@ -611,7 +638,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() { maxOutputBytes: PS_MAX_OUTPUT_BYTES, }) .pipe( - Effect.map((result) => parsePsEnvironmentThreads(result.stdout, process.pid)), + Effect.map((result) => + parsePsEnvironmentThreads(result.stdout, process.pid, launcherPid), + ), Effect.orElseSucceed(() => { agentScanPending = true; return new Map(); @@ -1242,7 +1271,12 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const table = yield* readProcessTable; // It exited after the scan, so there is nothing left to stop. if (!table.has(input.pid)) return; - const group = stoppableProcessGroup(table, input.pid, process.pid); + const group = stoppableProcessGroup( + table, + input.pid, + process.pid, + yield* processLauncher.currentPid, + ); if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" }); // False when the whole group already exited. const signalGroup = (signal: "SIGTERM" | "SIGKILL") => diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index f62a3c8445da2..397be7c42885d 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -22,6 +22,16 @@ import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorke const READY_TIMEOUT = "10 seconds"; const SPAWN_REPLY_TIMEOUT = "10 seconds"; +/** + * Exposes the active Linux process-launcher helper PID so callers such as port discovery can + * recognize direct children spawned through the helper instead of directly from the server. + */ +export class ProcessLauncher extends Context.Reference<{ + readonly currentPid: Effect.Effect; +}>("t3/process/ProcessLauncher", { + defaultValue: () => ({ currentPid: Effect.undefined }), +}) {} + /** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ class HostedChild extends NodeEvents.EventEmitter @@ -152,7 +162,11 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, ) { const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; - if ((yield* HostProcess.Platform) !== "linux") return fallback; + if ((yield* HostProcess.Platform) !== "linux") { + return Context.make(ChildProcessSpawner.ChildProcessSpawner, fallback).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.undefined }), + ); + } const executablePath = yield* HostProcess.ExecutablePath; const args = yield* launcherArguments(); @@ -368,13 +382,16 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( ); // Start while the server is still small; the launcher's own fork is the last full-size one. launch(); - return ChildProcessSpawner.make((command) => + const spawner = ChildProcessSpawner.make((command) => Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), ); + return Context.make(ChildProcessSpawner.ChildProcessSpawner, spawner).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.sync(() => current?.worker.pid) }), + ); }); /** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ -export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); +export const layer = Layer.effectContext(make()); /** The server's one spawner: memoized, so every build site shares a single launcher. */ export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index bd4ad037defa6..f31d7411c8625 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -592,10 +592,12 @@ describe("ProcessRunner.layer", () => { () => Effect.gen(function* () { const runner = yield* ProcessRunner.ProcessRunner; + const launcher = yield* ProcessLauncher.ProcessLauncher; const parentPid = runner .run({ command: "sh", args: ["-c", "echo $PPID"] }) .pipe(Effect.map((result) => expectHelperPid(result.stdout))); const helper = yield* parentPid; + expect(yield* launcher.currentPid).toBe(helper); process.kill(helper, "SIGSTOP"); const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); const replacement = yield* parentPid; @@ -603,15 +605,11 @@ describe("ProcessRunner.layer", () => { expect(error._tag).toBe("ProcessSpawnError"); expect(replacement).not.toBe(helper); expect(replacement).not.toBe(process.pid); + expect(yield* launcher.currentPid).toBe(replacement); }).pipe( Effect.provide( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provideMerge(Layer.effectContext(ProcessLauncher.make("1 second"))), Layer.provide(NodeServices.layer), ), ), @@ -651,12 +649,7 @@ describe("ProcessRunner.layer", () => { const runner = Context.get( yield* Layer.build( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provide(Layer.effectContext(ProcessLauncher.make("1 second"))), ), ), ProcessRunner.ProcessRunner, From 13b7893ac0a17907ef76d667b2109ca6e37d26ff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:24:05 -0800 Subject: [PATCH 034/255] fix(server): a timed-out provider update no longer force-kills the installer (#42171) --- .../providerMaintenanceRunner.test.ts | 65 ++++++++++++++++++- .../src/provider/providerMaintenanceRunner.ts | 36 ++-------- 2 files changed, 69 insertions(+), 32 deletions(-) diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index fa608d634a384..bdf74046def6d 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -876,7 +876,7 @@ describe("providerMaintenanceRunner", () => { // binary behind that later updates mistake for an install. it.effect.each([ { runFor: "6 minutes", status: "succeeded", message: "Provider updated." }, - { runFor: "31 minutes", status: "failed", message: "Update timed out after 30 minutes." }, + { runFor: "2 hours", status: "succeeded", message: "Provider updated." }, ] as const)("lets a slow installer run for $runFor", ({ runFor, status, message }) => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { @@ -1273,6 +1273,69 @@ describe("providerMaintenanceRunner", () => { }), ); + // npm moves the working package and its bin shims aside before it downloads + // the new version; a forced kill then (taskkill /F on Windows) leaves no CLI. + it.effect("does not force-kill an npm global update still running at the timeout", () => + Effect.gen(function* () { + const kills: Array = []; + let spawns = 0; + const spawned = yield* Deferred.make(); + const respawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed((spawns += 1) === 1 ? spawned : respawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner(registry); + yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(spawned); + yield* TestClock.adjust("31 minutes"); + + assert.deepStrictEqual( + kills, + [], + "the update timeout force-killed npm while it was replacing the installed CLI", + ); + // npm is still replacing the install, so a retry must not start a second installer. + yield* Effect.yieldNow.pipe(Effect.repeat({ times: 20 })); + const retry = yield* Effect.raceFirst( + updater.updateProvider(OPENCODE_DRIVER).pipe( + Effect.flip, + Effect.map((error) => error.reason), + ), + Deferred.await(respawned).pipe(Effect.as("a second installer started")), + ); + assert.include(retry, "already running"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("9.9.9"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ), + ); + }), + ); + it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { const captured: Array<{ readonly command: string; diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index a09bf1ee7dbba..4fb57bb08d3d0 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -15,7 +15,6 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; @@ -41,11 +40,6 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); -// Native updaters (`claude update`) download a ~300 MB binary without printing -// progress, and killing one mid-download leaves a truncated binary that the -// next run treats as installed. Allow a slow connection to finish. -const UPDATE_TIMEOUT_MINUTES = 30; -const UPDATE_TIMEOUT_MS = UPDATE_TIMEOUT_MINUTES * 60_000; const UPDATE_OUTPUT_MAX_BYTES = 10_000; // Sample installer output because every progress update resends the provider list to all clients. const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1); @@ -57,7 +51,6 @@ export interface ProviderMaintenanceCommandResult { readonly stdout: string; readonly stderr: string; readonly exitCode: number | null; - readonly timedOut: boolean; readonly stdoutTruncated: boolean; readonly stderrTruncated: boolean; } @@ -194,31 +187,16 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR stdout: stdout.text, stderr: stderr.text, exitCode: Number(exitCode), - timedOut: false, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, } satisfies ProviderMaintenanceCommandResult; }, ); - return yield* collectCommandResult().pipe( - Effect.scoped, - Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)), - Effect.map((result) => - Option.match(result, { - onSome: (value) => value, - onNone: () => - ({ - stdout: "", - stderr: "", - exitCode: null, - timedOut: true, - stdoutTruncated: false, - stderrTruncated: false, - }) satisfies ProviderMaintenanceCommandResult, - }), - ), - ); + // No timeout: killing an installer mid-install leaves the provider half-replaced (npm has moved + // the old package and its shims aside; `claude update` leaves a truncated binary), and an + // installer still running must keep the update's locks until it exits. + return yield* collectCommandResult().pipe(Effect.scoped); }, ); @@ -282,9 +260,6 @@ function failureReason(result: ProviderMaintenanceCommandResult): string | null } function failureMessage(result: ProviderMaintenanceCommandResult): string { - if (result.timedOut) { - return `Update timed out after ${UPDATE_TIMEOUT_MINUTES} minutes.`; - } const summary = result.exitCode !== null && result.exitCode !== 0 ? `Update command exited with code ${result.exitCode}` @@ -594,12 +569,11 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ), ); const finishedAt = yield* nowIso; - if (result.timedOut || result.exitCode !== 0) { + if (result.exitCode !== 0) { yield* Effect.logWarning("Provider update command failed", { provider, command: describeCommand(command), exitCode: result.exitCode, - timedOut: result.timedOut, output: commandOutput(result), }); return yield* finish( From 480f9f48614a324cdc9dcfdb9fe7c60e8791db84 Mon Sep 17 00:00:00 2001 From: Mihai Crisan <108331599+mihaicrisan04@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:27:36 +0200 Subject: [PATCH 035/255] fix(web): shortcut recorder takes Shift+Esc instead of cancelling (#42187) Co-authored-by: Julius Marminge --- .../KeybindingsSettings.browser.test.tsx | 28 +++++++++++++++++++ .../settings/KeybindingsSettings.tsx | 19 +++++++++---- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx index 8a91ce19d8cd5..bfe09b47aa277 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx @@ -111,6 +111,34 @@ describe("Esc in a shortcut recorder", () => { await userEvent.keyboard("{Escape}"); expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything()); }); + + it.each([ + { name: "existing binding", field: existingField, open: () => activate(existingPill, "click") }, + { + name: "new binding", + field: newField, + open: async () => { + await activate(page.getByRole("button", { name: "Add keybinding" }), "click"); + await activate(newField, "focus"); + }, + }, + ])("records Shift+Esc in the $name field", async ({ field, open }) => { + const onOpenChange = vi.fn(); + await using _screen = await render( + + + Settings + + + , + ); + + await open(); + await userEvent.keyboard("{Shift>}{Escape}{/Shift}"); + + await expect.element(field).toHaveValue("shift+esc"); + expect(onOpenChange).not.toHaveBeenCalled(); + }); }); it("unassigns a default shortcut and restores its condition when one is assigned again", async () => { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 720ec97ca0504..5ea9bc1595560 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -756,6 +756,13 @@ function rowKeybindingTarget(row: KeybindingRow): ServerRemoveKeybindingInput { }; } +// Esc with a modifier is a shortcut to record, not a cancel. +function isBareEscape(event: KeyboardEvent) { + return ( + event.key === "Escape" && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey + ); +} + function useKeybindingRowEditor({ row, allRows, @@ -804,9 +811,9 @@ function useKeybindingRowEditor({ const captureKeybinding = (event: KeyboardEvent) => { if (event.key === "Tab" && !isRecording) return; event.preventDefault(); - if (event.key === "Escape") { - // An unhandled Escape closes the settings page. - event.stopPropagation(); + // An unhandled Escape closes the settings page. + if (event.key === "Escape") event.stopPropagation(); + if (isBareEscape(event)) { const field = event.currentTarget; flushSync(() => setDraft({ @@ -1195,9 +1202,9 @@ function useNewKeybindingDraft({ const captureKeybinding = (event: KeyboardEvent) => { if (event.key === "Tab" && !isRecording) return; event.preventDefault(); - if (event.key === "Escape") { - // An unhandled Escape closes the settings page. - event.stopPropagation(); + // An unhandled Escape closes the settings page. + if (event.key === "Escape") event.stopPropagation(); + if (isBareEscape(event)) { setDraft({ keyDraft: "", isRecording: false }); event.currentTarget.blur(); return; From ae45e00923e026b2edd037bcac8d61be11976b46 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:30:02 -0800 Subject: [PATCH 036/255] fix(pi): Pi exiting while its session is idle ends the session as stopped (#42196) --- .../provider-pi/src/server/adapter.test.ts | 36 +++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 14 +++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index cd9b40f834840..c0ce5cb813421 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2078,6 +2078,42 @@ describe("PiAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("ends the session as stopped when Pi exits while no turn is running", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const adapter = yield* makeAdapter(fake, ""); + const runtime = yield* adapter.openSession({ + threadId: THREAD_ID, + providerSessionId: SESSION_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const statuses: Array<{ status: string; lastError: string | null | undefined }> = []; + const drained = yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type === "provider_session.updated") + statuses.push({ + status: event.providerSession.status, + lastError: event.providerSession.lastError, + }); + }), + ), + Effect.exit, + Effect.forkScoped, + ); + yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* fake.closeStdout; + const exit = yield* Fiber.join(drained); + assert.isTrue(Exit.isSuccess(exit)); + assert.deepEqual(statuses.at(-1), { status: "stopped", lastError: null }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("counts a running Pi for port discovery until its session closes", () => Effect.gen(function* () { const host = yield* ProviderHost.ProviderHost; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 2f3b6f5b49cf7..47af91b6c78e9 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -2883,6 +2883,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.gen(function* () { runtimeRetired = true; const state = threadState; + // Pi ending while nothing is in flight is an idle exit, not a failure. + const idle = + state !== null && + state.activeTurn === null && + pendingWake === null && + piAsyncRuns.size === 0 && + pendingPrompts.size === 0 && + !nativeCompacting && + !registrationInProgress && + rollbackBarrier === null && + extensionStatusReset === null && + pendingPromptResponsesDrained === null; closed = true; if (pendingPromptResponsesDrained !== null) yield* Deferred.fail( @@ -2916,7 +2928,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (unsolicitedActivityDetected) { yield* updateProviderSession("error", PI_UNSOLICITED_ACTIVITY_ERROR); yield* Queue.end(events); - } else if (stopRequested) { + } else if (stopRequested || idle) { yield* updateProviderSession("stopped", null); yield* Queue.end(events); } else { From 43e0b37382dff937c8f376e500a694fe02b6399e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:41:52 -0800 Subject: [PATCH 037/255] fix(web): PR Summary tab keeps its scroll and comment order when you switch right-panel tabs (#42179) --- .../pullRequest/PullRequestDetailPanel.tsx | 10 ++- .../PullRequestSummaryTab.browser.test.tsx | 57 +++++++++++++++++ .../pullRequest/PullRequestSummaryTab.tsx | 62 +++++++++++++++++-- .../pullRequest/holdLinkedNodeInView.ts | 25 ++++++++ 4 files changed, 147 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 729c6b4157876..9bc214851c74e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -339,6 +339,10 @@ function linkedTab(anchor: PullRequestAnchor | null): PullRequestDetailTab | nul } } +// The Summary restores its scroll on remount; a header left expanded would condense over the +// restored position and its scroll compensation would move the view. +const summaryCondensedByScopeKey = new Map(); + export function PullRequestDetailPanel({ environmentId, shortcutsEnabled, @@ -544,7 +548,7 @@ export function PullRequestDetailPanel({ // Each tab restores the condensed state its own scrolling left behind. const [condensedByTab, setCondensedByTab] = useState< Partial> - >({}); + >(() => ({ summary: summaryCondensedByScopeKey.get(tabScopeKey) ?? false })); const condensed = condensedByTab[tab] ?? false; const scrollerByTab = useRef>>({}); // Fresh ref callbacks would detach and reattach every scroller on each render. @@ -2105,7 +2109,9 @@ export function PullRequestDetailPanel({ compensationRef.current = { tab, scroller, target: top - chromeDelta }; next = true; } - if (next !== previous) setCondensedByTab({ ...condensedByTab, [tab]: next }); + if (next === previous) return; + if (tab === "summary") summaryCondensedByScopeKey.set(tabScopeKey, next); + setCondensedByTab({ ...condensedByTab, [tab]: next }); }} > {detailQuery.error && !detail ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx index a9139cc4a6e00..d208e34f934f3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx @@ -273,6 +273,63 @@ it("shows a comment's exact time in the chosen 24-hour clock", async () => { ); }); +it("keeps the chosen comment order when the right panel remounts the tab", async () => { + setup(); + const comment = (id: string, createdAt: string) => ({ + id, + kind: "review-comment" as const, + body: `Remark ${id}`, + author: { login: "reviewer", name: null, avatarUrl: null }, + createdAt, + url: null, + path: null, + reviewState: null, + }); + const value = { + ...detail, + comments: [comment("10", "2026-09-01T10:00:00Z"), comment("11", "2026-09-02T10:00:00Z")], + commentCount: 2, + }; + { + await using screen = await render(value); + await userEvent.click(screen.getByRole("button", { name: "Show oldest comments first" })); + await expect + .element(screen.getByRole("button", { name: "Show newest comments first" })) + .toBeVisible(); + } + // Switching to another right-panel tab unmounts the pull request surface. + await using screen = await render(value); + await expect + .element(screen.getByRole("button", { name: "Show newest comments first" })) + .toBeVisible(); +}); + +it("comes back at the scroll position it left when the right panel remounts the tab", async () => { + setup(); + const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n"); + const value = { ...detail, body, url: "https://github.com/owner/repo/pull/2" }; + const mount = async (shown = value) => { + const container = document.createElement("div"); + container.className = "flex h-[300px]"; + const screen = await renderUi(tab(shown), { container }); + const scroller = container.querySelector("[data-pull-request-summary-scroll]")!; + return Object.assign(screen, { scroller }); + }; + { + await using screen = await mount(); + screen.scroller.scrollTop = 500; + await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500)); + await act(async () => screen.scroller.dispatchEvent(new Event("scroll"))); + } + // The tab can come back before the content that reached that position has loaded. + await using screen = await mount({ ...value, body: "Paragraph 0" }); + await screen.rerender(tab(value)); + await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500)); + await screen.unmount(); + await using again = await mount(); + expect(again.scroller.scrollTop).toBe(500); +}); + it("scrolls from the keyboard after a click inside it", async () => { setup(); const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n"); diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 1f409d282ecc3..61ccfd23e0fa8 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -1,6 +1,6 @@ import { pullRequestCommentPreview } from "./pullRequestMarkdown.logic"; import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor"; -import { holdLinkedNodeInView } from "./holdLinkedNodeInView"; +import { holdLinkedNodeInView, holdScrollTop } from "./holdLinkedNodeInView"; import { useAtomValue } from "@effect/atom-react"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { useAtomCommand } from "~/state/use-atom-command"; @@ -25,7 +25,14 @@ import { } from "lucide-react"; import * as Schema from "effect/Schema"; import { msg, T, useGT, useMessages, Var } from "gt-react"; -import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react"; +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from "react"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -461,6 +468,14 @@ export function PullRequestSection({ const COMMENT_PAGE = 10; +interface SummaryView { + readonly order: "newest" | "oldest"; + readonly shown: number; + readonly scrollTop: number; +} +// Session-only: switching right-panel tabs unmounts the Summary, which comes back as it was left. +const summaryViewByScopeKey = new Map(); + const COMMENT_FILTER_STORAGE_KEY = "t3code:pull-request-comment-filter:v1"; const CommentFilterSchema = Schema.Struct({ bots: Schema.Boolean, resolved: Schema.Boolean }); const DEFAULT_COMMENT_FILTER: typeof CommentFilterSchema.Type = { bots: false, resolved: false }; @@ -510,7 +525,23 @@ export function PullRequestSummaryTab({ const fixCheckLabel = requestedFixCheckLabel ?? gt("Fix", { $context: "verb, fix a review finding" }); const terminology = sourceControlClients.get(detail.provider).changeRequest; - const [shown, setShown] = useState({ url: detail.url, count: COMMENT_PAGE }); + const viewKey = `${environmentId}:${detail.url}`; + const rememberView = (patch: Partial) => { + const view = summaryViewByScopeKey.get(viewKey) ?? { + order: "newest", + shown: COMMENT_PAGE, + scrollTop: 0, + }; + summaryViewByScopeKey.set(viewKey, { ...view, ...patch }); + }; + const [shown, setShownState] = useState(() => ({ + url: detail.url, + count: summaryViewByScopeKey.get(viewKey)?.shown ?? COMMENT_PAGE, + })); + const setShown = (next: { url: string; count: number }) => { + setShownState(next); + rememberView({ shown: next.count }); + }; const shownConversations = shown.url === detail.url ? shown.count : COMMENT_PAGE; const [commentFilter, setCommentFilter] = useLocalStorage( COMMENT_FILTER_STORAGE_KEY, @@ -536,7 +567,9 @@ export function PullRequestSummaryTab({ filteredItems, shownConversations, ); - const [commentOrder, setCommentOrder] = useState<"newest" | "oldest">("newest"); + const [commentOrder, setCommentOrder] = useState( + () => summaryViewByScopeKey.get(viewKey)?.order ?? "newest", + ); const visibleItems = orderPullRequestComments(recentItems, commentOrder); const showOldestCommentsButton = hiddenConversationCount > 0 ? ( @@ -637,6 +670,8 @@ export function PullRequestSummaryTab({ } } const stopHolding = useRef<(() => void) | null>(null); + // A restore clamped by content still loading must not overwrite the saved position. + const restoringScroll = useRef(false); const revealSummary = useEffectEvent(() => { const root = scrollRef.current; if (revealUrl === undefined || !root) return; @@ -674,6 +709,16 @@ export function PullRequestSummaryTab({ revealSummary(); // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries once the description markdown renders, including after its editor closes }, [revealUrl, description, checksReveals, descriptionReveals, editingDescription]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- puts a remounted Summary back at the scroll position it left, before paint + useLayoutEffect(() => { + const scrollTop = summaryViewByScopeKey.get(viewKey)?.scrollTop ?? 0; + if (!scrollRef.current || scrollTop === 0) return; + restoringScroll.current = true; + stopHolding.current = holdScrollTop(scrollRef.current, scrollTop, () => { + restoringScroll.current = false; + }); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- restores once per mount + }, []); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab useEffect(() => () => stopHolding.current?.(), []); // Checkbox ticks and the editor share one draft, so each starts from the other's latest body. @@ -871,6 +916,9 @@ export function PullRequestSummaryTab({ scrollRef.current = node; scrollerRef(node); }} + onScroll={(event) => { + if (!restoringScroll.current) rememberView({ scrollTop: event.currentTarget.scrollTop }); + }} tabIndex={-1} data-workspace-focus-default className="h-full overflow-y-auto outline-none" @@ -1152,7 +1200,11 @@ export function PullRequestSummaryTab({ ? gt("Show oldest comments first") : gt("Show newest comments first") } - onClick={() => setCommentOrder((value) => (value === "newest" ? "oldest" : "newest"))} + onClick={() => { + const order = commentOrder === "newest" ? "oldest" : "newest"; + setCommentOrder(order); + rememberView({ order }); + }} > {commentOrder === "newest" ? gt("Newest first") : gt("Oldest first")} diff --git a/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts b/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts index 4261cb2fb0da8..27d17966cc604 100644 --- a/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts +++ b/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts @@ -37,3 +37,28 @@ export function holdLinkedNodeInView( } return stop; } + +/** + * Keeps the scroller at `scrollTop` while content loads in under it, until the user scrolls or the + * returned stop runs. A remounted tab can render before the content that reached that offset. + */ +export function holdScrollTop( + scroller: HTMLElement, + scrollTop: number, + onStop: () => void, +): () => void { + const controller = new AbortController(); + const stop = () => { + unobserve(); + controller.abort(); + onStop(); + }; + const unobserve = observeResize([...scroller.children], () => { + scroller.scrollTop = scrollTop; + }); + for (const type of USER_SCROLL_INTENT) { + scroller.addEventListener(type, stop, { passive: true, signal: controller.signal }); + } + scroller.scrollTop = scrollTop; + return stop; +} From 53294d5a4fe0df2c34f9e43b584280793395173a Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Tue, 24 Nov 2026 20:14:40 +0530 Subject: [PATCH 038/255] fix(server): switchRef keeps the real branch name for remotes containing slashes (#42193) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 44 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 30 +++++++++++-- 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 7a099e5d4ecdf..29484e835fed7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6976,6 +6976,50 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "tracks the real branch name and refuses local collisions for remotes containing slashes", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const slashedRemote = yield* makeTmpDir("git-remote-slashed-"); + yield* git(slashedRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "team/origin", slashedRemote]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/feature/demo"]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/conflict"]); + yield* git(cwd, ["fetch", "team/origin"]); + + const driver = yield* GitVcsDriver.GitVcsDriver; + const switched = yield* driver.switchRef({ cwd, refName: "team/origin/feature/demo" }); + + assert.equal(switched.refName, "feature/demo"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/demo"); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(upstream)", "refs/heads/feature/demo"]), + "refs/remotes/team/origin/feature/demo", + ); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + + yield* git(cwd, ["checkout", "--no-track", "-b", "conflict"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "Local conflict work"]); + yield* git(cwd, ["checkout", initialBranch]); + + const conflicted = yield* driver + .switchRef({ cwd, refName: "team/origin/conflict" }) + .pipe(Effect.flip); + + assert.equal(conflicted.reason, "branch_already_exists"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 53c5f51d7166f..5fcddc70e144a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -6902,9 +6902,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) : null; - const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName); + const localTrackedBranchCandidate = + remoteExists && !localInputExists && !localTrackingBranch + ? yield* executeGit("GitVcsDriver.switchRef.remoteNames", input.cwd, ["remote"], { + timeoutMs: 5_000, + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => { + const remoteNames = result.exitCode === 0 ? parseRemoteNames(result.stdout) : []; + return ( + parseRemoteRefWithRemoteNames(input.refName, remoteNames)?.branchName ?? + deriveLocalBranchNameFromRemoteRef(input.refName) + ); + }), + ) + : null; const localTrackedBranchTargetExists = - remoteExists && !localInputExists && !localTrackingBranch && localTrackedBranchCandidate + localTrackedBranchCandidate !== null ? yield* executeGit( "GitVcsDriver.switchRef.localTrackedBranchTargetExists", input.cwd, @@ -6917,7 +6931,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : false; const newTrackingBranch = - !localInputExists && remoteExists && !localTrackingBranch && !localTrackedBranchTargetExists + localTrackedBranchCandidate !== null && !localTrackedBranchTargetExists ? localTrackedBranchCandidate : null; @@ -6926,7 +6940,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : newTrackingBranch ? ["checkout", newTrackingBranch] : remoteExists && !localTrackingBranch - ? ["checkout", "--track", input.refName] + ? localTrackedBranchCandidate + ? [ + "checkout", + "--track", + "-b", + localTrackedBranchCandidate, + `refs/remotes/${input.refName}`, + ] + : ["checkout", "--track", input.refName] : remoteExists && localTrackingBranch ? ["checkout", localTrackingBranch] : ["checkout", input.refName]; From f8d095151c82cd5dee38922e9aa11bdd31e73ec3 Mon Sep 17 00:00:00 2001 From: VulpesZerda <121235398+VulpesZerda27@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:51:12 +0100 Subject: [PATCH 039/255] fix(desktop): SnapShot setup edits Hyprland Lua bindings with a return inside a function (#42145) Co-authored-by: Julius Marminge --- .../src/snapShot/captureConfigEdit.test.ts | 12 ++++++++++++ apps/desktop/src/snapShot/captureConfigEdit.ts | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/snapShot/captureConfigEdit.test.ts b/apps/desktop/src/snapShot/captureConfigEdit.test.ts index 9db407be961d2..1923aba98a3e9 100644 --- a/apps/desktop/src/snapShot/captureConfigEdit.test.ts +++ b/apps/desktop/src/snapShot/captureConfigEdit.test.ts @@ -104,10 +104,22 @@ describe("Hyprland capture config edits", () => { }); it.each([ "return {}", + "local M = {}\n return M", '--[[\nhl.bind("CTRL + SHIFT + 2", hl.dsp.global("com.t3tools.T3Code:capture-window"))\n]]', ])("does not guess how to edit complex Lua", (source) => { expect(() => editCaptureConfig(source, "hyprland-lua", app, "install")).toThrow("manual edit"); }); + it("edits Lua that returns early inside a function", () => { + const before = + 'local function sync(window)\n if window == nil then\n return\n end\n hl.unbind("SUPER + Q")\nend\nhl.on("window.active", sync)\n'; + const added = editCaptureConfig(before, "hyprland-lua", app, "install"); + expect(added.after).toBe( + `${before}\n${captureConfigBinding("hyprland-lua", app, "Ctrl+Shift+2")}\n`, + ); + expect(editCaptureConfig(added.after, "hyprland-lua", app, "remove").after.trim()).toBe( + before.trim(), + ); + }); it.each(['Ctrl+"\nexec', "Ctrl+;", "2", "Mod+2"])( "rejects unsafe or ambiguous keys: %s", (keys) => { diff --git a/apps/desktop/src/snapShot/captureConfigEdit.ts b/apps/desktop/src/snapShot/captureConfigEdit.ts index 7de20719b3aa9..25ea665aeb1aa 100644 --- a/apps/desktop/src/snapShot/captureConfigEdit.ts +++ b/apps/desktop/src/snapShot/captureConfigEdit.ts @@ -137,6 +137,19 @@ function removeNodes(source: string, ranges: { start: number; end: number }[]) { return result; } +// A top-level return must end the chunk, so appending a binding after it would break the config. +// Block depth, not indentation, decides scope. Long brackets are rejected before this runs. +function luaTopLevelReturn(source: string) { + const code = source.replace(/--[^\n]*|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'/g, " "); + let depth = 0; + for (const [word] of code.matchAll(/\b(?:function|if|do|repeat|end|until|return)\b/g)) { + if (word === "return" && depth === 0) return true; + if (word === "end" || word === "until") depth--; + else if (word !== "return") depth++; + } + return false; +} + export function editCaptureConfig( source: string, format: CaptureConfigFormat, @@ -144,7 +157,7 @@ export function editCaptureConfig( operation: "install" | "remove", requestedKeys?: string, ) { - if (format === "hyprland-lua" && (/^\s*return\b/m.test(source) || /\[=*\[/.test(source))) + if (format === "hyprland-lua" && (/\[=*\[/.test(source) || luaTopLevelReturn(source))) throw new Error( "This Lua config needs a manual edit. Choose your bindings file or use manual setup in Advanced.", ); From fbe50337ea5068c5f1405b9512b4292b514fa22a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:52:23 -0800 Subject: [PATCH 040/255] fix(server): a task delegated from a linked machine settles there once its work is done (#42210) --- .../ThreadSettlementService.test.ts | 51 +++++++++++++++++++ .../ThreadSettlementService.ts | 12 +++-- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index be8a300872944..ed9b6b8355f16 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -3,6 +3,7 @@ import { assert, describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import { DEFAULT_SERVER_SETTINGS, + EnvironmentId, GitManagerError, ProjectId, EventId, @@ -1284,6 +1285,56 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(projectionStoreSql)), ); + it.effect( + "settles a finished task delegated from a linked environment, which has no parent here", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const store = yield* ProjectionStore.ProjectionStoreV2; + const delegated: OrchestrationV2AppThread = { + ...appThread("delegated-here", null), + branch: "feature", + delegatedFrom: { + environmentId: EnvironmentId.make("environment-elsewhere"), + threadId: ThreadId.make("parent-elsewhere"), + title: "Parent", + }, + }; + const ordinary = { ...appThread("ordinary", null), branch: "feature" }; + for (const thread of [delegated, ordinary]) { + yield* store.apply({ + type: "thread.created", + id: EventId.make(`created:${thread.id}`), + threadId: thread.id, + occurredAt: thread.createdAt, + payload: thread, + }); + } + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([]), + projections: store, + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: null, + sidebarAutoSettleOnMerge: false, + }, + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + yield* service.drain; + expect(yield* Ref.get(fixture.commands)).toEqual([ + expect.objectContaining({ + type: "thread.auto-settle", + threadId: delegated.id, + snapshotAt: delegated.updatedAt, + }), + ]); + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(projectionStoreSql)), + ); + it.effect( "coalesces bulk cleanup wakes and still drains children discovered during a sweep", () => diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 0a4cb5e9c1ec7..2884600ceef68 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -8,6 +8,7 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, + isDelegatedAppThread, isOrchestrationV2WorkActive, type ThreadId, type OrchestrationV2DomainEvent, @@ -381,17 +382,18 @@ export const make = Effect.gen(function* () { // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter( (thread) => - (automaticSettlementEnabled || thread.lineage.relationshipToParent === "subagent") && + (automaticSettlementEnabled || isDelegatedAppThread(thread)) && isAutoSettlementCandidate(thread, nowMs), ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. const settleThread = Effect.fnUntraced( function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) { - if (thread.lineage.relationshipToParent === "subagent") { + if (isDelegatedAppThread(thread)) { if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null; - // The store returns a subagent only once its parent is done, so it - // settles with the parent and never runs its own lookup. + // The store returns a subagent only once its parent is done, so it settles with the + // parent. A task delegated from a linked environment has no parent here, so it settles + // once its own work is done. Neither runs its own lookup. const uuid = yield* random.uuidV4(); yield* orchestrator.dispatch({ type: "thread.auto-settle", @@ -445,7 +447,7 @@ export const make = Effect.gen(function* () { const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { - if (thread.lineage.relationshipToParent === "subagent") return settleThread(thread, null); + if (isDelegatedAppThread(thread)) return settleThread(thread, null); const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; // Skip no-op decisions; actual settlement still reads fresh settings before dispatch. const settledAt = resolveAutoSettlementAt({ From c6e32aa4ebe0364eaf226003d40d54546d89f418 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 08:57:52 -0600 Subject: [PATCH 041/255] fix(cli): trace summary prints the correct date at a millisecond boundary (#42208) Co-authored-by: Julius Marminge --- apps/server/src/cli/trace.test.ts | 23 +++++++++++++++++++++++ apps/server/src/cli/trace.ts | 20 +++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/apps/server/src/cli/trace.test.ts b/apps/server/src/cli/trace.test.ts index 521f06a70e48a..054653a1aab39 100644 --- a/apps/server/src/cli/trace.test.ts +++ b/apps/server/src/cli/trace.test.ts @@ -72,3 +72,26 @@ it("prints durations that round up to a second in seconds", () => { .find((line) => line.startsWith("rpc")); assert.deepStrictEqual(row?.trim().split(/\s+/).slice(3, 6), ["999ms", "1s", "1s"]); }); + +it("keeps sub-millisecond windows and rates without rounding printed dates", () => { + const summarizer = makeTraceSpanSummary(1_795_478_399_998.25); + ["1795478399998000000", "1795478399998999950", "1795478399999999999"] + .map((endTimeUnixNano) => JSON.stringify({ name: "rpc", durationMs: 1, endTimeUnixNano })) + .forEach(summarizer.addLine); + const summary = summarizer.finish(); + const formatted = formatTraceSummary(summary, 25); + const row = formatted.split("\n").find((line) => line.startsWith("rpc")); + + assert.strictEqual(summary.spanCount, 2); + assert.strictEqual(row?.trim().split(/\s+/)[2], "120000.0"); + assert.include(formatted, "from 2026-11-23T23:59:59.998Z to 2026-11-23T23:59:59.999Z"); +}); + +it("prints end times in other numeric spellings as before", () => { + const summarizer = makeTraceSpanSummary(); + summarizer.addLine( + JSON.stringify({ name: "rpc", durationMs: 1, endTimeUnixNano: "1795478400001e6" }), + ); + + assert.include(formatTraceSummary(summarizer.finish(), 25), "to 2026-11-24T00:00:00.001Z"); +}); diff --git a/apps/server/src/cli/trace.ts b/apps/server/src/cli/trace.ts index b2463dab0d98d..7ebcb755ddfd4 100644 --- a/apps/server/src/cli/trace.ts +++ b/apps/server/src/cli/trace.ts @@ -20,7 +20,7 @@ const decodeTraceSpanLine = Schema.decodeUnknownOption( Schema.Struct({ name: Schema.String, durationMs: Schema.Finite, - endTimeUnixNano: Schema.FiniteFromString, + endTimeUnixNano: Schema.Union([Schema.BigIntFromString, Schema.FiniteFromString]), exit: Schema.optional(Schema.Struct({ _tag: Schema.String })), // OTLP errors use code 2; interrupts carry effect.fiber.interrupted, or code 1 with Interrupted before Effect 4.0.2. status: Schema.optional( @@ -42,6 +42,8 @@ export function makeTraceSpanSummary(sinceMs = -Infinity) { let skippedLineCount = 0; let firstEndMs = Infinity; let lastEndMs = -Infinity; + let firstPrintedMs = Infinity; + let lastPrintedMs = -Infinity; const addLine = (line: string) => { if (line.trim().length === 0) return; @@ -50,7 +52,7 @@ export function makeTraceSpanSummary(sinceMs = -Infinity) { skippedLineCount += 1; return; } - const endMs = span.endTimeUnixNano / 1_000_000; + const endMs = Number(span.endTimeUnixNano) / 1_000_000; // The report prints end times as dates, so skip ones outside the Date range. if (Option.isNone(DateTime.make(endMs))) { skippedLineCount += 1; @@ -61,6 +63,11 @@ export function makeTraceSpanSummary(sinceMs = -Infinity) { spanCount += 1; firstEndMs = Math.min(firstEndMs, endMs); lastEndMs = Math.max(lastEndMs, endMs); + // Printed dates use the exact value while float bounds feed the rate. + const printedMs = + typeof span.endTimeUnixNano === "bigint" ? Number(span.endTimeUnixNano / 1_000_000n) : endMs; + firstPrintedMs = Math.min(firstPrintedMs, printedMs); + lastPrintedMs = Math.max(lastPrintedMs, printedMs); const stats = byName.get(span.name) ?? { durations: [], interrupted: 0, failures: 0 }; stats.durations.push(span.durationMs); if ( @@ -93,7 +100,14 @@ export function makeTraceSpanSummary(sinceMs = -Infinity) { }) .toSorted((left, right) => right.count - left.count || left.name.localeCompare(right.name)); - return { spanCount, skippedLineCount, firstEndMs, lastEndMs, minutes, spans }; + return { + spanCount, + skippedLineCount, + firstEndMs: firstPrintedMs, + lastEndMs: lastPrintedMs, + minutes, + spans, + }; }; return { addLine, finish }; From 43cd52fc3f818b3175f421f6b42349400b3a9979 Mon Sep 17 00:00:00 2001 From: Kyros Abas Date: Tue, 24 Nov 2026 23:00:11 +0800 Subject: [PATCH 042/255] fix(server): OpenDocument attachments no longer show agents the values a merge hides (#42202) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 4 ++++ .../src/provider/userInputAttachments.test.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 9ecef186efe77..9ec248ce3bfa2 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -291,7 +291,9 @@ function odfValue(cell: XmlNode): string { return attr("value"); } } +const covered = (cell: XmlNode) => cell.name === "covered-table-cell"; function hasCellText(cell: XmlNode): boolean { + if (covered(cell)) return false; if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true; // Space markers can have enormous repeat counts; emptiness never requires expanding them. if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false; @@ -316,6 +318,8 @@ function* table(node: XmlNode): Generator { for (let i = 0; i < count; i++) { if (column >= 512) throw new Truncation("Column limit"); if (column++) yield "\t"; + // LibreOffice hides the contents a merge covers; the cell still holds its column. + if (covered(cell)) continue; yield CELL_START; yield* paragraphs(cell); yield { fallback: odfValue(cell) }; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 22c6f05141e83..78f7e4d176497 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1253,6 +1253,19 @@ describe("question answer paths", () => { }, expected: ["## Sheet: Cargo", "Violet\t19\t27"], }, + { + ext: "ods", + parts: { + "content.xml": + '' + + 'WideAfterTail' + + 'BelowNext' + + "Only" + + "Last", + }, + expected: ["## Sheet: Merged", "Wide\t\t\tAfter\n\t\t\tNext\nLast"], + absent: ["4242", "Gone", "Tail", "Below", "Only", "After\t"], + }, { ext: "ods", bounded: true, From ccdafe1f611a82f5136c6ffd0f1ff1d0ebc63fe9 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 09:03:15 -0600 Subject: [PATCH 043/255] fix(web): held or modified Backspace no longer leaves a Command Palette submenu (#42205) Co-authored-by: Julius Marminge --- .../CommandPalette.browser.test.tsx | 36 +++++++++++++++++++ apps/web/src/components/CommandPalette.tsx | 13 +++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index f29feada58e0a..9f73536295c8a 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -308,4 +308,40 @@ describe("CommandPalette open intents", () => { }), ); }); + + it("leaves a submenu only on a fresh, unmodified Backspace", async () => { + setup({ projects: [makeProject("Acme"), makeProject("Beta")] }); + await using _screen = await render({null}); + + openCommandPalette({}); + const rootInput = page.getByPlaceholder("Search commands, projects, and threads..."); + await expect.element(rootInput).toHaveFocus(); + await userEvent.keyboard("{ArrowDown}"); + await expect + .element(page.getByRole("option", { name: /^New thread in\.\.\./ })) + .toHaveAttribute("data-highlighted"); + await userEvent.keyboard("{Enter}"); + + const submenuInput = page.getByPlaceholder("Search..."); + await expect.element(submenuInput).toHaveFocus(); + + for (const init of [ + { repeat: true }, + { ctrlKey: true }, + { isComposing: true }, + ] satisfies ReadonlyArray) { + const event = new KeyboardEvent("keydown", { + key: "Backspace", + bubbles: true, + cancelable: true, + ...init, + }); + await act(() => submenuInput.element().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(false); + await expect.element(submenuInput).toBeVisible(); + } + + await userEvent.keyboard("{Backspace}"); + await expect.element(rootInput).toHaveFocus(); + }); }); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 4610ef7542890..1599ff3819c25 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2787,14 +2787,21 @@ function OpenCommandPaletteDialog(props: { return; } - if (event.key === "Backspace" && query === "" && isSubmenu) { + if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; + + if ( + event.key === "Backspace" && + query === "" && + isSubmenu && + !event.repeat && + !event.nativeEvent.isComposing && + event.keyCode !== 229 + ) { event.preventDefault(); popView(); return; } - if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; - if (event.key === "Tab" && isBrowsing && !relativePathNeedsActiveProject) { if (event.nativeEvent.isComposing || event.keyCode === 229) return; (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); From e9b227b0212d5e3e61d8da02567e23ecb69284ec Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 07:04:01 -0800 Subject: [PATCH 044/255] fix(web): typing / or $ in the composer no longer waits for the suggestion menu to render (#42183) --- apps/web/src/components/chat/ChatComposer.tsx | 36 ++++++++++--------- .../chat/ComposerCommandMenuLayer.tsx | 11 +++++- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b022fff63a495..7a03418ea384d 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -283,7 +283,10 @@ import { usePanelAnimationSettings } from "../../panelAnimations"; import { readEnvironmentScope, readPreparedConnection } from "../../state/session"; import type { ReviewCommentContext } from "../../reviewCommentContext"; import { useComposerRestingTransition } from "./useComposerRestingTransition"; -import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer"; +import { + ComposerCommandMenuLayer, + DeferredComposerCommandMenuLayer, +} from "./ComposerCommandMenuLayer"; import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout"; import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; import { useComposerProviderModel } from "./useComposerProviderModel"; @@ -3873,21 +3876,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : composerMenuEmptyState : ""} - {composerSuggestionsVisible && ( - - - - )} + + + {!isComposerCollapsedMobile && activeEditingQueuedAttachments !== null && diff --git a/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx b/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx index e8f76e3a381c9..8479573baeefb 100644 --- a/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx @@ -1,4 +1,4 @@ -import { type ReactNode, useLayoutEffect, useState } from "react"; +import { type ReactNode, useDeferredValue, useLayoutEffect, useState } from "react"; import { createPortal } from "react-dom"; import { observeResize } from "~/lib/observeResize"; @@ -18,6 +18,15 @@ function composerCommandMenuPositionsEqual( ); } +/** Mounts the layer one deferred render after `open` turns true, so the keystroke that opened it paints first. */ +export function DeferredComposerCommandMenuLayer({ + open, + ...props +}: Parameters[0] & { open: boolean }) { + const mounted = useDeferredValue(open, false); + return open && mounted ? : null; +} + export function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode; From 7105792176869f9e6b03be723c605b452e511275 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 24 Nov 2026 17:07:28 +0200 Subject: [PATCH 045/255] fix(web): notebook previews show a progress bar's last frame (#42201) Co-authored-by: Julius Marminge --- .../src/components/files/FilePreviewPanel.test.ts | 6 ++++++ .../components/files/extendedDocumentPreview.ts | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index d4ba382837981..6de12a7863475 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -389,6 +389,11 @@ Third}`; { data: { "text/html": "", "text/plain": "\u001b[1mstring fallback\u001b[0m" } }, { data: { "text/html": " ", "text/plain": "space fallback" } }, { output_type: "stream", text: ["\u001b[", "32m42\u001b[0m\n"] }, + { + output_type: "stream", + name: "stderr", + text: ["\r 10%|# |", "\r100%|##########|\n", "done\r\n", "🚀 ready\rX\n"], + }, { data: { "text/html": ["Results"], "text/plain": ["Results"] } }, ], }, @@ -409,6 +414,7 @@ Third}`; { kind: "text", text: "string fallback" }, { kind: "text", text: "space fallback" }, { kind: "text", text: "42\n" }, + { kind: "text", text: "100%|##########|\ndone\nX ready\n" }, { kind: "html", text: "Results" }, ], }, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index f2e959286fee4..cd9b86f32f727 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -498,6 +498,15 @@ function tracebackLines(value: unknown): unknown { index && !frames[index - 1]!.endsWith("\n") ? `\n${frame}` : frame, ); } +// tqdm redraws a progress bar after a carriage return; JupyterLab shows only what the last +// redraws leave on the line. Walking the frames from the last keeps this linear. +function lastFrame(line: string): string { + let row = ""; + for (const frame of line.split("\r").reverse()) + // A cut through a surrogate pair blanks the glyph's other half, as a terminal does. + if (frame.length > row.length) row += frame.slice(row.length).replace(/^[\udc00-\udfff]/u, " "); + return row; +} export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult { if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "notebook-too-large" }); const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))); @@ -526,9 +535,13 @@ export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult { } const html = notebookText(data["text/html"]); if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html }; - const text = terminalOutputPlainText( + const plain = terminalOutputPlainText( notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), ); + const text = + output.output_type === "stream" && /\r(?!\n)/.test(plain) + ? plain.replaceAll("\r\n", "\n").split("\n").map(lastFrame).join("\n") + : plain; if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text }; const summary = [output.ename, output.evalue] .filter((part) => typeof part === "string") From 0e34fe98f2bcf76f0f611d4dc34c078728bc8b7f Mon Sep 17 00:00:00 2001 From: m Date: Tue, 24 Nov 2026 16:08:37 +0100 Subject: [PATCH 046/255] fix(mobile): dictation keeps its floating controls when a question hides the composer (#42132) Co-authored-by: Julius Marminge --- .../features/issues/IssueCommentComposer.tsx | 9 ++- .../src/features/threads/ThreadComposer.tsx | 1 + .../useVoiceInputController.test.tsx | 80 +++++++++++++++++++ .../voice-input/useVoiceInputController.ts | 5 +- apps/mobile/vite.config.ts | 1 + 5 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 901dee46152a4..46082efd89dec 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -73,6 +73,7 @@ export function IssueCommentComposer(props: { readDraftMessage: () => latestDraft.current, selection, disabled: props.blocked !== null, + hidden: props.blocked !== null, onChangeDraftMessage: changeDraft, onChangeSelection: setSelection, }); @@ -134,10 +135,6 @@ export function IssueCommentComposer(props: { paddingVertical: chrome.paddingVertical, }} > - {props.blocked !== null ? ( ) : ( <> + getComposerDraftSnapshot(composerDraftKey).text, selection: composerMenu.selection, + hidden: props.hidden, onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text), onChangeSelection: composerMenu.onSelectionChange, }); diff --git a/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx b/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx new file mode 100644 index 0000000000000..f6e5ae62836c3 --- /dev/null +++ b/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx @@ -0,0 +1,80 @@ +import { act, useEffect, useSyncExternalStore } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const harness = vi.hoisted(() => ({ + session: null as import("./voiceInputSession").VoiceInputSession | null, +})); + +vi.mock("@react-navigation/native", () => ({ + useFocusEffect: (callback: () => void | (() => void)) => useEffect(callback, [callback]), +})); +vi.mock("./VoiceInputProvider", () => ({ + useGlobalVoiceInput: () => { + const session = harness.session!; + const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot); + return { ...snapshot, isAvailable: true, isBusy: false, session }; + }, +})); + +import { useVoiceInputController } from "./useVoiceInputController"; +import { VoiceInputSession } from "./voiceInputSession"; + +function Composer(props: { readonly hidden: boolean }) { + useVoiceInputController({ + ownerKey: "thread-1", + label: "Thread", + readDraftMessage: () => "", + selection: { start: 0, end: 0 }, + hidden: props.hidden, + onChangeDraftMessage: () => {}, + onChangeSelection: () => {}, + }); + return null; +} + +function setup() { + const session = new VoiceInputSession({ + recorder: { + uri: "file:///voice.m4a", + prepareToRecordAsync: async () => {}, + record: () => {}, + stop: async () => {}, + }, + getTranscriber: () => ({ + prepare: async () => ({ locale: "en-US", transcribe: async () => "" }), + }), + requestPermission: async () => ({ granted: true, canAskAgain: true }), + configureRecording: async () => {}, + releaseRecording: async () => {}, + deleteRecording: () => {}, + sampleRecording: () => null, + publishAudioLevels: () => {}, + keepAwake: () => () => {}, + }); + harness.session = session; + const root = createRoot(document.createElement("div")); + return { + isFocused: () => session.getSnapshot().focusedOwners.has("thread-1"), + render: (hidden: boolean) => act(() => root.render(