From 6f15610d5be1bb1e55842aab7a8b0fe1d180e2b9 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:24:08 -0600 Subject: [PATCH 001/278] fix(server): resolve a later local project favicon when an earlier icon link is not a local file (#42023) Co-authored-by: Julius Marminge --- .../project/ProjectFaviconResolver.test.ts | 24 ++++++++++++- .../src/project/ProjectFaviconResolver.ts | 35 ++++++++++++------- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 7c0207eed557d..00ac4e5d17ef3 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -194,8 +194,20 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile( + cwd, + "index.html", + ` + + + + + +`, + ); yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + yield* writeTextFile(cwd, "public/brand/late.svg", "late"); + yield* writeTextFile(cwd, "public/cdn.example.com/icon.svg", "cdn"); yield* writeTextFile(cwd, "web/favicon.png", "flutter"); const resolved = yield* resolver.resolvePath(cwd); @@ -203,6 +215,15 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(resolved).not.toBeNull(); expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); + // A cached icon whose `public` folder became a file falls back instead of failing. + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "public"), { + recursive: true, + }); + yield* writeTextFile(cwd, "public", "not a folder"); + expect(yield* resolver.resolvePath(cwd)).toBe( + (yield* Path.Path).join(cwd, "web", "favicon.png"), + ); + const flutterCwd = yield* makeTempDir; yield* writeTextFile(flutterCwd, "web/favicon.png", "flutter"); expect(yield* resolver.resolvePath(flutterCwd)).toBe( @@ -284,6 +305,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, + { rel: "icon", href: "https://cdn.example.com/icon.svg" }, { rel: "icon shortcut", href: "/brand/logo.svg" }, ], }), diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 12c8e2fc63ea2..b2df7e0f53eb3 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -122,7 +122,7 @@ export class ProjectFaviconResolver extends Context.Service< } >()("t3/project/ProjectFaviconResolver") {} -function extractIconHref(source: string): string | null { +function* extractIconHrefs(source: string): Generator { for (const [tag] of source.matchAll(HTML_LINK_RE)) { const attributes = new Map(); for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag @@ -145,14 +145,13 @@ function extractIconHref(source: string): string | null { // An unquoted `{...}` is a JSX expression, not a path. if (!href || (!href.quoted && href.value.startsWith("{"))) continue; const path = href.value.split("?")[0]; - if (path) return path; + if (path) yield path; } for (const run of source.split("}")) { if (!ICON_REL_RE.test(run)) continue; const hrefMatch = run.match(ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + if (hrefMatch?.[1]) yield hrefMatch[1]; } - return null; } export const optionOnNotFound = ( @@ -166,6 +165,17 @@ export const optionOnNotFound = ( }), ); +// A path through a file (ENOTDIR) or a symlink loop names no file either. +const optionOnMissing = ( + effect: Effect.Effect, +): Effect.Effect, PlatformError.PlatformError, R> => + optionOnNotFound(effect).pipe( + Effect.catchIf( + (error) => error.reason._tag === "BadResource", + () => Effect.succeedNone, + ), + ); + export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -173,6 +183,8 @@ export const make = Effect.gen(function* () { const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader; const resolveIconHref = (href: string): ReadonlyArray => { + // `data:`, `https:` and `//host` icons name no project file, and a long data URL fails `stat`. + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href.trim())) return []; // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs. const clean = href.trim().replace(/^\//, ""); return [path.join("public", clean), clean]; @@ -203,7 +215,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(candidate)) { continue; } - const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(candidate.value.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -242,7 +254,7 @@ export const make = Effect.gen(function* () { }), ), ); - const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(sourcePath.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -257,7 +269,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(stats) || stats.value.type !== "File") { return null; } - const source = yield* optionOnNotFound( + const source = yield* optionOnMissing( fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe( Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)), Effect.scoped, @@ -277,11 +289,8 @@ export const make = Effect.gen(function* () { if (Option.isNone(source) || Option.isNone(source.value)) { return null; } - const href = extractIconHref(new TextDecoder().decode(source.value.value)); - if (!href) { - return null; - } - return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace"); + const hrefs = Array.from(extractIconHrefs(new TextDecoder().decode(source.value.value))); + return yield* findExistingFile(projectCwd, hrefs.flatMap(resolveIconHref), "workspace"); }); // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit. @@ -377,7 +386,7 @@ export const make = Effect.gen(function* () { return null; } - const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(cached)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ From 9010d7d5a1fb17b4cbaa4299596bcbaba0171cbf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:29:29 -0800 Subject: [PATCH 002/278] fix(server): session import no longer offers T3 sandbox chats behind a symlinked base or a Codex project (#42036) --- .../src/project/AgentSessionScanner.test.ts | 177 ++++++++++++++++++ .../server/src/project/AgentSessionScanner.ts | 52 +++-- 2 files changed, 212 insertions(+), 17 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 09a7a396a294f..0fcab0d7ad4c3 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1345,6 +1345,60 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("excludes sandboxes recorded by their real path when the base dir is a symlink", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + + const worktreeCwd = path.join(realBaseDir, "worktrees", "t3code", "wt-4"); + yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(worktreeCwd), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates).toEqual([]); + }), + ); + + it.effect("offers an outside project reached through a link inside a symlinked base dir", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const projectDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-project-"), + ); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + const projectLink = path.join(realBaseDir, "project-link"); + yield* fileSystem.symlink(projectDir, projectLink); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(projectLink), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: projectLink, threadCount: 1 }, + ]); + }), + ); + it.effect("finds the cwd on a later line when the first records carry none", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1937,6 +1991,129 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect.each([{ layout: "plain" }, { layout: "symlinked into Downloads" }] as const)( + "does not file T3 sandbox chats under the Codex project they were moved into ($layout base dir)", + ({ layout }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nowMs = Date.parse("2026-11-08T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const homeDir = yield* makeTempDir("t3code-home-"); + let configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + let realBaseDir = configBaseDir; + if (layout === "symlinked into Downloads") { + // A Downloads folder is scratch, so only the base's real spelling tells the sandbox apart. + realBaseDir = path.join(homeDir, "Downloads", "t3-data"); + yield* fileSystem.makeDirectory(realBaseDir, { recursive: true }); + configBaseDir = path.join(homeDir, "t3-link"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + } + const projectDir = path.join(homeDir, "code", "my-project"); + const sandboxDir = path.join(realBaseDir, "worktrees", "my-project", "wt-1"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.makeDirectory(sandboxDir, { recursive: true }); + + const projectId = "019a5f00-0000-7000-8000-000000000101"; + const chats = [ + { + id: "019a5f00-0000-7000-8000-00000000010a", + cwd: projectDir, + message: "Started in the project", + }, + { + id: "019a5f00-0000-7000-8000-00000000010b", + cwd: sandboxDir, + message: "Started in a T3 worktree", + }, + ]; + const rolloutPaths: Array = []; + for (const [index, chat] of chats.entries()) { + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "11", + "08", + `rollout-2026-11-08T08-0${index}-00-${chat.id}.jsonl`, + ); + rolloutPaths.push(filePath); + yield* writeTranscript({ + filePath, + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: chat.id, cwd: chat.cwd }, + }), + encodeTranscriptRecord({ type: "turn_context", payload: { cwd: chat.cwd } }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: chat.message }, + }), + ].join("\n"), + mtimeMs: nowMs - 60_000 + index, + }); + } + yield* Effect.sync(() => { + const db = new NodeSqlite.DatabaseSync(path.join(codexHomePath, "state_5.sqlite")); + try { + db.exec(` + CREATE TABLE projects ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + position INTEGER NOT NULL, + created_at_ms INTEGER NOT NULL, + updated_at_ms INTEGER NOT NULL + ); + CREATE TABLE project_roots ( + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (project_id, position) + ); + CREATE TABLE threads ( + id TEXT PRIMARY KEY, + rollout_path TEXT NOT NULL, + cwd TEXT NOT NULL, + project_id TEXT REFERENCES projects(id) ON DELETE SET NULL + ); + `); + db.prepare("INSERT INTO projects VALUES (?, ?, '{}', 0, ?, ?)").run( + projectId, + "my-project", + nowMs, + nowMs, + ); + db.prepare("INSERT INTO project_roots VALUES (?, 0, ?)").run(projectId, projectDir); + const insertThread = db.prepare("INSERT INTO threads VALUES (?, ?, ?, ?)"); + for (const [index, chat] of chats.entries()) { + insertThread.run(chat.id, rolloutPaths[index]!, chat.cwd, projectId); + } + } finally { + db.close(); + } + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + configBaseDir, + workspaceRoot: projectDir, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + expect(threads.map((thread) => thread.title)).toEqual(["Started in the project"]); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }).pipe( + Effect.provideService(HostProcess.HomeDirectory, homeDir), + ); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual( + [{ path: projectDir, threadCount: 1 }], + ); + }), + ); + it.effect("imports a rewound Codex thread with the history its new rollout inherits", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b9029b8746b46..745d60e6f2c26 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -921,8 +921,17 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const projectStore = yield* ProjectStore.ProjectStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - const baseDir = path.resolve(serverConfig.baseDir); - const worktreesDir = path.resolve(serverConfig.worktreesDir); + const configuredT3Dirs = { + baseDir: path.resolve(serverConfig.baseDir), + worktreesDir: path.resolve(serverConfig.worktreesDir), + }; + // Resolved candidates are compared with T3's folders as resolved too, so a symlinked base still matches. + const realPathOf = (directory: string) => + fileSystem.realPath(directory).pipe(Effect.orElseSucceed(() => directory)); + const realT3Dirs = { + baseDir: yield* realPathOf(configuredT3Dirs.baseDir), + worktreesDir: yield* realPathOf(configuredT3Dirs.worktreesDir), + }; const platform = yield* HostProcess.Platform; const isWindows = platform === "win32"; const foldWorktreeCase = isWindows; @@ -939,17 +948,19 @@ export const make = Effect.gen(function* () { path.join(homeDir, "Documents", "Codex"), ]; - const isExcludedProjectPath = (candidatePath: string) => + const isScratchPath = (candidatePath: string) => excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) || excludedProjectAncestors.some((ancestor) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( normalizeForWorktreeMatch(ancestor, foldWorktreeCase), ), - ) || + ); + const isT3OwnedPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( - normalizeForWorktreeMatch(baseDir, foldWorktreeCase), - ) || - isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase); + normalizeForWorktreeMatch(t3Dirs.baseDir, foldWorktreeCase), + ) || isT3ManagedWorktree(candidatePath, t3Dirs.worktreesDir, foldWorktreeCase); + const isExcludedProjectPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => + isScratchPath(candidatePath) || isT3OwnedPath(candidatePath, t3Dirs); const listDirectory = (directory: string) => fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); @@ -1010,7 +1021,7 @@ export const make = Effect.gen(function* () { .realPath(directory) .pipe(Effect.orElseSucceed(() => directory)); // Symlinks can disguise excluded worktree paths; re-check their targets. - return isExcludedProjectPath(realPath) ? Option.none() : stats; + return isExcludedProjectPath(realPath, realT3Dirs) ? Option.none() : stats; }); // Paths whose own read outlived the deadline, mapped to when they may be read @@ -1614,12 +1625,17 @@ export const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed((): ReadonlyMap> => new Map())); }); - // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root. - const projectCwd = (cwd: string, projectRoots: ReadonlyArray | undefined) => - projectRoots !== undefined && - isExcludedProjectPath(path.resolve(expandHomePath(cwd.trim(), homeDir))) - ? projectRoots[0]! - : cwd; + // Only chats left in a scratch folder, such as Codex's, take their project's root; T3's own stay excluded. + const projectCwd = Effect.fnUntraced(function* ( + cwd: string, + projectRoots: ReadonlyArray | undefined, + ) { + if (projectRoots === undefined) return cwd; + const resolved = path.resolve(expandHomePath(cwd.trim(), homeDir)); + if (!isScratchPath(resolved) || isT3OwnedPath(resolved)) return cwd; + const realCwd = yield* realPathOf(resolved); + return isT3OwnedPath(realCwd, realT3Dirs) ? cwd : projectRoots[0]!; + }); const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")( function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) { @@ -1788,7 +1804,7 @@ export const make = Effect.gen(function* () { sameTranscriptIdentity(imported.source, transcript.identity), )?.cwd ?? (yield* readCwd(source, transcript, budget)); if (rolloutCwd === null || rolloutCwd === false) continue; - const cwd = projectCwd(rolloutCwd, transcript.projectRoots); + const cwd = yield* projectCwd(rolloutCwd, transcript.projectRoots); const key = `${transcript.providerInstanceId}\0${cwd}`; const existing = byOwnerAndCwd.get(key); if (existing) { @@ -2097,7 +2113,9 @@ export const make = Effect.gen(function* () { ) { const root = path.resolve(expandHomePath(workspaceRoot, homeDir)); const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); - if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty; + if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot, realT3Dirs)) { + return Stream.empty; + } const rootIdentity = yield* directoryIdentity(root); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; @@ -2283,7 +2301,7 @@ export const make = Effect.gen(function* () { return Option.some({ _tag: "Skipped" }); } const expandedCwd = expandHomePath( - projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), + (yield* projectCwd(snapshot.cwd.value, transcript.projectRoots)).trim(), homeDir, ); if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { From 2ced06ef4acb3b013232faad5bcd0b66bcddecb2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:32:55 -0800 Subject: [PATCH 003/278] fix(web): model picker search finds a model by its ID (#42041) --- apps/web/src/components/chat/ModelPickerContent.tsx | 1 + packages/client-runtime/src/modelSearch.test.ts | 13 +++++++++++++ packages/client-runtime/src/modelSearch.ts | 2 ++ 3 files changed, 16 insertions(+) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e536bbeea44c7..59b67580a4b16 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -707,6 +707,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result; return rankModelPickerSearch(candidates, searchQuery, (model) => ({ name: model.name, + slug: model.slug, ...(model.shortName ? { shortName: model.shortName } : {}), ...(model.subProvider ? { subProvider: model.subProvider } : {}), driverKind: model.driverKind, diff --git a/packages/client-runtime/src/modelSearch.test.ts b/packages/client-runtime/src/modelSearch.test.ts index 3e6be15d89cf4..57697d0cb15e7 100644 --- a/packages/client-runtime/src/modelSearch.test.ts +++ b/packages/client-runtime/src/modelSearch.test.ts @@ -57,6 +57,7 @@ type CatalogModel = { driverKind: string; providerDisplayName: string; name: string; + slug?: string; subProvider?: string; isFavorite?: boolean; }; @@ -127,6 +128,13 @@ const catalog: CatalogModel[] = [ name: "Kimi K2", subProvider: "Moonshot", }, + { + driverKind: "opencode", + providerDisplayName: "OpenCode", + name: "DeepSeek V4.1 Flash 1017", + slug: "opencode-go/deepseek-v4.1-flash", + subProvider: "OpenCode Go", + }, ]; function search(query: string, models: ReadonlyArray = catalog): string[] { @@ -155,6 +163,11 @@ describe("rankModelPickerSearch", () => { expect(search("moonshot")).toEqual(["Kimi K3", "Kimi K2.5", "Kimi K2"]); }); + it("finds a model by its full or bare ID when the name is written differently", () => { + expect(search("opencode-go/deepseek-v4.1-flash")).toEqual(["DeepSeek V4.1 Flash 1017"]); + expect(search("deepseek-v4.1-flash")).toEqual(["DeepSeek V4.1 Flash 1017"]); + }); + it("ranks a favorite above newer models in the same family", () => { const models = catalog.map((model) => model.name === "Claude Opus 4.5" ? { ...model, isFavorite: true } : model, diff --git a/packages/client-runtime/src/modelSearch.ts b/packages/client-runtime/src/modelSearch.ts index bf1a278c87ad8..832f26cde1398 100644 --- a/packages/client-runtime/src/modelSearch.ts +++ b/packages/client-runtime/src/modelSearch.ts @@ -4,6 +4,7 @@ export type ModelPickerSearchableModel = { driverKind: string; providerDisplayName: string; name: string; + slug?: string; shortName?: string; subProvider?: string; isFavorite?: boolean; @@ -20,6 +21,7 @@ function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[] normalizeSearchQuery(model.driverKind), normalizeSearchQuery(model.providerDisplayName), buildModelPickerSearchText(model), + ...(model.slug ? [normalizeSearchQuery(model.slug)] : []), ]; } From f15d908759b7953c4471bf50ab00bc14382de7ee Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:34:34 -0600 Subject: [PATCH 004/278] fix(web): Esc in voice alias input cancels it without closing Settings (#42027) Co-authored-by: Julius Marminge --- .../VoiceSettingsPanel.browser.test.tsx | 38 +++++++++++++++++++ .../settings/VoiceSettingsPanel.tsx | 8 +++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx index 5c918f9430086..6ddfee2ace198 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx @@ -22,6 +22,7 @@ import { } from "../../speech/useEnvironmentSpeechInput"; import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent"; import { useEnvironmentScope } from "../../state/session"; +import { AppRouteModal } from "../AppRouteModal"; import { toastManager } from "../ui/toast"; import { SettingsScopeProvider } from "./SettingsScopeContext"; import { SpeechLanguageSelect } from "./SpeechLanguageSelect"; @@ -700,6 +701,43 @@ it("keeps a dictionary term and alias draft on the Enter that confirms an IME ca await expect.element(alias).toHaveValue("にほん"); }); +it("cancels an alias draft on Esc without closing Settings", async () => { + const previous = getClientSettings(); + using cleanup = new DisposableStack(); + cleanup.defer(() => __setClientSettingsForTests(previous)); + __setClientSettingsForTests({ + ...previous, + speechCustomWords: [{ term: "Kubernetes", aliases: [] }], + }); + await using screen = await render( + + {}}> + + + , + { router: "/settings/voice" }, + ); + const settings = screen.getByRole("dialog", { name: "Settings" }); + const addAlias = screen.getByRole("button", { name: "Add an alias for Kubernetes" }); + await expect.element(addAlias).toBeVisible(); + (addAlias.element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); + const alias = screen.getByRole("textbox", { name: "Alias for Kubernetes" }); + await expect.element(alias).toHaveFocus(); + await userEvent.keyboard("cooper"); + + await userEvent.keyboard("{Escape}"); + + await expect.element(alias).not.toBeInTheDocument(); + await expect.element(settings).toHaveAttribute("data-open"); + await expect.element(settings).toHaveFocus(); + expect(getClientSettings().speechCustomWords).toEqual([{ term: "Kubernetes", aliases: [] }]); + + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).not.toBeInTheDocument(); +}); + it("records from the first connected microphone in the saved order", async () => { const previous = getClientSettings(); using cleanup = new DisposableStack(); diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 84a76f373c8be..e045d0e8d5282 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -479,7 +479,13 @@ function DictionaryEditor(props: { onBlur={() => setAliasDraft(null)} onKeyDown={(event) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Escape") setAliasDraft(null); + if (event.key === "Escape") { + event.stopPropagation(); + // Unmounting the focused input lets the dialog move focus to a control whose + // tooltip would swallow the next Esc; the surface keeps Esc closing Settings. + event.currentTarget.closest("[data-app-modal]")?.focus(); + setAliasDraft(null); + } if (event.key !== "Enter") return; event.preventDefault(); addAlias(); From 548a61d711ca3b97e59d590f07f14847a8a0a3d9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:43:19 -0800 Subject: [PATCH 005/278] fix(desktop): an update whose downloaded file was deleted downloads again before installing (#42035) --- .../src/updates/DesktopUpdates.test.ts | 33 +++++++++++++ apps/desktop/src/updates/DesktopUpdates.ts | 48 +++++++++++++++++-- apps/desktop/src/updates/updateMachine.ts | 16 +++++++ .../desktop/src/updates/updatesTestHarness.ts | 4 ++ 4 files changed, 96 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 535e1123d2911..c1115f314e015 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -647,6 +647,39 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("downloads again when the downloaded update file was deleted before install", () => { + const downloadedFile = "/cache/pending/T3-Code-1.2.4-arm64.zip"; + let installedFileExists: boolean | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + downloadUpdate: Effect.sync(() => { + harness.deletedFiles.delete(downloadedFile); + harness.emit("update-downloaded", { version: "1.2.4", downloadedFile }); + }), + quitAndInstall: Effect.sync(() => { + installedFileExists = !harness.deletedFiles.has(downloadedFile); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + assert.equal(harness.downloadCount(), 1); + + harness.deletedFiles.add(downloadedFile); + const result = yield* updates.installPrepared("1.2.4"); + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 2); + assert.equal(harness.quitAndInstalls(), 1); + assert.isTrue(installedFileExists); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 7976503d9e761..32e64502d9333 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -51,6 +51,7 @@ import { reduceDesktopUpdateStateOnCheckStart, reduceDesktopUpdateStateOnDownloadComplete, reduceDesktopUpdateStateOnDownloadFailure, + reduceDesktopUpdateStateOnDownloadLost, reduceDesktopUpdateStateOnDownloadProgress, reduceDesktopUpdateStateOnDownloadStart, reduceDesktopUpdateStateOnInstallFailure, @@ -80,6 +81,7 @@ const UpdateInfo = Schema.Struct({ releaseNotes: Schema.optional(Schema.Unknown), releaseName: Schema.optional(Schema.NullOr(Schema.String)), releaseDate: Schema.optional(Schema.String), + downloadedFile: Schema.optional(Schema.String), }); const DownloadProgressInfo = Schema.Struct({ @@ -403,6 +405,7 @@ export const make = Effect.gen(function* () { const updaterConfiguredRef = yield* Ref.make(false); const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1); const notAppliedVersionRef = yield* Ref.make(Option.none()); + const downloadedFileRef = yield* Ref.make(Option.none()); // The release a track switch's database check cleared. A build crosses to another track only // through such a switch, and never below that release: version order alone cannot tell whether // a Stable knows a Nightly's migrations. @@ -995,6 +998,19 @@ export const make = Effect.gen(function* () { }), ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate")); + const downloadedFileMissing = Ref.get(downloadedFileRef).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(false), + onSome: (path) => + fileSystem.exists(path).pipe( + Effect.map((exists) => !exists), + Effect.orElseSucceed(() => false), + ), + }), + ), + ); + const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* ( expectedVersion?: string, ) { @@ -1007,11 +1023,32 @@ export const make = Effect.gen(function* () { }; } let installVersion = expectedVersion; - // A download can be hours old: a release published since replaces it before restarting. const retained = yield* Ref.get(updateStateRef); - if ( - retained.downloadedVersion !== null && - (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) && + const retainedVersion = retained.downloadedVersion; + const retainsExpectedDownload = + retainedVersion !== null && + (expectedVersion === undefined || retainedVersion === expectedVersion); + // A cache cleaner can delete the archive; Squirrel.Mac would then fail every install attempt. + if (retainsExpectedDownload && (yield* downloadedFileMissing)) { + yield* logUpdaterWarning("the downloaded update file is gone; downloading it again", { + version: retainedVersion, + }); + yield* updateState(reduceDesktopUpdateStateOnDownloadLost); + const download = yield* downloadAvailableUpdate(true); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + if (expectedVersion !== undefined) { + installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion; + } + } else if ( + // A download can be hours old: a release published since replaces it before restarting. + retainsExpectedDownload && (yield* checkForUpdates( "install", "acquire", @@ -1023,7 +1060,7 @@ export const make = Effect.gen(function* () { // electron-updater compares a stale feed with the running build, not the retained download. if ( refreshed.availableVersion === null || - compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + compareSemverVersions(refreshed.availableVersion, retainedVersion) <= 0 ) { yield* setState(retained); } else { @@ -1244,6 +1281,7 @@ export const make = Effect.gen(function* () { } return; } + yield* Ref.set(downloadedFileRef, Option.fromNullishOr(info.downloadedFile)); yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version)); yield* logUpdaterInfo("update downloaded", { version: info.version }); }), diff --git a/apps/desktop/src/updates/updateMachine.ts b/apps/desktop/src/updates/updateMachine.ts index 80751315657c0..53785a6a57a34 100644 --- a/apps/desktop/src/updates/updateMachine.ts +++ b/apps/desktop/src/updates/updateMachine.ts @@ -209,6 +209,22 @@ export function reduceDesktopUpdateStateOnDownloadComplete( }; } +export function reduceDesktopUpdateStateOnDownloadLost( + state: DesktopUpdateState, +): DesktopUpdateState { + if (state.downloadedVersion === null) return state; + return { + ...withoutTrackMismatch(state), + status: "available", + availableVersion: state.downloadedVersion, + downloadedVersion: null, + downloadPercent: null, + message: null, + errorContext: null, + canRetry: false, + }; +} + export function reduceDesktopUpdateStateOnInstallFailure( state: DesktopUpdateState, message: string, diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..9b8f78e19000c 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -246,6 +246,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { const updateRestartMarkers = new Set(); const updateMarkerContents = new Map(); const installRecords = new Map(); + const deletedFiles = new Set(); let previousInstallRecord = options.installRecord; const isInstallRecord = (path: string) => path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE); @@ -266,6 +267,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { }), ); }, + exists: (path) => Effect.succeed(!deletedFiles.has(path)), makeDirectory: () => Effect.void, writeFileString: (path, data) => Effect.sync(() => { @@ -320,6 +322,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { updateInProgressMarker: () => [...updateMarkerContents].find(([path]) => path.endsWith("/desktop-update-in-progress"))?.[1], installRecords, + /** Paths removed behind the app's back, as by a cache cleaner. */ + deletedFiles, previousInstallRecord: () => previousInstallRecord, downloadCount: () => downloadCount, feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls, From 4cff209428f8451182c482b88d4aa1ee11503706 Mon Sep 17 00:00:00 2001 From: Solomon Botchway <62394255+snnbotchway@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:48:47 +0000 Subject: [PATCH 006/278] fix(server): preview browser downloads Chrome 158.0.8127.88 with its security fix (#42043) Co-authored-by: Julius Marminge --- apps/server/src/preview/PreviewBrowser.ts | 26 +++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/apps/server/src/preview/PreviewBrowser.ts b/apps/server/src/preview/PreviewBrowser.ts index 3f0de9b0af346..306a0bf1f1e8c 100644 --- a/apps/server/src/preview/PreviewBrowser.ts +++ b/apps/server/src/preview/PreviewBrowser.ts @@ -25,31 +25,31 @@ import { openZipArchive } from "../zipArchive.ts"; // https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json // Never pin below 156.0.8078.70: the shell has no CRLSet and older SPKI blocklists trust // compromised eMudhra intermediates (crrev.com/c/8627687). -export const VERSION = "158.0.8127.36"; +export const VERSION = "158.0.8127.88"; const ARCHIVES = { linux64: { - bytes: 132_087_165, - sha256: "2d3a23017323c54fd457a678e4351f895c4076d8050e39d5aa6247f93448b73a", + bytes: 132_091_593, + sha256: "63401333cc587645bfaeea7f0c90958b327d249251e23954a47f30112ca23d5b", }, "linux-arm64": { - bytes: 129_938_239, - sha256: "176ee5c55486c22de43128871189061365ea28e881fc96016fd18e7cb59437c8", + bytes: 129_942_265, + sha256: "9f89b7ef6574e4bbf6ddda9f17f1fab5626e93d6f7d852653232d0d3554df975", }, "mac-arm64": { - bytes: 105_057_133, - sha256: "c24d40a3786322ff3a5e3ac6eed162226cbaf07ebe468715407827226b0f8897", + bytes: 105_060_087, + sha256: "69320f6869c4defbbdac8b8fa83aef65dc63975e83bbd06899b75dbea5c464b3", }, "mac-x64": { - bytes: 112_306_247, - sha256: "e0c5d07d8f5bcc5bdd5ef370e7daf3770856b585fcc9eecf441c7e3bb2e3d1cf", + bytes: 112_314_759, + sha256: "dc1ac31965cb2ec7794aed8c66127aceea304ae15353cd56fc4b8bde44091548", }, win32: { - bytes: 122_509_290, - sha256: "c1fc009622363bccbc1e5f60be654b90fa7b70ad83e642875da1fcb147ae430d", + bytes: 122_509_314, + sha256: "936ad5e7f530bdd66b7261d0a2ceed76b057d429cf31b770a95fd903a7969856", }, win64: { - bytes: 127_876_264, - sha256: "9655950dfeddf565561cd64cfe8ee716ccd6482fa3798503b632219efc65a71e", + bytes: 127_879_225, + sha256: "e935ea2d4633495b5e9ab7bc66bcd982806329c0ee9ecbafc1ac9596a3b34cdb", }, } as const; From 147384f61aae7613ab084a20ac8f963b599bc155 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:50:17 -0800 Subject: [PATCH 007/278] fix(server): storage cleanup removes worktrees that take over 30 s to walk (#42034) --- apps/server/src/storageCleanup.test.ts | 32 ++++++++++++++++++++++++++ apps/server/src/storageCleanup.ts | 24 +++++++++++++------ 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index c62d74f186553..61565f3a5e0a1 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3411,6 +3411,38 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect("removes an eligible worktree whose ignored files take over 30 seconds to walk", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fs = yield* FileSystem.FileSystem; + const walking = yield* Deferred.make(); + let slowPath: string | undefined; + // Stands in for a flat Bun or npm node_modules with hundreds of thousands of files. + const fixture = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + lstat: (target) => + Effect.gen(function* () { + if (target === slowPath) { + yield* Deferred.succeed(walking, undefined); + yield* Effect.sleep("31 seconds"); + } + return yield* fs.lstat(target); + }), + }), + ); + yield* fs.makeDirectory(`${fixture.worktree}/node_modules/pkg`, { recursive: true }); + yield* fs.writeFileString(`${fixture.worktree}/node_modules/pkg/index.js`, "export {};\n"); + slowPath = `${yield* fs.realPath(fixture.worktree)}/node_modules`; + const run = yield* fixture.service.runNow.pipe(Effect.forkChild); + yield* Deferred.await(walking); + yield* TestClock.adjust("31 seconds"); + expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "removed" }); + expect(yield* fs.exists(fixture.worktree)).toBe(false); + }), + ), + ); it.effect("removes a worktree owned by a repository other than the project root", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 451df614f8184..d091c9d11228d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -515,9 +515,19 @@ const make = Effect.gen(function* () { } return { bytes, reason: null }; }, - Effect.timeout("30 seconds"), + // No time limit: the entry cap bounds the walk, and a removal that timed out would + // repeat the whole walk on every sweep without ever deleting the worktree. Effect.orElseSucceed(() => ({ bytes: null, reason: "worktree could not be fully inspected" })), ); + // For walks under a workspace lease, which provider startup waits on, or repeated under one. + const measureWorktreeBounded = (...args: Parameters) => + measureWorktree(...args).pipe( + Effect.timeoutOrElse({ + duration: "30 seconds", + orElse: () => + Effect.succeed({ bytes: null, reason: "worktree could not be fully inspected" }), + }), + ); // Large snapshots take seconds; use the reader worker instead of blocking the event loop. const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () { @@ -682,9 +692,9 @@ const make = Effect.gen(function* () { if (orphanSizes.has(key)) continue; const remaining = measurementDeadline - (yield* Clock.currentTimeMillis); if (!firstMeasurement && remaining <= 0) break; - const measured = yield* measureWorktree(path).pipe( - firstMeasurement ? Effect.asSome : Effect.timeoutOption(remaining), - ); + const measured = yield* firstMeasurement + ? measureWorktreeBounded(path).pipe(Effect.asSome) + : measureWorktree(path).pipe(Effect.timeoutOption(remaining)); firstMeasurement = false; if (Option.isSome(measured)) orphanSizes.set(key, measured.value.bytes); } @@ -1282,7 +1292,7 @@ const make = Effect.gen(function* () { ((yield* branchChanged(checkoutPath, branch)) ? "repository or branch changed" : null) ?? (yield* localChangesReason(checkoutPath, rules)); if (reason !== null) return { keep: reason, force: false, bytes: null }; - const { bytes, reason: measureReason } = yield* measureWorktree(checkoutPath, true); + const { bytes, reason: measureReason } = yield* measureWorktreeBounded(checkoutPath, true); if (measureReason !== null) return { keep: measureReason, force: false, bytes }; // Measuring takes time, and what follows deletes ignored files under these rules. if (yield* settingsChanged) @@ -1616,13 +1626,13 @@ const make = Effect.gen(function* () { (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? (yield* blockedSinceCheck()); if (blocked !== null) return keep(blocked); - const inspection = yield* measureWorktree(worktreePath, "plain-folder"); + const inspection = yield* measureWorktreeBounded(worktreePath, "plain-folder"); if (inspection.reason !== null) return keep(inspection.reason); return yield* withWorkspaceLease( worktreePath, Effect.gen(function* () { // Walked again under the lease: a repository deleted with the folder is gone for good. - const finalInspection = yield* measureWorktree(worktreePath, "plain-folder"); + const finalInspection = yield* measureWorktreeBounded(worktreePath, "plain-folder"); if (finalInspection.reason !== null) return keep(finalInspection.reason); // The walk takes time, so the cheap checks run last, right before removal. const blockedWhileMeasuring = From fc91bfdf6ce2010007843ecdcfa37ec93ffb6e31 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:54:09 -0600 Subject: [PATCH 008/278] fix(cli): keep the triage picker open after an invalid numbered choice (#42046) Co-authored-by: Julius Marminge --- apps/server/src/cli/triage.test.ts | 13 +++++++++++++ apps/server/src/cli/triage.ts | 23 +++++++++++++++-------- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 41f4241fade68..a0bf8597431dc 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -21,6 +21,7 @@ import { expect, vi } from "vite-plus/test"; import { cli } from "../binCli.ts"; import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts"; +import { matchAgentAnswer } from "./triage.ts"; const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)); @@ -108,6 +109,18 @@ it.live.each([ }), ); +it.each([ + { answer: "2", picked: "codex" }, + { answer: " 1 ", picked: "claude" }, + { answer: "CLAUDE", picked: "claude" }, + { answer: "1.5", picked: undefined }, + { answer: "1x", picked: undefined }, + { answer: "2codex", picked: undefined }, + { answer: "3", picked: undefined }, +])("the agent picker reads $answer as $picked", ({ answer, picked }) => { + expect(matchAgentAnswer([{ id: "claude" }, { id: "codex" }], answer)?.id).toBe(picked); +}); + it.live( "requires an explicit choice when Codex and Antigravity are installed without a terminal", () => diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index df73347cd9fe4..a4c7da2a91e49 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -86,6 +86,17 @@ export class TriageAgentSpawnError extends Schema.TaggedError( + agents: ReadonlyArray, + answer: string, +) => { + const trimmed = answer.trim(); + return ( + agents.find((_, index) => String(index + 1) === trimmed) ?? + agents.find((agent) => agent.id === trimmed.toLowerCase()) + ); +}; + const pickAgent = (agents: ReadonlyArray) => Effect.promise(async () => { const readline = NodeReadlinePromises.createInterface({ @@ -97,14 +108,10 @@ const pickAgent = (agents: ReadonlyArray) => .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`) .join("\n"); for (;;) { - const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim(); - const byNumber = agents[Number.parseInt(answer, 10) - 1]; - if (byNumber !== undefined) { - return byNumber; - } - const byId = agents.find((agent) => agent.id === answer.toLowerCase()); - if (byId !== undefined) { - return byId; + const answer = await readline.question(`Run triage with:\n${menu}\n> `); + const picked = matchAgentAnswer(agents, answer); + if (picked !== undefined) { + return picked; } } } finally { From 139af501b6781183b82341a8a76bee01e7109974 Mon Sep 17 00:00:00 2001 From: hanmin6 Date: Tue, 24 Nov 2026 17:56:01 +0800 Subject: [PATCH 009/278] fix(usage): skip elapsed resets in pooled refill summaries (#42037) Co-authored-by: hanmin6 <226948540+hanmin6@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/features/usage/UsageLimitsPooled.tsx | 2 +- .../usage/UsageLimitsPooled.browser.test.tsx | 39 +++++++++++++++++++ .../components/usage/UsageLimitsPooled.tsx | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 50a987787b4e4..9942754660b8e 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -195,7 +195,7 @@ function PoolWindowCard({ const inlineLabels = wide && segmentWidth >= 96; const inlineReset = wide && segmentWidth >= 150; const inlineName = wide && segmentWidth >= 220; - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); const openAccount = (account: LimitAccount) => navigation.navigate("SettingsUsageAccount", { accountKey: account.key, diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f21..b6fe3e50c9d37 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -7,6 +7,8 @@ import { import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; import { describe, expect, it } from "vite-plus/test"; +import "~/index.css"; + import { render } from "../../../test/render"; import { UsageLimitsPooled } from "./UsageLimitsPooled"; @@ -63,3 +65,40 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +describe("UsageLimitsPooled next refill", () => { + it("skips elapsed resets while waiting for refreshed account data", async () => { + function account(instanceId: string, usedPercent: number, resetsAt: string): ServerProvider { + return { + ...managedChatGpt(instanceId, instanceId), + usageLimits: { + checkedAt, + windows: [{ id: "weekly", label: "Weekly", kind: "weekly", usedPercent, resetsAt }], + }, + }; + } + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + account("Work", 20, "2026-10-25T17:00:00.000Z"), + account("Personal", 60, "2026-10-25T18:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + await expect.element(screen.getByText("↻ +30%", { exact: true })).toBeVisible(); + + await screen.rerender( + , + ); + await expect.element(screen.getByText(/^↻ \+\d+%$/)).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index c3932252691e5..d45ca4c0b6b15 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -604,7 +604,7 @@ function PoolWindowCard({ readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); return (
From 28d8a63d7f8e5b1c0e70d479a315885a425fae32 Mon Sep 17 00:00:00 2001 From: pepsi <120768686+pepsile@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:56:14 +0800 Subject: [PATCH 010/278] fix(web): sidebar search times no longer wrap in translated languages (#42011) Co-authored-by: pepsi Co-authored-by: Julius Marminge --- apps/web/src/components/sidebar/SidebarThreadRow.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 2aa9be4c244a6..1811f17afac97 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1932,7 +1932,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props settled={props.isSettled} /> - + From a326dea2f9dd1ef80daf591c7ee90ccbde9ac094 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 02:02:20 -0800 Subject: [PATCH 011/278] fix(ci): a newer push to a PR is no longer cancelled by the older push's label job (#42061) --- .github/workflows/pr-size.yml | 10 +++++++--- .github/workflows/pr-vouch.yml | 14 +++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index 45f5c9b9f7760..41e4ccecb024d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -7,6 +7,13 @@ on: permissions: contents: read +# Run-level, not job-level: runs join the group when their event arrives, so a newer push +# always supersedes an older one. A job-level group is joined when the job starts, which +# let an older run's slower job cancel the newer head's job and label from a stale diff. +concurrency: + group: pr-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + jobs: prepare-config: name: Prepare PR size config @@ -120,9 +127,6 @@ jobs: contents: read issues: read pull-requests: write - concurrency: - group: pr-size-${{ github.event.pull_request.number }} - cancel-in-progress: true steps: # This pull_request_target job may fetch untrusted PR commits only as passive # git data. Do not add dependency installs, build/test scripts, or cache diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index a81f877e69ddd..c8b067e7637dd 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -15,6 +15,17 @@ on: permissions: contents: read +# Per-PR events supersede each other at the run level, in arrival order (a job-level group +# is joined when the job starts, so an older run's slower job could cancel the newer one). +# Other comments and pushes get a unique group so they never cancel a PR's run. +concurrency: + group: >- + ${{ (github.event_name == 'pull_request_target' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '/recheck-vouch'))) + && format('pr-vouch-run-{0}', github.event.pull_request.number || github.event.issue.number) + || format('pr-vouch-run-{0}', github.run_id) }} + cancel-in-progress: true + jobs: collect-targets: name: Collect PR targets @@ -74,9 +85,6 @@ jobs: permissions: contents: read pull-requests: write - concurrency: - group: pr-vouch-${{ matrix.target.number }} - cancel-in-progress: true strategy: fail-fast: false matrix: From 38634aa6a5414baa3a00df5554c8c8a42dacabb5 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:24:09 -0600 Subject: [PATCH 012/278] fix(cli): find the worktree's project when a Git hook sets GIT_DIR (#42063) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 5 +++++ apps/server/src/cli/thread.ts | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index eafda7f3e9b69..41632c169d03f 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -767,5 +767,10 @@ it.live("resolves a path inside a git worktree of the project's repository to th assert.strictEqual(ambiguous._tag, "ThreadUsageError"); assert.include(ambiguous.message, "sample (project-sample)"); assert.include(ambiguous.message, "feature (project-feature)"); + + // An inherited relative GIT_DIR resolves against Git's cwd, where no repository is. + vi.stubEnv("GIT_DIR", ".git"); + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index fc3476739d1b0..ce74ce4eb2815 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -34,6 +34,7 @@ import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; +import { unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -327,9 +328,15 @@ const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools /** The checkouts of the git repository at `directory`, or none outside a repository. */ const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const env = unsetInheritedRepositoryEnv(process.env, yield* HostProcess.Platform); const list = (args: ReadonlyArray) => processRunner - .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory }) + .run({ + command: "git", + args: ["worktree", "list", "--porcelain", ...args], + cwd: directory, + env, + }) .pipe( Effect.option, Effect.map((result) => From 42068f543e529006197275122f6d29d7fa4fdee4 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 24 Nov 2026 12:31:02 +0200 Subject: [PATCH 013/278] fix(shared): a Markdown piece held open for a wrapper is cut before it passes 128 KB (#42040) Co-authored-by: Julius Marminge --- packages/shared/src/markdownChunks.test.ts | 10 +++++++++- packages/shared/src/markdownChunks.ts | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts index 8b4801ad7594f..d57885b73fbf8 100644 --- a/packages/shared/src/markdownChunks.test.ts +++ b/packages/shared/src/markdownChunks.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { splitMarkdown } from "./markdownChunks.ts"; +import { LARGE_MARKDOWN_CHUNK_MAX_CHARS, splitMarkdown } from "./markdownChunks.ts"; const splitLargeMarkdown = (text: string, targetChars?: number) => splitMarkdown(text, targetChars).chunks; @@ -119,6 +119,14 @@ describe("splitMarkdown", () => { expect(starts(multiline)).toEqual(["", "", "x".repeat(32 * 1024), "", "after"].join("\n"); expect(starts(unclosed)).toEqual(["
", "after"]); + const head = ["
", "", "a".repeat(8 * 1024), "", ""].join("\n"); + const longLine = "x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - head.length); + expect(starts(head + longLine)).toEqual(["
"]); + expect(starts(`${head}${longLine}x`)).toEqual(["
", `${longLine}x`]); + expect(starts(`${head}\`\`\`json\n${longLine}\n\`\`\`\n\n
`)).toEqual([ + "
", + "```json", + ]); }); it("treats an autolink line as a paragraph, so a following fence still opens", () => { diff --git a/packages/shared/src/markdownChunks.ts b/packages/shared/src/markdownChunks.ts index e714e8ed5ed76..ee01ed535a94a 100644 --- a/packages/shared/src/markdownChunks.ts +++ b/packages/shared/src/markdownChunks.ts @@ -114,10 +114,12 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let afterHeading = false; let definitionChars = 0; let openWrappers = 0; + let heldCut = 0; const flush = () => { chunks.push({ text: lines.join("\n"), lines: lines.length }); lines = []; chars = 0; + heldCut = 0; }; for (const line of text.split("\n")) { if (closes !== null) { @@ -127,12 +129,12 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; } else { if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0; - const cut = + const cutPoint = chars >= targetChars && - openWrappers === 0 && (ATX_HEADING.test(line) || (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); - if (cut) flush(); + if (cutPoint && openWrappers === 0) flush(); + else if (cutPoint) heldCut = lines.length; closes = blockCloser(line); // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or // another definition. @@ -149,6 +151,14 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S first = false; lines.push(line); chars += line.length + 1; + // A piece too large to render goes back to the last cut a wrapper held. + if (heldCut > 0 && chars - 1 > LARGE_MARKDOWN_CHUNK_MAX_CHARS) { + const rest = lines.splice(heldCut); + flush(); + lines = rest; + chars = rest.reduce((sum, kept) => sum + kept.length + 1, 0); + openWrappers = 0; + } afterBlankLine = line.trim() === ""; afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); } From dc326236ea21531d1bb931b7e0ba94fac5cfbd1d Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 24 Nov 2026 12:33:26 +0200 Subject: [PATCH 014/278] fix(web): raw HTML paragraphs and list items keep their lines when line breaks are on (#42055) Co-authored-by: Julius Marminge --- apps/web/src/markdown/wordsHast.test.ts | 5 +++++ apps/web/src/markdown/wordsHast.ts | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index 78478c06cc195..516fa71bee722 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -168,6 +168,11 @@ describe("wordsHast", () => { expect(wordsHtml(markdown, { breaks: true })).toBe( '

one
\ntwo three
\nfour

\n
    \n
  • item
    \nnext\n
      \n
    • sub
    • \n
    \n
  • \n
\n
kept\nlines\n
', ); + const rawHtml = + '

\n \n

\n\n
    \n
  • \none\ntwo\n
  • \n
'; + expect(wordsHtml(rawHtml, { breaks: true })).toBe( + '

\n \n

\n
    \n
  • \none\ntwo\n
  • \n
', + ); }); it("keeps the composer's tildes and list numbers in user messages", () => { diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index 4a3397dd062b8..16de1be79fcc2 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -702,8 +702,10 @@ function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: bo checkbox.properties = { type: "checkbox", checked, disabled: true }; if (node.type === "element") node.properties.className = ["contains-task-list"]; } - breakLines(child, walk.options.breaks); - } else if (tagName === "p") { + if (child.position) breakLines(child, walk.options.breaks); + } else if (tagName === "p" && Object.keys(child.properties).length === 0) { + // Words writes a Markdown paragraph bare; one with attributes is raw HTML, which keeps its + // lines as written, as remark-breaks never touched raw HTML. breakLines(child, walk.options.breaks); } else if (tagName === "blockquote") { // remarkGithubAlerts From 47329274bc3d06f8ea1e7c40ae42696060c85a8e Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:33:44 -0600 Subject: [PATCH 015/278] fix(client-runtime): local repository clone folders keep # and ? in their name (#42062) Co-authored-by: Julius Marminge --- .../client-runtime/src/operations/projects.test.ts | 5 +++++ packages/client-runtime/src/operations/projects.ts | 13 +++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index 5975f9c0dfdf9..fc55dccf4256a 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -143,6 +143,11 @@ describe("add project shared logic", () => { expect(getCloneDirectoryName("C:\\src\\repo.git")).toBe("repo"); expect(getCloneDirectoryName("git@github.com:repo.git")).toBe("repo"); expect(getCloneDirectoryName(" https://github.com/owner/repo.git ")).toBe("repo"); + expect(getCloneDirectoryName("/srv/git/firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("~/git/what?.git")).toBe("what?"); + expect(getCloneDirectoryName("../firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("C:\\src\\firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("github.com:owner/repo.git?ref=main")).toBe("repo"); }); it("lays clone folders out like ghq only when asked, and only when the URL is safe", () => { diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 3808a3667286e..9f65f63e44a4a 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -12,7 +12,12 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { isAbsolutePath, isExplicitRelativePath, newProjectFolderName } from "@t3tools/shared/path"; +import { + isAbsolutePath, + isExplicitRelativePath, + isHostPath, + newProjectFolderName, +} from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -234,7 +239,11 @@ export function getAddProjectInitialQuery(baseDirectory: string | null | undefin } export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string { - const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? ""; + const trimmed = (repositoryOrRemoteUrl ?? "").trim(); + // A local path keeps `#` and `?` in its name; in a URL they start a query or fragment. + const isLocalPath = + !trimmed.includes("://") && (isHostPath(trimmed) || isExplicitRelativePath(trimmed)); + const withoutQuery = isLocalPath ? trimmed : (trimmed.split(/[?#]/)[0] ?? ""); const schemeIndex = withoutQuery.indexOf("://"); const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery); const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery; From 60c9cb927e36df49dde83b4ebcb19d4a6fc6a7b0 Mon Sep 17 00:00:00 2001 From: Dang Date: Tue, 24 Nov 2026 18:40:54 +0800 Subject: [PATCH 016/278] fix(server): report CI passing during watch registration (#42049) Co-authored-by: Julius Marminge --- .../orchestration-v2/pullRequestWatch.test.ts | 36 +++++++++++++++++++ .../src/orchestration-v2/pullRequestWatch.ts | 4 ++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 7eb1868cbb1f5..506c3d203b453 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -170,6 +170,42 @@ describe("evaluatePullRequestWatch", () => { ); }); + it.each([false, true])( + "reports CI that passes during registration once (required: %s)", + (required) => { + const green = detail({ checks: [{ ...check("test", "success"), required }] }); + for (const awaitingBaseline of ["all", "checks"] as const) { + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline, checksPending: true }), + green, + noRemarks, + ); + assert.deepEqual(first.changes, [{ kind: "checks-passed", count: 1, required }]); + assert.isFalse(first.next.checksPending); + assert.deepEqual(evaluatePullRequestWatch(first.next, green, noRemarks).changes, []); + } + }, + ); + + it("does not announce an unchanged required gate while optional CI still runs", () => { + const pending = detail({ + checks: [{ ...check("test", "success"), required: true }, check("advisory", "pending")], + }); + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline: "all", checksPending: true }), + pending, + noRemarks, + ); + assert.deepEqual(first.changes, []); + const green = { + ...pending, + checks: pending.checks.map((check) => ({ ...check, status: "success" as const })), + }; + const finished = evaluatePullRequestWatch(first.next, green, noRemarks); + assert.deepEqual(finished.changes, [{ kind: "checks-passed", count: 2, required: false }]); + assert.deepEqual(evaluatePullRequestWatch(finished.next, green, noRemarks).changes, []); + }); + it("baselines existing failures and conflicts, then reports new ones", () => { const broken = detail({ checks: [check("lint", "failure"), check("test", "pending")], diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index e6e0be0f20310..284949f96c510 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -163,7 +163,9 @@ export function evaluatePullRequestWatch( checks.every((check) => check.status !== "pending"); owedChecks = owed; if (passedNow && (!passed || gateGrew)) { - if (!checksBaseline) { + // CI running at the start that has since settled green is news. The start rollup can be + // pending only on optional checks, so a passed gate alone is not. + if (!checksBaseline || (watch.checksPending === true && settled)) { changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 }); } owedChecks = From 74d73ac23fc183ddd6bf65ede469e9b261891bf2 Mon Sep 17 00:00:00 2001 From: karstennilsen Date: Tue, 24 Nov 2026 11:47:53 +0100 Subject: [PATCH 017/278] fix(web): a thread link to an unconnected environment shows why instead of a blank pane (#42048) Co-authored-by: Karsten Nilsen <8917480+karstennilsen@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/components/ThreadRouteView.tsx | 32 ++++++++++++++++++++- apps/web/src/i18n/translations/de.json | 2 ++ apps/web/src/i18n/translations/en.json | 2 ++ apps/web/src/i18n/translations/es.json | 2 ++ apps/web/src/i18n/translations/fr.json | 2 ++ apps/web/src/i18n/translations/ja.json | 2 ++ apps/web/src/i18n/translations/ko.json | 2 ++ apps/web/src/i18n/translations/pt-BR.json | 2 ++ apps/web/src/i18n/translations/ru.json | 2 ++ apps/web/src/i18n/translations/sv.json | 2 ++ apps/web/src/i18n/translations/zh.json | 2 ++ apps/web/src/state/presentation.ts | 21 ++++++++++++++ apps/web/src/state/shell.test.ts | 23 +++++++++++++++ apps/web/src/threadRoutes.test.ts | 11 +++++++ apps/web/src/threadRoutes.ts | 7 ++++- 15 files changed, 112 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 48b86b8ddfe56..f9a1aca77daa6 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -4,11 +4,14 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; import type { ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; -import { Navigate, useNavigate } from "@tanstack/react-router"; +import { Link, Navigate, useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; +import { Button } from "./ui/button"; +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -17,6 +20,7 @@ import { useAnyEnvironmentHiding, useQuietThreadShell, } from "../state/entities"; +import { environmentUnreachableAtom } from "../state/presentation"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useEnvironmentShellStatus } from "../state/shell"; import { environmentThreadShells, threadFamilies, useEnvironmentThread } from "../state/threads"; @@ -70,6 +74,9 @@ export function ThreadRouteView({ const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); + const environmentUnreachable = useAtomValue( + environmentUnreachableAtom(serverThreadRef?.environmentId ?? null), + ); const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus); const draftThread = useComposerDraftStore((store) => serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null, @@ -137,6 +144,7 @@ export function ThreadRouteView({ serverThreadDeleted: serverThreadShell?.deletedAt != null, unlistedThreadDetail, draftThreadExists: draftThread !== null, + environmentUnreachable, }); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; @@ -208,6 +216,8 @@ export function ThreadRouteView({ } else { redirect = ; } + } else if (renderState === "unreachable") { + view = ; } else if (hiddenByTagFilter) { redirect = ; } else if (offShellBlocked) { @@ -236,3 +246,23 @@ export function ThreadRouteView({ ); } + +function UnreachableEnvironmentState() { + return ( + + + + Thread unavailable + + + This thread is on an environment this app is not connected to. + + + + + + + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 9bffdc0b7b720..967c314fd18fe 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2630,6 +2630,8 @@ "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", "c6196d99000642b4": "Thread öffnen", + "70bdebaa3d291d3b": "Thread nicht verfügbar", + "a351ebbdcf1a3f7a": "Dieser Thread liegt in einer Umgebung, mit der diese App nicht verbunden ist.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index d62730f5addeb..1b8e2d7620338 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", "c6196d99000642b4": "Open thread", + "70bdebaa3d291d3b": "Thread unavailable", + "a351ebbdcf1a3f7a": "This thread is on an environment this app is not connected to.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4ded558e58454..65966981e964d 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", "c6196d99000642b4": "Abrir hilo", + "70bdebaa3d291d3b": "Hilo no disponible", + "a351ebbdcf1a3f7a": "Este hilo está en un entorno al que esta app no está conectada.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 60dae1d830451..24c38c1ece801 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", "c6196d99000642b4": "Ouvrir le fil", + "70bdebaa3d291d3b": "Fil indisponible", + "a351ebbdcf1a3f7a": "Ce fil se trouve dans un environnement auquel cette app n’est pas connectée.", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8f3380f194613..cb90e296f2ff6 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2627,6 +2627,8 @@ "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", "c6196d99000642b4": "スレッドを開く", + "70bdebaa3d291d3b": "スレッドを利用できません", + "a351ebbdcf1a3f7a": "このスレッドは、このアプリが接続していない環境にあります。", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f2f266662eb74..70a655f4c9e09 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2628,6 +2628,8 @@ "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", "c6196d99000642b4": "스레드 열기", + "70bdebaa3d291d3b": "스레드를 사용할 수 없음", + "a351ebbdcf1a3f7a": "이 스레드는 이 앱이 연결되어 있지 않은 환경에 있습니다.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 7348253aa8980..32bae390ab0cf 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", "c6196d99000642b4": "Abrir thread", + "70bdebaa3d291d3b": "Thread indisponível", + "a351ebbdcf1a3f7a": "Esta thread está em um ambiente ao qual este app não está conectado.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4b428ec6a1751..dc38cf4289dce 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", "c6196d99000642b4": "Открыть тред", + "70bdebaa3d291d3b": "Тред недоступен", + "a351ebbdcf1a3f7a": "Этот тред находится в окружении, к которому это приложение не подключено.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 353f3554e31e9..7a1eb406e1a19 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", "c6196d99000642b4": "Öppna tråd", + "70bdebaa3d291d3b": "Tråden är inte tillgänglig", + "a351ebbdcf1a3f7a": "Den här tråden finns i en miljö som den här appen inte är ansluten till.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 1b72edb0ab4d4..4e904ee3add84 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2633,6 +2633,8 @@ "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", "c6196d99000642b4": "打开会话", + "70bdebaa3d291d3b": "会话不可用", + "a351ebbdcf1a3f7a": "此会话位于本应用未连接的环境中。", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", diff --git a/apps/web/src/state/presentation.ts b/apps/web/src/state/presentation.ts index e970c64f23c7e..36ba359fb8678 100644 --- a/apps/web/src/state/presentation.ts +++ b/apps/web/src/state/presentation.ts @@ -9,6 +9,7 @@ import { Atom } from "effect/reactivity"; import { environmentCatalog } from "../connection/catalog"; import { serverEnvironment } from "./server"; +import { expectsPrimaryEnvironment } from "./shell"; export const environmentPresentations = createEnvironmentPresentationAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, @@ -25,6 +26,26 @@ const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make + Atom.make((get) => { + if (environmentId === null) return false; + const catalog = get(environmentCatalog.catalogValueAtom); + if (!catalog.isReady) return false; + // The catalog is ready before primary discovery lands; until then it cannot prove absence. + if ( + expectsPrimaryEnvironment() && + !Array.from(catalog.entries.values()).some( + (entry) => entry.target._tag === "PrimaryConnectionTarget", + ) + ) { + return false; + } + const entry = catalog.entries.get(environmentId); + return !entry?.enabled || entry.unsupportedReason !== undefined; + }), +); + export function useEnvironmentPresentation(environmentId: EnvironmentId | null) { const catalog = useAtomValue(environmentCatalog.catalogValueAtom); const presentation = useAtomValue( diff --git a/apps/web/src/state/shell.test.ts b/apps/web/src/state/shell.test.ts index 530c96b9c8d29..6b6434e283590 100644 --- a/apps/web/src/state/shell.test.ts +++ b/apps/web/src/state/shell.test.ts @@ -16,6 +16,7 @@ import { environmentShell, } from "./shell"; import { environmentCatalog } from "../connection/catalog"; +import { environmentUnreachableAtom } from "./presentation"; import { defaultProjectFallbackReadyAtom } from "./projects"; const LOCAL = EnvironmentId.make("local"); @@ -143,6 +144,28 @@ describe("project snapshot readiness", () => { }); }); +it("calls an environment unreachable only once primary discovery can prove it absent", () => { + const UNKNOWN = EnvironmentId.make("unknown"); + const unreachable = (catalog: EnvironmentCatalogState, environmentId: EnvironmentId) => { + const registry = AtomRegistry.make({ + initialValues: [[environmentCatalog.catalogValueAtom, catalog]], + }); + try { + return registry.get(environmentUnreachableAtom(environmentId)); + } finally { + registry.dispose(); + } + }; + vi.stubGlobal("window", { desktopBridge: { getLocalEnvironmentEnabled: () => true } }); + try { + expect(unreachable(catalogState([REMOTE]), LOCAL)).toBe(false); + expect(unreachable(catalogState([LOCAL, REMOTE]), UNKNOWN)).toBe(true); + expect(unreachable(catalogState([LOCAL, REMOTE]), REMOTE)).toBe(false); + } finally { + vi.unstubAllGlobals(); + } +}); + it("expects a primary environment only on desktops with the local environment enabled", () => { const desktop = (enabled: boolean) => { vi.stubGlobal("window", { desktopBridge: { getLocalEnvironmentEnabled: () => enabled } }); diff --git a/apps/web/src/threadRoutes.test.ts b/apps/web/src/threadRoutes.test.ts index c4fef5897c5f4..fd8e7c1b157d6 100644 --- a/apps/web/src/threadRoutes.test.ts +++ b/apps/web/src/threadRoutes.test.ts @@ -153,6 +153,17 @@ describe("threadRoutes", () => { draftThreadExists: false, }), ).toBe("missing"); + // A link to an environment this app has no connection to never bootstraps. + expect( + resolveThreadRouteRenderState({ + bootstrapComplete: false, + serverThreadExists: false, + serverThreadDeleted: false, + unlistedThreadDetail: EMPTY_ENVIRONMENT_THREAD_STATE, + draftThreadExists: false, + environmentUnreachable: true, + }), + ).toBe("unreachable"); }); it("opens an unlisted server thread once its detail arrives, without waiting for the shell", () => { diff --git a/apps/web/src/threadRoutes.ts b/apps/web/src/threadRoutes.ts index a2047d4fe2e14..49192f75cf56d 100644 --- a/apps/web/src/threadRoutes.ts +++ b/apps/web/src/threadRoutes.ts @@ -21,7 +21,7 @@ type DraftThreadRouteState = { promotedTo?: ScopedThreadRef | null; }; -export type ThreadRouteRenderState = "loading" | "ready" | "missing"; +export type ThreadRouteRenderState = "loading" | "ready" | "missing" | "unreachable"; export function isThreadRouteSnapshotAuthoritative( status: EnvironmentShellStatus | null | undefined, @@ -35,10 +35,15 @@ export function resolveThreadRouteRenderState(input: { serverThreadDeleted: boolean; unlistedThreadDetail: EnvironmentThreadState; draftThreadExists: boolean; + /** The app has no enabled connection to the thread's environment, so its shell never goes live. */ + environmentUnreachable?: boolean; }): ThreadRouteRenderState { if (input.draftThreadExists || (input.serverThreadExists && !input.serverThreadDeleted)) { return "ready"; } + if (input.environmentUnreachable) { + return "unreachable"; + } if (!input.bootstrapComplete) { return "loading"; } From 8fcd0a8f76a911b175eadc82c94fdff7eaa26822 Mon Sep 17 00:00:00 2001 From: Gourango Sutradhar Date: Tue, 24 Nov 2026 16:56:14 +0600 Subject: [PATCH 018/278] fix(server): hide Android emulator consoles on Windows (#41971) Co-authored-by: Julius Marminge --- apps/server/src/device/LocalDeviceHost.ts | 3 +- .../src/device/deviceHubNodeArgs.test.ts | 59 +++++++++++++++++++ apps/server/src/device/deviceHubNodeArgs.ts | 25 ++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/device/deviceHubNodeArgs.test.ts create mode 100644 apps/server/src/device/deviceHubNodeArgs.ts diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 7fd2816e3c17c..0c9912aadd034 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -40,6 +40,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts"; import * as DeviceHost from "./DeviceHost.ts"; import { makeDeviceHubOperations } from "./DeviceHubOperations.ts"; +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; import { agentDeviceStateDir, type DeviceToolPaths, @@ -455,7 +456,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ChildProcess.make( nodePath, [ - hubTool.entryPath, + ...deviceHubNodeArgs(hubTool.entryPath, hostPlatform), "--port", String(port), "--host", diff --git a/apps/server/src/device/deviceHubNodeArgs.test.ts b/apps/server/src/device/deviceHubNodeArgs.test.ts new file mode 100644 index 0000000000000..efe434862d46d --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.test.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics nodeBuiltinImport:off - exercises the standalone Node preload in a subprocess. +import { describe, expect, it } from "@effect/vitest"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeUtil from "node:util"; + +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; + +const exec = NodeUtil.promisify(NodeChildProcess.execFile); + +describe("deviceHubNodeArgs", () => { + it("hides emulator consoles without changing other hub children or arguments", async () => { + const capture = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +childProcess.spawn = (...args) => console.log(JSON.stringify(args)); +syncBuiltinESMExports(); +`; + const fixture = ` +import { spawn } from "node:child_process"; +import { join } from "node:path"; +spawn(join("sdk with spaces", "emulator", "Emulator.exe"), ["-avd", "Pixel"], { + detached: true, stdio: "ignore", env: { TEST: "preserved" } +}); +spawn("ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }); +spawn("emulator.exe", { detached: true, cwd: "sdk" }); +console.log(JSON.stringify(process.argv.slice(1))); +`; + const args = deviceHubNodeArgs("unused-entry.mjs", "win32"); + const { stdout } = await exec( + process.execPath, + [ + "--import", + `data:text/javascript,${encodeURIComponent(capture)}`, + ...args.slice(0, -1), + "--input-type=module", + "-e", + fixture, + "--", + "--port", + "12345", + ], + { encoding: "utf8", windowsHide: true }, + ); + const [emulator, ffmpeg, withoutArgs, argv] = stdout + .trim() + .split(/\r?\n/) + .map((line) => JSON.parse(line)); + expect(emulator.slice(1)).toEqual([ + ["-avd", "Pixel"], + { detached: false, stdio: "ignore", env: { TEST: "preserved" }, windowsHide: true }, + ]); + expect(ffmpeg).toEqual(["ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }]); + expect(withoutArgs).toEqual([ + "emulator.exe", + { detached: false, cwd: "sdk", windowsHide: true }, + ]); + expect(argv).toEqual(["--port", "12345"]); + }); +}); diff --git a/apps/server/src/device/deviceHubNodeArgs.ts b/apps/server/src/device/deviceHubNodeArgs.ts new file mode 100644 index 0000000000000..5cd3c3629c63b --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.ts @@ -0,0 +1,25 @@ +// expo-device-hub detaches emulators without hiding their Windows console. Closing that +// console terminates the emulator; keep the workaround scoped to the hub process. +const WINDOWS_EMULATOR_PRELOAD = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +import { basename } from "node:path"; +const spawn = childProcess.spawn; +childProcess.spawn = function(command, ...args) { + if (typeof command === "string" && basename(command).toLowerCase() === "emulator.exe") { + const index = Array.isArray(args[0]) ? 1 : 0; + args[index] = { ...args[index], detached: false, windowsHide: true }; + } + return Reflect.apply(spawn, this, [command, ...args]); +}; +syncBuiltinESMExports(); +`; + +export const deviceHubNodeArgs = (entryPath: string, platform: NodeJS.Platform): string[] => + platform === "win32" + ? [ + "--import", + `data:text/javascript,${encodeURIComponent(WINDOWS_EMULATOR_PRELOAD)}`, + entryPath, + ] + : [entryPath]; From 26f4c7550e7ac954f63b9583a1905373aa07039c Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:57:43 -0600 Subject: [PATCH 019/278] fix(web): Esc in provider model filter clears it without closing Settings (#42076) Co-authored-by: Julius Marminge --- .../ProviderModelsSection.browser.test.tsx | 43 +++++++++++++++++++ .../settings/ProviderModelsSection.tsx | 7 +++ 2 files changed, 50 insertions(+) diff --git a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx index 4c0f25762fef3..375026245065f 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx @@ -179,3 +179,46 @@ it("cancels adding or editing a custom model on Escape without closing Settings" await userEvent.keyboard("{Escape}"); await expect.element(settings).not.toBeInTheDocument(); }); + +it("clears the model filter on Escape without closing Settings", async () => { + const manyModels = Array.from({ length: 9 }, (_, index) => ({ + slug: `gpt-${index}`, + name: `GPT ${index}`, + isCustom: false, + capabilities: null, + })); + await using _screen = await render( + {section({ models: manyModels })}, + { router: "/settings/providers" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + const filter = page.getByRole("textbox", { name: "Filter models" }); + await userEvent.type(filter, "gpt 1"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + filter.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + filter + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(filter).toHaveValue("gpt 1"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(filter).toHaveValue(""); + await expect.element(filter).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close Settings. + await act(() => { + filter + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + await expect.element(settings).toHaveAttribute("data-open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx index 921955c29dc9f..fb9bd2df702ea 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.tsx @@ -355,6 +355,13 @@ export function ProviderModelsSection({ setFilter(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) + return; + if (!filter && !event.repeat) return; + event.stopPropagation(); + setFilter(""); + }} placeholder={gt("Filter models")} size="sm" className="w-56 max-w-full" 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 020/278] 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 021/278] 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 022/278] 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 023/278] 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 024/278] 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 025/278] 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 026/278] 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 027/278] 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 028/278] 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 029/278] 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 030/278] =?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 052/278] 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 053/278] 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 054/278] 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 055/278] 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 056/278] 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 057/278] 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 058/278] 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 059/278] 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 060/278] 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 061/278] 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 062/278] 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 063/278] 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 064/278] 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 065/278] 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(