From 1c379b63bafbd5fa54b7fa15282b5900af7bd604 Mon Sep 17 00:00:00 2001 From: Filippo Mameli Date: Fri, 20 Nov 2026 16:16:33 +0100 Subject: [PATCH 1/6] fix(server): Antigravity links and discovers skills from skills.json (#39765) Co-authored-by: Julius Marminge --- .../Drivers/AntigravitySkills.test.ts | 75 ++++++ .../src/provider/Drivers/AntigravitySkills.ts | 227 ++++++++++++++++++ .../provider/antigravityAuthSupport.test.ts | 21 +- .../src/provider/antigravityAuthSupport.ts | 120 ++++----- docs/user/providers-antigravity.md | 6 +- 5 files changed, 391 insertions(+), 58 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 79f9bc438447c..e1bdbb66911f5 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -367,4 +367,79 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { } }), ); + + it.effect( + "reads skills declared in global and workspace skills.json with filters and inherits", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const input = yield* makeWorkspace(); + + const sharedSkills = path.join(input.userHome, ".agents", "skills"); + const keptPath = yield* writeSkill( + path.join(sharedSkills, "yagni"), + "---\nname: yagni\ndescription: Keep it simple.\n---\n", + ); + yield* writeSkill( + path.join(sharedSkills, "experimental-draft"), + "---\nname: experimental-draft\n---\n", + ); + + const inheritedSkills = path.join(input.userHome, "inherited-skills"); + const inheritedPath = yield* writeSkill( + path.join(inheritedSkills, "linter"), + "---\nname: linter\n---\n", + ); + yield* writeSkill(path.join(inheritedSkills, "skipped"), "---\nname: skipped\n---\n"); + // Backtracks exponentially under RegExp against the pattern below. + yield* writeSkill( + path.join(inheritedSkills, "a".repeat(40)), + "---\nname: backtrack\n---\n", + ); + + const projectSkills = path.join(input.cwd, "tools", "skills"); + const projectPath = yield* writeSkill( + path.join(projectSkills, "deploy"), + "---\nname: deploy\n---\n", + ); + + const globalConfigDir = path.join(input.userHome, ".gemini", "config"); + const inheritedConfigPath = path.join(input.userHome, "shared-skills.json"); + yield* fileSystem.makeDirectory(globalConfigDir, { recursive: true }); + yield* fileSystem.makeDirectory(path.join(input.cwd, ".agents"), { recursive: true }); + yield* fileSystem.writeFileString( + inheritedConfigPath, + JSON.stringify({ + inherits: [{ path: path.join(globalConfigDir, "skills.json") }], + entries: [{ path: "~/inherited-skills" }], + }), + ); + yield* fileSystem.writeFileString( + path.join(globalConfigDir, "skills.json"), + JSON.stringify({ + inherits: [{ path: inheritedConfigPath, include_only: ["linter", "(a*)*b"] }], + entries: [{ path: sharedSkills, exclude: ["experimental-.*"] }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, ".agents", "skills.json"), + JSON.stringify({ + entries: [{ path: "tools/skills" }], + }), + ); + + assert.deepEqual(yield* discoverAntigravitySkills(input), [ + { name: "deploy", path: projectPath, scope: "project", enabled: true }, + { name: "linter", path: inheritedPath, scope: "user", enabled: true }, + { + name: "yagni", + description: "Keep it simple.", + path: keptPath, + scope: "user", + enabled: true, + }, + ]); + }), + ); }); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index ddea4239745e8..b1d39feacefbd 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -37,6 +37,7 @@ export function antigravityUserSkillDirectories( const MAX_SKILL_BYTES = 1_000_000; const MAX_SCAN_BYTES = 8_000_000; const MAX_SCAN_ENTRIES = 10_000; +const MAX_INHERIT_DEPTH = 10; // Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget. const SKILL_READ_CHUNK_BYTES = 1024; @@ -45,6 +46,19 @@ const SkillFrontmatter = Schema.Struct({ description: Schema.optional(Schema.NullOr(Schema.String)), }); const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); +const SkillConfigEntry = Schema.Struct({ + path: Schema.String, + include_only: Schema.optional(Schema.Array(Schema.String)), + exclude: Schema.optional(Schema.Array(Schema.String)), +}); +const decodeSkillsConfig = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + inherits: Schema.optional(Schema.Array(SkillConfigEntry)), + entries: Schema.optional(Schema.Array(SkillConfigEntry)), + }), + ), +); const decodePluginPreferences = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ @@ -171,6 +185,139 @@ const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( return bytes.toString("utf8", 0, frontmatterEnd); }); +type SkillPatternMatcher = (entry: string) => boolean; + +interface SkillEntryFilter { + readonly includeGroups: ReadonlyArray>; + readonly excludePatterns: ReadonlyArray; +} + +const EMPTY_SKILL_FILTER: SkillEntryFilter = { + includeGroups: [], + excludePatterns: [], +}; + +interface SkillPatternToken { + readonly test: (character: string) => boolean; + readonly optional: boolean; + readonly repeats: boolean; +} + +/** Undefined for syntax outside literals, escapes, `.`, `[...]` and `* + ?`; such patterns match literally. */ +function parseSkillPattern(pattern: string): ReadonlyArray | undefined { + const characters = Array.from(pattern); + const tokens: Array = []; + let index = 0; + while (index < characters.length) { + const character = characters[index]!; + let test: (candidate: string) => boolean; + if (character === "\\") { + const escaped = characters[index + 1]; + if (escaped === undefined) return undefined; + if (/[dDwWsS]/.test(escaped)) { + const characterClass = new RegExp(`^\\${escaped}$`, "u"); + test = (candidate) => characterClass.test(candidate); + } else { + test = (candidate) => candidate === escaped; + } + index += 2; + } else if (character === "[") { + const close = characters.indexOf("]", index + 2); + if (close === -1) return undefined; + let characterClass: RegExp; + try { + characterClass = new RegExp(`^[${characters.slice(index + 1, close).join("")}]$`, "u"); + } catch { + return undefined; + } + test = (candidate) => characterClass.test(candidate); + index = close + 1; + } else if (character === ".") { + test = () => true; + index += 1; + } else if ("()|{}^$*+?".includes(character)) { + return undefined; + } else { + test = (candidate) => candidate === character; + index += 1; + } + const quantifier = characters[index]; + const optional = quantifier === "*" || quantifier === "?"; + const repeats = quantifier === "*" || quantifier === "+"; + if (optional || repeats) { + index += 1; + if (characters[index] === "?") index += 1; + } + tokens.push({ test, optional, repeats }); + } + return tokens; +} + +/** Manifests can come from an opened workspace, so matching runs as an NFA in linear time instead of RegExp. */ +function compileSkillPattern(pattern: string): SkillPatternMatcher { + const tokens = parseSkillPattern(pattern); + if (tokens === undefined) return (entry) => entry === pattern; + const close = (states: Set) => { + for (const state of states) { + if (state < tokens.length && tokens[state]!.optional) states.add(state + 1); + } + return states; + }; + return (entry) => { + let states = close(new Set([0])); + for (const character of entry) { + const next = new Set(); + for (const state of states) { + const token = tokens[state]; + if (!token?.test(character)) continue; + next.add(state + 1); + if (token.repeats) next.add(state); + } + if (next.size === 0) return false; + states = close(next); + } + return states.has(tokens.length); + }; +} + +function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { + for (const group of filter.includeGroups) { + if (!group.some((matches) => matches(entry))) return false; + } + return !filter.excludePatterns.some((matches) => matches(entry)); +} + +function narrowSkillFilter( + parent: SkillEntryFilter, + entry: { + readonly include_only?: ReadonlyArray | undefined; + readonly exclude?: ReadonlyArray | undefined; + }, +): SkillEntryFilter { + const includeGroups = + entry.include_only && entry.include_only.length > 0 + ? [...parent.includeGroups, entry.include_only.map(compileSkillPattern)] + : parent.includeGroups; + const excludePatterns = + entry.exclude && entry.exclude.length > 0 + ? [...parent.excludePatterns, ...entry.exclude.map(compileSkillPattern)] + : parent.excludePatterns; + return { includeGroups, excludePatterns }; +} + +function resolveSkillsConfigPath( + path: Path.Path, + rawPath: string, + baseDir: string, + userHome: string, +): string { + if (rawPath === "~") return userHome; + if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) { + return path.join(userHome, rawPath.slice(2)); + } + return path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseDir, rawPath); +} + /** Keep read errors typed so workspace snapshots cannot cache partial results. */ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: { readonly cwd: string; @@ -205,6 +352,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( directory: string, scope: string, scanChildren: boolean, + filter: SkillEntryFilter = EMPTY_SKILL_FILTER, ): Effect.fn.Return { const info = yield* readIfPresent(fileSystem.stat(directory), directory); if (info?.type !== "Directory") return; @@ -237,6 +385,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( } if (scanChildren) { const children = sortedEntries + .filter((entry) => matchesSkillFilter(entry, filter)) .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) })) .sort((left, right) => left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0, @@ -247,10 +396,88 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( } }); + const scanSkillsConfig = Effect.fn("scanAntigravitySkillsConfig")(function* ( + configPath: string, + baseDir: string, + scope: string, + filter: SkillEntryFilter, + visitedConfigs: ReadonlySet, + depth: number, + ): Effect.fn.Return { + if (depth > MAX_INHERIT_DEPTH) return; + const resolvedConfigPath = path.resolve(configPath); + if (visitedConfigs.has(resolvedConfigPath)) return; + const configInfo = yield* readIfPresent( + fileSystem.stat(resolvedConfigPath), + resolvedConfigPath, + ); + if (configInfo?.type !== "File") return; + const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes); + if (configInfo.size > BigInt(byteLimit)) { + return yield* new AntigravitySkillsProbeError({ + reason: "scan-budget-exhausted", + path: resolvedConfigPath, + }); + } + const raw = yield* readIfPresent( + fileSystem.readFileString(resolvedConfigPath), + resolvedConfigPath, + ); + if (raw === undefined) return; + budget.remainingBytes -= Buffer.byteLength(raw, "utf8"); + const parsed = decodeSkillsConfig(raw); + if (parsed._tag === "None") return; + + const nextVisited = new Set(visitedConfigs); + nextVisited.add(resolvedConfigPath); + for (const inherited of parsed.value.inherits ?? []) { + const inheritedPath = resolveSkillsConfigPath(path, inherited.path, baseDir, input.userHome); + yield* scanSkillsConfig( + inheritedPath, + path.dirname(inheritedPath), + scope, + narrowSkillFilter(filter, inherited), + nextVisited, + depth + 1, + ); + } + for (const entry of parsed.value.entries ?? []) { + const entryDirectory = resolveSkillsConfigPath(path, entry.path, baseDir, input.userHome); + yield* scanDirectory(entryDirectory, scope, true, narrowSkillFilter(filter, entry)); + } + }); + for (const root of roots) { yield* scanDirectory(root.directory, root.scope, true); } + for (const config of [ + { + configPath: path.resolve(input.cwd, ".agents", "skills.json"), + baseDir: input.cwd, + scope: "project", + }, + { + configPath: path.resolve(input.cwd, ".agent", "skills.json"), + baseDir: input.cwd, + scope: "project", + }, + { + configPath: path.join(input.userHome, ".gemini", "config", "skills.json"), + baseDir: path.join(input.userHome, ".gemini", "config"), + scope: "user", + }, + ]) { + yield* scanSkillsConfig( + config.configPath, + config.baseDir, + config.scope, + EMPTY_SKILL_FILTER, + new Set(), + 0, + ); + } + const pluginsDirectory = path.join(input.profileDirectory, "config", "plugins"); const plugins = yield* readIfPresent( fileSystem.readDirectory(pluginsDirectory), diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index f71ff0372a777..ca759ef80a72f 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -699,9 +699,13 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { const userHome = path.join(temporaryDirectory, "home"); const profileDirectory = path.join(temporaryDirectory, "profile"); const userGemini = path.join(userHome, ".gemini"); - yield* fs.makeDirectory(userGemini, { recursive: true }); + yield* fs.makeDirectory(path.join(userGemini, "config"), { recursive: true }); yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "global agents rule"); yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule"); + yield* fs.writeFileString( + path.join(userGemini, "config", "skills.json"), + JSON.stringify({ entries: [{ path: "/tmp/shared-skills" }] }), + ); yield* prepareAntigravityProfile({ profileDirectory, userHome }); expect(yield* fs.readLink(path.join(profileDirectory, "AGENTS.md"))).toBe( @@ -710,12 +714,17 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { expect(yield* fs.readLink(path.join(profileDirectory, "GEMINI.md"))).toBe( path.join(userGemini, "GEMINI.md"), ); + expect(yield* fs.readLink(path.join(profileDirectory, "config", "skills.json"))).toBe( + path.join(userGemini, "config", "skills.json"), + ); yield* fs.remove(path.join(userGemini, "AGENTS.md")); + yield* fs.remove(path.join(userGemini, "config", "skills.json")); yield* fs.remove(path.join(profileDirectory, "GEMINI.md")); yield* fs.writeFileString(path.join(profileDirectory, "GEMINI.md"), "profile's own rule"); yield* prepareAntigravityProfile({ profileDirectory, userHome }); expect(yield* fs.exists(path.join(profileDirectory, "AGENTS.md"))).toBe(false); + expect(yield* fs.exists(path.join(profileDirectory, "config", "skills.json"))).toBe(false); expect(yield* fs.readFileString(path.join(profileDirectory, "GEMINI.md"))).toBe( "profile's own rule", ); @@ -733,24 +742,32 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { const prepare = prepareAntigravityProfile({ profileDirectory, userHome, platform: "win32" }); const profileAgents = path.join(profileDirectory, "AGENTS.md"); const profileGemini = path.join(profileDirectory, "GEMINI.md"); - yield* fs.makeDirectory(userGemini, { recursive: true }); + const profileSkillsJson = path.join(profileDirectory, "config", "skills.json"); + const userSkillsJson = path.join(userGemini, "config", "skills.json"); + yield* fs.makeDirectory(path.join(userGemini, "config"), { recursive: true }); yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "global agents rule"); yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule"); + yield* fs.writeFileString(userSkillsJson, '{"entries":[]}'); yield* prepare; expect(yield* fs.readFileString(profileAgents)).toBe("global agents rule"); expect(yield* fs.readFileString(profileGemini)).toBe("global gemini rule"); + expect(yield* fs.readFileString(profileSkillsJson)).toBe('{"entries":[]}'); yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "edited agents rule"); yield* fs.remove(path.join(userGemini, "GEMINI.md")); + yield* fs.writeFileString(userSkillsJson, '{"entries":[{"path":"/skills"}]}'); yield* prepare; expect(yield* fs.readFileString(profileAgents)).toBe("edited agents rule"); expect(yield* fs.exists(profileGemini)).toBe(false); + expect(yield* fs.readFileString(profileSkillsJson)).toBe('{"entries":[{"path":"/skills"}]}'); yield* fs.writeFileString(profileGemini, "profile's own rule"); yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule"); + yield* fs.remove(userSkillsJson); yield* prepare; expect(yield* fs.readFileString(profileGemini)).toBe("profile's own rule"); + expect(yield* fs.exists(profileSkillsJson)).toBe(false); }), ); diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 12e34c8fa8f5f..8edd875839773 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -253,7 +253,11 @@ class AntigravitySkillLinkError extends Schema.TaggedError - [path.join(input.profileDirectory, name), path.join(userGemini, name), "file"] as const, + : antigravityUserConfigFiles.map( + (segments) => + [ + path.join(input.profileDirectory, ...segments), + path.join(userGemini, ...segments), + "file", + ] as const, )), ] as const) { yield* Effect.gen(function* () { @@ -329,54 +337,58 @@ const decodeRuleCopies = Schema.decodeUnknownOption(RuleCopiesJson); const encodeRuleCopies = Schema.encodeSync(RuleCopiesJson); /** Copies refresh each launch; the recorded copy keeps a file the profile owns or edited untouched. */ -const copyAntigravityUserRuleFiles = Effect.fn("copyAntigravityUserRuleFiles")(function* (input: { - readonly profileDirectory: string; - readonly userHome: string; -}): Effect.fn.Return { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const manifestPath = path.join(input.profileDirectory, ".t3-rule-copies.json"); - const readOptional = (file: string) => - fs.readFileString(file).pipe(Effect.orElseSucceed((): string | undefined => undefined)); - const manifestText = yield* readOptional(manifestPath); - const copies: Record = { - ...Option.getOrElse(decodeRuleCopies(manifestText), () => ({})), - }; - for (const name of antigravityUserRuleFiles) { - const link = path.join(input.profileDirectory, name); - const target = path.join(input.userHome, ".gemini", name); - yield* Effect.gen(function* () { - const current = yield* readOptional(link); - if (current !== undefined && current !== copies[name]) { - delete copies[name]; - return; - } - const source = yield* readOptional(target); - if (source === undefined) { - if (current !== undefined) yield* fs.remove(link); - delete copies[name]; - return; - } - yield* fs.writeFileString(link, source); - copies[name] = source; - }).pipe( - Effect.catch((error) => - Effect.logWarning("Antigravity user rules are not copied into the profile.", { - link, - target, - error, - }), - ), - ); - } - yield* fs - .writeFileString(manifestPath, encodeRuleCopies(copies)) - .pipe( - Effect.catch((error) => - Effect.logWarning("Antigravity rule copy record could not be written.", { error }), - ), - ); -}); +const copyAntigravityUserConfigFiles = Effect.fn("copyAntigravityUserConfigFiles")( + function* (input: { + readonly profileDirectory: string; + readonly userHome: string; + }): Effect.fn.Return { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const manifestPath = path.join(input.profileDirectory, ".t3-rule-copies.json"); + const readOptional = (file: string) => + fs.readFileString(file).pipe(Effect.orElseSucceed((): string | undefined => undefined)); + const manifestText = yield* readOptional(manifestPath); + const copies: Record = { + ...Option.getOrElse(decodeRuleCopies(manifestText), () => ({})), + }; + for (const segments of antigravityUserConfigFiles) { + const key = segments.join("/"); + const link = path.join(input.profileDirectory, ...segments); + const target = path.join(input.userHome, ".gemini", ...segments); + yield* Effect.gen(function* () { + const current = yield* readOptional(link); + if (current !== undefined && current !== copies[key]) { + delete copies[key]; + return; + } + const source = yield* readOptional(target); + if (source === undefined) { + if (current !== undefined) yield* fs.remove(link); + delete copies[key]; + return; + } + yield* fs.makeDirectory(path.dirname(link), { recursive: true }); + yield* fs.writeFileString(link, source); + copies[key] = source; + }).pipe( + Effect.catch((error) => + Effect.logWarning("Antigravity user configuration is not copied into the profile.", { + link, + target, + error, + }), + ), + ); + } + yield* fs + .writeFileString(manifestPath, encodeRuleCopies(copies)) + .pipe( + Effect.catch((error) => + Effect.logWarning("Antigravity rule copy record could not be written.", { error }), + ), + ); + }, +); export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: { readonly profileDirectory: string; @@ -526,7 +538,7 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( ); yield* linkAntigravityUserConfig({ profileDirectory: geminiHome, userHome, platform }); if (platform === "win32") { - yield* copyAntigravityUserRuleFiles({ profileDirectory: geminiHome, userHome }); + yield* copyAntigravityUserConfigFiles({ profileDirectory: geminiHome, userHome }); } return profile; }); diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 1720baa5e6f2e..614fda68f2c1d 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -102,8 +102,10 @@ wins in this order: `.gemini/skills`, `.agents/skills`, `.agent/skills`. See [commands and skills](./composer.md#commands-and-skills) for invoking them. Skills for every project go in `~/.gemini/config/skills` or -`~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills`, -so a skill there only appears when the project itself is your home directory. +`~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills` +on its own; to share a folder like that one, list it in `~/.gemini/config/skills.json` +(or a project's `.agents/skills.json`), and T3 Code shows the skills it declares, +honoring `inherits`, `include_only`, and `exclude`. Antigravity receives images and audio directly, and reads PDFs and text files as documents. Other attachments, including videos, are passed as a saved file path for From 905346e0d091bd447eff72d17f1b8296845e0aa2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 07:25:00 -0800 Subject: [PATCH 2/6] fix(desktop): WSL backend honors T3CODE_HOME from the distro's login shell (#39771) --- .../DesktopBackendConfiguration.test.ts | 55 +++++--- .../backend/DesktopBackendConfiguration.ts | 41 +++--- .../src/backend/DesktopBackendManager.ts | 2 + .../src/wsl/DesktopWslEnvironment.test.ts | 50 +++++-- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 130 +++++++++--------- 5 files changed, 159 insertions(+), 119 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 565a50f193e0f..fd820a2c478d1 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -354,7 +354,12 @@ describe("DesktopBackendConfiguration", () => { }, ensureNodePty: (distro) => { observedDistros.push(distro); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, getDistroIp: (distro) => { observedDistros.push(distro); @@ -385,10 +390,12 @@ describe("DesktopBackendConfiguration", () => { windowsArchivePath: string; runtimeId: string; sha256: string; + t3Home: string | null; }> = []; let probeCount = 0; let legacyCleanupCount = 0; - const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64"; + const t3Home = "/home/test/.config/t3"; + const linuxAppRoot = `${t3Home}/wsl-runtime/1.2.3-x64`; const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin"; return withPackagedWslHarness( @@ -399,17 +406,18 @@ describe("DesktopBackendConfiguration", () => { legacyCleanupCount += 1; }), wsl: () => ({ - prepareRuntime: (_distro, archive) => { + prepareRuntime: (_distro, archive, archiveT3Home) => { observedArchives.push({ windowsArchivePath: archive.windowsPath, runtimeId: archive.runtimeId, sha256: archive.sha256, + t3Home: archiveT3Home, }); return { ok: true, linuxAppRoot }; }, probeRuntime: () => { probeCount += 1; - return { ok: true, resolvedPath }; + return { ok: true, resolvedPath, t3Home }; }, ensureNodePty: () => { throw new Error("the staged runtime must not probe for node-pty"); @@ -427,6 +435,7 @@ describe("DesktopBackendConfiguration", () => { windowsArchivePath: archivePath, runtimeId: `sha256-${archiveHash}`, sha256: archiveHash, + t3Home, }, ]); assert.equal(probeCount, 1); @@ -442,12 +451,14 @@ describe("DesktopBackendConfiguration", () => { "--exec", "env", `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`, + `T3CODE_HOME=${t3Home}`, `${linuxAppRoot}/t3`, "--bootstrap-fd", "0", ]); assert.notInclude(config.args, "/usr/bin/node"); assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`); + assert.equal(config.wslT3Home, t3Home); assert.equal(legacyCleanupCount, 1); assert.isTrue(Option.isNone(config.preflightFailure)); }), @@ -470,6 +481,7 @@ describe("DesktopBackendConfiguration", () => { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin", + t3Home: null, }), }), }, @@ -502,10 +514,14 @@ describe("DesktopBackendConfiguration", () => { archiveHash: "b".repeat(64), wsl: () => ({ prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }), - invalidateRuntime: () => Effect.die("failed staging must not invalidate a runtime"), ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, }), }, @@ -524,28 +540,30 @@ describe("DesktopBackendConfiguration", () => { ); }); - it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => { + it.effect("resolveWsl does not stage a runtime when the login-shell probe fails", () => { const archiveHash = "c".repeat(64); const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`; let probeCount = 0; const observedNodePtyRoots: string[] = []; - const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( { archiveHash, wsl: () => ({ - prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }), - invalidateRuntime: (_distro, runtimeId) => - Effect.sync(() => { - invalidatedRuntimeIds.push(runtimeId); - }), + prepareRuntime: () => { + throw new Error("a failed probe must not stage the runtime"); + }, probeRuntime: () => { probeCount += 1; return { ok: false, reason: "WSL login-shell PATH could not be resolved" }; }, ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, }), }, @@ -562,23 +580,17 @@ describe("DesktopBackendConfiguration", () => { assert.equal(config.entryPath, mountedEntryPath); assert.isUndefined(config.wslRuntimeId); assert.isTrue(Option.isNone(config.preflightFailure)); - assert.deepEqual(invalidatedRuntimeIds, [`sha256-${archiveHash}`]); }), ); }); it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => { const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache"; - const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( { archiveHash: "f".repeat(64), wsl: () => ({ prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }), - invalidateRuntime: (_distro, runtimeId) => - Effect.sync(() => { - invalidatedRuntimeIds.push(runtimeId); - }), probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }), ensureNodePty: () => ({ ok: false, @@ -596,7 +608,6 @@ describe("DesktopBackendConfiguration", () => { assert.isFalse(failure.fatal); assert.equal(failure.retryLimit, 12); assert.include(failure.reason, "timed out"); - assert.deepEqual(invalidatedRuntimeIds, []); }), ); }); @@ -633,7 +644,7 @@ describe("DesktopBackendConfiguration", () => { isAvailable: true, distros: [{ name: "Ubuntu", isDefault: true, version: 2 }], windowsToWslPath: () => Option.some(linuxAppRoot), - ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }), + ensureNodePty: () => ({ ok: true, nodePath, resolvedPath, t3Home: null }), getDistroIp: () => Option.some("172.27.0.99"), }), ), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 82f0a30a40cd9..983c00a04c3fd 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -293,6 +293,7 @@ interface WslPreflightSuccess { readonly windowsEntryPath: string; readonly runtime: WslPreflightRuntime; readonly resolvedPath: string; + readonly t3Home: string | null; readonly runtimeId?: string; } @@ -412,7 +413,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const); }); - let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined; + let stagedFailure: { readonly reason: string } | undefined; const failedStaged = (failure: { readonly reason: string }) => ({ _tag: "Failed", @@ -421,11 +422,16 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f }) as const; if (input.runtimeArchive !== null) { - const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); - if (runtime.ok) { - // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. - const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); - if (stagedProbe.ok) { + // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. + // Probe first: the runtime cache lives under the login shell's T3CODE_HOME. + const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); + if (stagedProbe.ok) { + const runtime = yield* wslEnv.prepareRuntime( + runningDistro, + input.runtimeArchive, + stagedProbe.t3Home, + ); + if (runtime.ok) { yield* wslServerTree.cleanupLegacy; return { _tag: "Ready", @@ -433,20 +439,21 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f windowsEntryPath: environment.backendEntryPath, runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` }, resolvedPath: stagedProbe.resolvedPath, + t3Home: stagedProbe.t3Home, runtimeId: input.runtimeArchive.runtimeId, } as const; } - yield* Effect.logWarning( - "The staged WSL runtime probe failed; retrying from the mounted server tree.", - { reason: stagedProbe.reason }, - ); - stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason }; - } else { stagedFailure = { reason: runtime.reason }; yield* Effect.logWarning( "Could not stage the WSL runtime; launching from the mounted server tree instead.", { reason: runtime.reason }, ); + } else { + yield* Effect.logWarning( + "The staged WSL runtime probe failed; retrying from the mounted server tree.", + { reason: stagedProbe.reason }, + ); + stagedFailure = { reason: stagedProbe.reason }; } } @@ -469,10 +476,6 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : failedNodePty(nodePtyResult); } - if (stagedFailure?.runtimeId) { - yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); - } - return { _tag: "Ready", runningDistro, @@ -483,6 +486,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`, }, resolvedPath: nodePtyResult.resolvedPath, + t3Home: nodePtyResult.t3Home, } as const; }); @@ -745,13 +749,16 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl "--exec", "env", `PATH=${launchPath}`, + ...(preflight.t3Home === null ? [] : [`T3CODE_HOME=${preflight.t3Home}`]), ...command, "--bootstrap-fd", "0", ...devUrlArgs, ], preflightFailure: Option.none(), - ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }), + ...(preflight.runtimeId === undefined + ? {} + : { wslRuntimeId: preflight.runtimeId, wslT3Home: preflight.t3Home }), } satisfies DesktopBackendManager.DesktopBackendStartConfig; }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 8b4f154b5d4de..4f7e115a5456f 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -84,6 +84,7 @@ export interface DesktopBackendStartConfig extends BackendProcessContext { readonly preflightFailure: Option.Option; readonly runningDistro?: string; readonly wslRuntimeId?: string; + readonly wslT3Home?: string | null; } export interface PreflightFailure { @@ -992,6 +993,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( yield* wslEnvironment.pruneRuntimes( config.value.runningDistro, config.value.wslRuntimeId, + config.value.wslT3Home ?? null, ); } }), diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 7f4a2507a736e..a563b6a4ee3a7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -22,10 +22,10 @@ import { layer as layerDesktopWslEnvironment, buildWslRuntimeInstallScript, makeIsAvailable, - buildWslRuntimeInvalidateScript, buildWslRuntimePruneScript, buildWslRuntimeProbeScript, parseResolvedPath, + parseT3Home, parseWslRuntimeRoot, windowsToWslPathImpl, } from "./DesktopWslEnvironment.ts"; @@ -96,10 +96,9 @@ describe("WSL runtime cache", () => { it.each([ [ "install", - (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)), + (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64), null), ], - ["prune", buildWslRuntimePruneScript], - ["invalidate", buildWslRuntimeInvalidateScript], + ["prune", (id: string) => buildWslRuntimePruneScript(id, null)], ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => { const runtimeId = "1.2.3/x64; touch /tmp/nope"; const script = buildScript(runtimeId); @@ -139,11 +138,11 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed const archiveSha = readField(result.stdout, "archiveSha"); const runtimeId = `sha256-${archiveSha}`; // WSL does not inherit HOME; embed the fixture's override in the script. - const installScript = (archive = archivePath, sha = archiveSha) => + const installScript = (archive = archivePath, sha = archiveSha, t3Home: string | null = null) => [ `HOME=${sh(`${work}/home`)}`, "export HOME", - buildWslRuntimeInstallScript(archive, runtimeId, sha), + buildWslRuntimeInstallScript(archive, runtimeId, sha, t3Home), ].join("\n"); return { work, @@ -154,7 +153,8 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`, serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`, installScript, - install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)), + install: (archive?: string, sha?: string, t3Home?: string | null) => + runShell(installScript(archive, sha, t3Home)), }; }; @@ -200,6 +200,24 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(provider.stdout).toBe("linux-node-provider\n"); }); + it("stages the runtime under the login shell's T3CODE_HOME and reports it to the launcher", () => { + const fixture = createFixture(); + const t3Home = `${fixture.work}/home/.config/t3 home`; + const install = fixture.install(undefined, undefined, t3Home); + expect(install.status, install.stderr).toBe(0); + expect(parseWslRuntimeRoot(install.stdout)).toBe(`${t3Home}/wsl-runtime/${fixture.runtimeId}`); + expect(runShell(`test ! -e ${sh(`${fixture.work}/home/.t3`)}`).status).toBe(0); + + const probe = runShell( + [ + `bash() { ( export T3CODE_HOME=${sh(t3Home)}; eval "$2" ); }`, + buildWslRuntimeProbeScript(), + ].join("\n"), + ); + expect(probe.status, probe.stderr).toBe(0); + expect(parseT3Home(probe.stdout)).toBe(t3Home); + }); + it("keeps the inherited PATH when bash is unavailable", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); @@ -382,7 +400,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed `sh ${sh(`${fixture.work}/select.sh`)}`, `HOME=${sh(`${fixture.work}/home`)}`, "export HOME", - buildWslRuntimePruneScript("sha256-current"), + buildWslRuntimePruneScript("sha256-current", null), `test -d ${sh(fixture.runtimeRoot)}`, ].join("\n"), ); @@ -463,11 +481,15 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath); expect(translated._tag).toBe("None"); - const prepared = yield* wsl.prepareRuntime("Ubuntu", { - windowsPath: fixture.archivePath, - runtimeId: fixture.runtimeId, - sha256: fixture.archiveSha, - }); + const prepared = yield* wsl.prepareRuntime( + "Ubuntu", + { + windowsPath: fixture.archivePath, + runtimeId: fixture.runtimeId, + sha256: fixture.archiveSha, + }, + null, + ); expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot }); const version = runShell(`${sh(fixture.serverEntry)} --version`); @@ -500,7 +522,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'), `HOME="$home"`, "export HOME", - buildWslRuntimePruneScript("sha256-current"), + buildWslRuntimePruneScript("sha256-current", null), 'test -d "$runtime_parent/sha256-current"', 'test -d "$runtime_parent/sha256-previous"', 'test -d "$runtime_parent/sha256-active"', diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 5ba7d3794fad1..f1d2fccde537b 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -60,6 +60,7 @@ export type EnsureWslNodePtyResult = readonly ok: true; readonly nodePath: string; readonly resolvedPath: string; + readonly t3Home: string | null; } | { readonly ok: false; @@ -72,6 +73,7 @@ export type ProbeWslRuntimeResult = | { readonly ok: true; readonly resolvedPath: string; + readonly t3Home: string | null; } | { readonly ok: false; @@ -104,12 +106,17 @@ export class DesktopWslEnvironment extends Context.Service< readonly getUserHome: (distro: string | null) => Effect.Effect>; // Use the distro IP to avoid unreliable wslhost localhost forwarding. readonly getDistroIp: (distro: string | null) => Effect.Effect>; + // A null t3Home means the distro's login shell has no absolute T3CODE_HOME, so ~/.t3 applies. readonly prepareRuntime: ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, ) => Effect.Effect; - readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect; + readonly pruneRuntimes: ( + distro: string | null, + runtimeId: string, + t3Home: string | null, + ) => Effect.Effect; readonly probeRuntime: (distro: string | null) => Effect.Effect; readonly ensureNodePty: ( distro: string | null, @@ -264,16 +271,22 @@ const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5; const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_"); +const runtimeParentAssignment = (t3Home: string | null): string => + t3Home === null + ? 'runtime_parent="$HOME/.t3/wsl-runtime"' + : `runtime_parent=${shellQuote(`${t3Home}/wsl-runtime`)}`; + // A null archive path asks for a staging directory to copy the archive into, unless the cache is ready. export const buildWslRuntimeInstallScript = ( linuxArchivePath: string | null, runtimeId: string, archiveSha256: string, + t3Home: string | null, ): string => { const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); const readyCheck = [ "set -eu", - 'runtime_parent="$HOME/.t3/wsl-runtime"', + runtimeParentAssignment(t3Home), `runtime_root="$runtime_parent/${safeRuntimeId}"`, `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`, "runtime_entry_runs() {", @@ -369,11 +382,11 @@ export const buildWslRuntimeInstallScript = ( // Two hours exceeds cold-install time while bounding orphan retention. const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120; -export const buildWslRuntimePruneScript = (runtimeId: string): string => { +export const buildWslRuntimePruneScript = (runtimeId: string, t3Home: string | null): string => { const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); return [ "set -eu", - 'runtime_parent="$HOME/.t3/wsl-runtime"', + runtimeParentAssignment(t3Home), `current_runtime="$runtime_parent/${safeRuntimeId}"`, '[ -d "$runtime_parent" ] || exit 0', // Serialize pruning so backends cannot select and delete different previous caches. @@ -419,15 +432,6 @@ export const buildWslRuntimePruneScript = (runtimeId: string): string => { ].join("\n"); }; -// Invalidate trees that pass install checks but fail launch probes, or each launch reuses the broken cache. -export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => { - const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); - return [ - "set -eu", - `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`, - ].join("\n"); -}; - const parseAbsolutePathField = (stdout: string, field: string): string | null => { const prefix = `${field}:`; const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix)); @@ -448,12 +452,15 @@ const formatNodePtyProbeFailureReason = (exitCode: number): string | null => // Capture login-shell PATH because the server launches provider CLIs by name. const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`; +// wsl.exe --exec skips the profile, so the server only sees a profile-exported T3CODE_HOME if passed on. +const T3_HOME_LINE = `printf 't3Home:%s\\n' "\${T3CODE_HOME:-}"`; const NODE_PTY_PROBE_SCRIPT = ( linuxServerDir: string, ) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)" printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)" ${RESOLVED_PATH_LINE} +${T3_HOME_LINE} cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1 // The WSL Node can't read inside app.asar, so confirm what the server needs is // unpacked on the real filesystem before reporting the backend healthy. Exit 3 @@ -482,7 +489,7 @@ NODE`; // Resolve version-managed Node for providers without making runtime readiness depend on it. // The install script already ran the staged t3, so running it again here only adds a second startup. export const buildWslRuntimeProbeScript = () => - `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; + `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}\n${T3_HOME_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; const TOOLCHAIN_CHECK_SCRIPT = [ "for tool in node make g++ python3; do", @@ -553,6 +560,10 @@ export const parseResolvedPath = (stdout: string): string | null => { return resolvedPath.length > 0 ? resolvedPath : null; }; +// Relative values are ignored: the runtime scripts and the server would resolve them from different cwds. +export const parseT3Home = (stdout: string): string | null => + parseAbsolutePathField(stdout, "t3Home"); + const formatMissingToolsReason = ( report: ToolchainReport, requiredRange: string | null, @@ -614,7 +625,7 @@ const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl reason: "WSL login-shell PATH could not be resolved during backend preflight.", } as const; } - return { ok: true, resolvedPath } as const; + return { ok: true, resolvedPath, t3Home: parseT3Home(probe.stdout) } as const; }); const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* ( @@ -634,6 +645,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f ); const nodePath = parseNodePath(probe.stdout); const resolvedPath = parseResolvedPath(probe.stdout); + const t3Home = parseT3Home(probe.stdout); const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure); if (transportFailureReason !== null) { @@ -700,7 +712,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f fatal: true, } as const; } - return { ok: true, nodePath, resolvedPath } as const; + return { ok: true, nodePath, resolvedPath, t3Home } as const; } if (options.allowBuild !== true) { @@ -773,7 +785,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f retryLimit: BUILD_TRANSPORT_RETRY_LIMIT, } as const; } - if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const; + if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath, t3Home } as const; const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500); return { ok: false, @@ -789,11 +801,12 @@ type WslRuntimeInstallOutcome = const runWslRuntimeInstall = Effect.fn("desktop.wsl.runRuntimeInstall")(function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, linuxArchivePath: string | null, ): Effect.fn.Return { const install = yield* runWslShell( distro, - buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256), + buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256, t3Home), RUNTIME_INSTALL_TIMEOUT, { resolveNode: false }, ); @@ -832,9 +845,10 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, archiveBytes: Stream.Stream, ): Effect.fn.Return { - const staged = yield* runWslRuntimeInstall(distro, archive, null); + const staged = yield* runWslRuntimeInstall(distro, archive, t3Home, null); if (!staged.ok || parseWslRuntimeRoot(staged.stdout) !== null) { return toPrepareWslRuntimeResult(staged); } @@ -875,7 +889,7 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH } as const; } return toPrepareWslRuntimeResult( - yield* runWslRuntimeInstall(distro, archive, linuxArchivePath), + yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath), ); }); @@ -892,6 +906,7 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, windowsToWslPath: ( distro: string | null, windowsPath: string, @@ -907,21 +922,23 @@ const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(functi return yield* installWslRuntimeFromHostCopy( distro, archive, + t3Home, fileSystem.stream(archive.windowsPath), ); } return toPrepareWslRuntimeResult( - yield* runWslRuntimeInstall(distro, archive, linuxArchivePath.value), + yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath.value), ); }); const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* ( distro: string | null, runtimeId: string, + t3Home: string | null, ): Effect.fn.Return { const result = yield* runWslShell( distro, - buildWslRuntimePruneScript(runtimeId), + buildWslRuntimePruneScript(runtimeId, t3Home), RUNTIME_PRUNE_TIMEOUT, { resolveNode: false }, ); @@ -935,26 +952,6 @@ const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function }); }); -const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* ( - distro: string | null, - runtimeId: string, -): Effect.fn.Return { - const result = yield* runWslShell( - distro, - buildWslRuntimeInvalidateScript(runtimeId), - RUNTIME_INVALIDATE_TIMEOUT, - { resolveNode: false }, - ); - if (result.transportFailure === null && result.exitCode === 0) return; - - const detail = `${result.stdout}${result.stderr}`.trim().slice(-500); - yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", { - distro, - runtimeId, - detail: detail || `exit ${result.exitCode}`, - }); -}); - const probeWslDistros: Effect.Effect< readonly WslDistro[], DesktopWslDistroListError, @@ -1154,9 +1151,13 @@ export interface DesktopWslEnvironmentTestStub { readonly prepareRuntime?: ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, ) => PrepareWslRuntimeResult; - readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect; + readonly pruneRuntimes?: ( + distro: string | null, + runtimeId: string, + t3Home: string | null, + ) => Effect.Effect; readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult; readonly ensureNodePty?: ( distro: string | null, @@ -1188,20 +1189,19 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) { return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none()); }), - prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) { - return Effect.succeed( - stub.prepareRuntime?.(distro, archive) ?? { - ok: false, - reason: "prepareRuntime stub not configured", - }, - ); - }), - pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) { - return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void; - }), - invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")( - function (distro, runtimeId) { - return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void; + prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")( + function (distro, archive, t3Home) { + return Effect.succeed( + stub.prepareRuntime?.(distro, archive, t3Home) ?? { + ok: false, + reason: "prepareRuntime stub not configured", + }, + ); + }, + ), + pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")( + function (distro, runtimeId, t3Home) { + return stub.pruneRuntimes?.(distro, runtimeId, t3Home) ?? Effect.void; }, ), probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) { @@ -1209,6 +1209,7 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { stub.probeRuntime?.(distro) ?? { ok: true, resolvedPath: "/usr/bin:/bin", + t3Home: null, }, ); }), @@ -1288,18 +1289,15 @@ export const layer = Layer.effect( windowsToWslPath, getUserHome, getDistroIp, - prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) { + prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive, t3Home) { return provideSpawner( - prepareWslRuntimeImpl(distro, archive, windowsToWslPath).pipe( + prepareWslRuntimeImpl(distro, archive, t3Home, windowsToWslPath).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), ), ); }), - pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) { - return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)); - }), - invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) { - return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)); + pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId, t3Home) { + return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId, t3Home)); }), probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) { return provideSpawner(probeWslRuntimeImpl(distro)); From f08272f965525e21ace4af1eddd308cb3d3d6de6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 07:29:52 -0800 Subject: [PATCH 3/6] fix(server): pull_request_create opens a draft PR as a draft on GitHub and Azure (#39772) --- apps/server/src/git/GitManager.test.ts | 32 ++++++++++++++++++- apps/server/src/git/GitManager.ts | 9 +++++- .../src/server/AzureDevOpsCli.test.ts | 11 +++++++ .../src/server/AzureDevOpsCli.ts | 2 ++ .../AzureDevOpsSourceControlProvider.ts | 2 ++ .../src/server/SourceControlProvider.ts | 4 +++ .../src/server/OriginSourceControlProvider.ts | 5 +-- .../GitHubSourceControlProvider.test.ts | 9 ++++++ .../src/server/GitHubSourceControlProvider.ts | 2 ++ 9 files changed, 72 insertions(+), 4 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 73da4ec2a6bac..ae35e44cd3ccf 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -84,6 +84,8 @@ interface FakeProviderScenario { }; /** The kind the fake host reports itself as. */ kind?: string; + /** False for a host that opens every change request ready for review. */ + createsDraftChangeRequests?: boolean; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -119,6 +121,7 @@ type FakeProviderCall = readonly baseRefName: string; readonly headSelector: string; readonly title: string; + readonly draft: unknown; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -477,6 +480,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { return { service: { kind, + createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -509,6 +513,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { baseRefName: input.baseRefName, headSelector: input.headSelector, title: input.title, + draft: "draft" in input ? input.draft : undefined, }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -4488,7 +4493,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { // A draft of a PR the host does not list yet fails, so a retry drafts it. yield* runGit(repoDir, ["push"]); - const unlisted = yield* makeManager({ providerScenario: { prListSequence: [[], []] } }); + const unlisted = yield* makeManager({ + providerScenario: { prListSequence: [[], []], createsDraftChangeRequests: false }, + }); const notListed = yield* Effect.flip( unlisted.manager.createPullRequest({ cwd: repoDir, @@ -4500,6 +4507,29 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ); expect(notListed.message).toContain("does not list it yet"); expect(created(unlisted.providerCalls)).toHaveLength(1); + + // A new PR asked for as a draft is opened as one, never ready first. + const newActions: Array = []; + const fresh = yield* makeManager({ + providerScenario: { prListSequence: [[], [open]] }, + pullRequests: { + summary: () => Effect.succeed({ isDraft: false } as never), + runAction: (action) => Effect.sync(() => void newActions.push(action)), + }, + }); + yield* fresh.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Feature", + body: "Body", + draft: true, + }); + expect( + fresh.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call.draft] : [], + ), + ).toEqual([true]); + expect(newActions).toEqual([]); }), ); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 77acae07dee63..92b961d763b46 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2465,6 +2465,7 @@ export const make = Effect.gen(function* () { emit: GitActionProgressEmitter, pushRemoteRef: { readonly remoteName: string; readonly upstreamRef: string } | undefined, requestedBase: string | undefined, + draft: boolean, content: (input: { readonly provider: SourceControlProvider.SourceControlProvider["Service"]; readonly baseBranch: string; @@ -2563,6 +2564,7 @@ export const make = Effect.gen(function* () { : {}), title: generated.title, bodyFile, + ...(draft ? { draft: true } : {}), }) .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore))); @@ -2608,6 +2610,7 @@ export const make = Effect.gen(function* () { emit, pushRemoteRef, undefined, + false, ({ provider, baseBranch, baseRef, headBranch }) => Effect.gen(function* () { const terms = sourceControlDefinitions.get(provider.kind).changeRequest; @@ -2652,11 +2655,15 @@ export const make = Effect.gen(function* () { () => Effect.void, undefined, input.baseBranch, + input.draft === true, () => Effect.succeed({ title: input.title, body: input.body }), ); // The thread's branch PR comes from status, which may hold the lookup from before. if (result.status === "created") yield* invalidateStatus(input.cwd); - if (input.draft === true && !(yield* draftOpened(input, result))) { + const openedAsDraft = + result.status === "created" && + (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; + if (input.draft === true && !openedAsDraft && !(yield* draftOpened(input, result))) { // A retry finds the open PR and drafts it then. return yield* new GitManagerError({ operation: "createPullRequest", diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 200f2d67fdb80..6e4600fe5a338 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -314,6 +314,17 @@ describe("AzureDevOpsCli.layer", () => { // az expands a separate `@file` value a second time, so a body of `@notes.txt` read notes.txt. expect(mockRun.mock.calls.at(-1)?.[0].args).toContain("--description=@/tmp/body.md"); } + + mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}"))); + yield* az.createPullRequest({ + cwd: "/somewhere", + baseBranch: "main", + headSelector: "feature", + title: "Draft", + bodyFile: "/tmp/body.md", + draft: true, + }); + expect(mockRun.mock.calls.at(-1)?.[0].args.join(" ")).toContain("--draft true"); }).pipe(Effect.provide(layer)), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 4052429d18a57..6cffe9ab0b3ab 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -261,6 +261,7 @@ export class AzureDevOpsCli extends Context.Service< readonly target?: SourceControlProvider.SourceControlRefSelector; readonly title: string; readonly bodyFile: string; + readonly draft?: boolean; readonly remoteUrl?: string; }) => Effect.Effect; @@ -746,6 +747,7 @@ export const make = Effect.gen(function* () { title.arg, // Joined: az expands a separate `@file` value again, so a body of `@path` read that file. `--description=@${input.bodyFile}`, + ...(input.draft === true ? ["--draft", "true"] : []), ], ...(title.stdin === undefined ? {} : { stdin: title.stdin }), }).pipe(Effect.asVoid); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts index 83df3683f7755..88a6fd7db6e1a 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts @@ -178,6 +178,7 @@ export const make = Effect.gen(function* () { ); }, ), + createsDraftChangeRequests: true, createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")( function (input) { const source = SourceControlProvider.sourceControlRefFromInput(input); @@ -191,6 +192,7 @@ export const make = Effect.gen(function* () { ...(input.target !== undefined ? { target: input.target } : {}), title: input.title, bodyFile: input.bodyFile, + ...(input.draft === true ? { draft: true } : {}), }) .pipe( Effect.mapError( diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index d24fc6f9d82d0..8b16b7943605e 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -171,6 +171,8 @@ export class SourceControlProvider extends Context.Service< readonly branch: string; readonly baseBranch: string; }) => Effect.Effect; + /** True when `createChangeRequest` opens the change request as a draft when asked. */ + readonly createsDraftChangeRequests?: boolean; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -193,6 +195,8 @@ export class SourceControlProvider extends Context.Service< readonly headSelector: string; readonly title: string; readonly bodyFile: string; + /** Honored only by a provider with `createsDraftChangeRequests`. */ + readonly draft?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-cursor-origin/src/server/OriginSourceControlProvider.ts b/packages/source-control-cursor-origin/src/server/OriginSourceControlProvider.ts index 6128de0baff4e..e36a025649d98 100644 --- a/packages/source-control-cursor-origin/src/server/OriginSourceControlProvider.ts +++ b/packages/source-control-cursor-origin/src/server/OriginSourceControlProvider.ts @@ -193,10 +193,11 @@ export const make = Effect.gen(function* () { effect.pipe(mapError("getChangeRequest", input.cwd, { reference: input.reference })), ), + createsDraftChangeRequests: true, createChangeRequest: Effect.fn("OriginSourceControlProvider.createChangeRequest")( function* (input) { const repository = input.target?.repository ?? (yield* cli.resolveRepository(input)); - // Origin creates drafts unless told otherwise; T3 asks for draft explicitly elsewhere. + // Origin creates drafts unless told otherwise, so `draft` is always sent. yield* cli.api( { cwd: input.cwd, @@ -208,7 +209,7 @@ export const make = Effect.gen(function* () { body: yield* fs.readFileString(input.bodyFile), head: SourceControlProvider.sourceBranch(input), base: input.target?.refName ?? input.baseRefName, - draft: false, + draft: input.draft === true, }, }, Schema.Unknown, diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts index 816f855d86439..560f503a76c16 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts @@ -612,6 +612,15 @@ describe("GitHubSourceControlProvider writes", () => { body: "Body", maintainer_can_modify: true, }); + yield* gh.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "me:feature", + title: "Title", + bodyFile, + draft: true, + }); + assert.strictEqual((requests[1]!.body as { draft?: unknown }).draft, true); }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer))); }); diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts index f69e06fedc663..2d9c298e4d7f6 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts @@ -1101,6 +1101,7 @@ export const make = Effect.gen(function* () { ), ); }), + createsDraftChangeRequests: true, createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")( function* (input) { const locator = yield* resolveRepository(input); @@ -1124,6 +1125,7 @@ export const make = Effect.gen(function* () { title: input.title, body, maintainer_can_modify: true, + ...(input.draft === true ? { draft: true } : {}), }, }); }, From e24f0c7154cc625a401545b3e49cc5776802c210 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 07:31:03 -0800 Subject: [PATCH 4/6] fix(server): Antigravity wake runs accept steers again (#39767) --- .../Adapters/AntigravityAdapterV2.test.ts | 67 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 17 ++--- 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index c1f3b72b77f93..e87b96f990466 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1414,6 +1414,73 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A wake run has no prompt of its own, yet agy can keep working in it for minutes. + it.effect("steers a continuation run that keeps working after its wake", () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand( + { IsDaemon: true, WaitMsBeforeAsync: 500 }, + undefined, + { agentVersion: "1.5.11", holdsFirstPrompt: false }, + ); + const { session, providerThread, command, offers, send, startTurn, until, throughTerminal } = + opened; + yield* startTurn(1, false); + yield* throughTerminal; + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + assert.lengthOf(offers, 1, "the finished daemon must wake the thread"); + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + const followUp = { toolCallId: "call_build", kind: "execute", title: "vp run build" }; + yield* send({ sessionUpdate: "tool_call", ...followUp, status: "in_progress" }); + const continued = yield* until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === followUp.toolCallId, + ); + const providerTurnId = continued.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]!; + + const steer = yield* session + .steerTurn({ + threadId: ThreadId.make("thread-antigravity-wake"), + runId: RunId.make("run-antigravity-wake-2"), + providerThread, + providerTurnId, + message: { + messageId: MessageId.make("message-antigravity-steer"), + text: "Skip the build", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + }) + .pipe(Effect.exit); + assert.isTrue( + Exit.isSuccess(steer), + `a working wake run must accept a steer: ${String(Exit.isFailure(steer) && steer.cause)}`, + ); + assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's work"); + assert.lengthOf(opened.prompts, 2); + assert.deepEqual(opened.prompts[1]!.prompt, [{ type: "text", text: "Skip the build" }]); + + yield* send({ sessionUpdate: "tool_call_update", ...followUp, status: "completed" }); + yield* TestClock.adjust("16 minutes"); + const silent = yield* until((event) => event.type === "turn.terminal"); + const terminal = silent.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "failed", + "a silent steer prompt must still hit the inactivity timeout", + ); + }).pipe(Effect.provide(layerSession)), + ); + it.effect("steers a run held open by a detached subagent without stopping it", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 9af7a307d6efb..d25274bb9a4ce 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9539,7 +9539,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( text, turnInput.message.attachments, ); - const dispatched = yield* runtimeTransitionPermit.withPermit( + const [dispatched, context] = yield* runtimeTransitionPermit.withPermit( Effect.gen(function* () { const context = yield* Ref.get(activeTurn); if ( @@ -9553,14 +9553,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, }); } - // A wake turn has no prompt of its own to steer; its reply ends the run soon. - if (context.promptSequence === 0) { - return yield* new ProviderAdapter.ProviderAdapterSteerDeclinedError({ - driver, - providerThreadId: turnInput.providerThread.id, - providerTurnId: turnInput.providerTurnId, - }); - } const generation = yield* Ref.get(runtimeCallbackGeneration); const checkPromptOutcome = flavor.watchPromptOutcome === undefined @@ -9624,10 +9616,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: `Provider turn ${turnInput.providerTurnId} ended before it could be steered.`, }); } - return dispatched; + return [dispatched, context] as const; }), ); yield* Deferred.await(dispatched); + // A wake run sent no prompt, so its inactivity watchdog waits for this one. + yield* Deferred.succeed(context.promptDispatched, undefined); }); yield* Effect.addFinalizer(() => @@ -9967,8 +9961,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (effect, turnInput) => effect.pipe( Effect.mapError((cause) => - cause._tag === "ProviderAdapterSteerRunUnsupportedError" || - cause._tag === "ProviderAdapterSteerDeclinedError" + cause._tag === "ProviderAdapterSteerRunUnsupportedError" ? cause : new ProviderAdapter.ProviderAdapterSteerRunError({ driver, From 31e31c608d33da7755eb331ed214ab42eda29d04 Mon Sep 17 00:00:00 2001 From: cxuan <33996561+crisxuan@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:34:27 -0800 Subject: [PATCH 5/6] fix(server): keep DeepSeek ACP probes out of session history (#39733) Co-authored-by: Julius Marminge --- .../src/provider/AcpRegistryProbe.test.ts | 59 +++++++++++++++++++ .../src/server/driver.ts | 6 ++ .../provider-acp-registry/src/server/probe.ts | 52 +++++++++++++++- 3 files changed, 116 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 30915b31d474f..6c0766d1cf7d8 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -467,6 +467,65 @@ describe("ACP Registry probe", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.live("keeps DeepSeek Harness probe history in a temporary directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-probe-dsh-" }); + const launcher = NodePath.join(directory, "dsh-fixture.mjs"); + const launchLog = NodePath.join(directory, "launch.json"); + yield* fs.writeFileString( + launcher, + ` +import { readFileSync, writeFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; +const [,, agentPath, logPath, ...args] = process.argv; +const patchFlag = args.lastIndexOf("--patch"); +const patchPath = patchFlag === -1 ? null : args[patchFlag + 1]; +const patch = patchPath === null ? null : JSON.parse(readFileSync(patchPath, "utf8")); +writeFileSync(logPath, JSON.stringify({ args, patch })); +await import(pathToFileURL(agentPath).href); +`, + ); + const userPatch = NodePath.join(directory, "user-patch.json"); + yield* fs.writeFileString(userPatch, "[]"); + const commandArgs = ["--profile", "acp", "--patch", userPatch]; + const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + inspect: () => Effect.die("unused inspect"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + resolve: () => + Effect.succeed({ + distribution: "local", + spawn: { + command: process.execPath, + args: [launcher, mockAgentPath, launchLog, ...commandArgs], + }, + }), + }); + const result = yield* probeAcpRegistryConfiguration({ + instanceId, + settings: decodeSettings({ source: "local", commandPath: "dsh", commandArgs }), + cwd: directory, + environment: process.env, + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + expect(result.probe.ready).toBe(true); + expect(result.probe.models.length).toBeGreaterThan(0); + + const { args, patch } = JSON.parse(yield* fs.readFileString(launchLog)); + expect(args).toEqual([...commandArgs, "--patch", expect.any(String)]); + const probeDirectory = NodePath.dirname(args.at(-1)); + expect(patch).toEqual([ + { + id: "session-persistence-jsonl", + config: { root: NodePath.join(probeDirectory, "sessions") }, + }, + { id: "session-projection-cache", disabled: true }, + ]); + expect(yield* fs.exists(probeDirectory)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it("distinguishes authentication failures from generic probe failures", () => { const advertised = normalizeAcpRegistryAuthMethods([ { id: "grok-login", name: "Log in with Grok" }, diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 2346a9c782c76..46d8ed3219aa4 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -18,7 +18,9 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; +import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; @@ -635,6 +637,8 @@ export const AcpRegistryDriver: ProviderDriver({ diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index c012f38d195df..03002f914adf5 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -16,10 +16,13 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; @@ -50,6 +53,7 @@ const COMMAND_ADVERTISEMENT_GRACE = "500 millis"; // settle it in seconds, not milliseconds; commands arrive much sooner. const MODEL_ADVERTISEMENT_GRACE = "5 seconds"; const PROBE_SESSION_DELETE_TIMEOUT = "5 seconds"; +const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const boundedText = (value: string, maximumLength: number): string => value.trim().slice(0, maximumLength); @@ -388,6 +392,37 @@ export type AcpRegistryConfigurationProbe = ( input: AcpRegistryConfigurationProbeInput, ) => Effect.Effect; +const isolateDeepSeekProbeHistory = Effect.fn("AcpRegistryProbe.isolateDeepSeekProbeHistory")( + function* (commandPath: string, spawn: AcpSessionRuntime.AcpSpawnInput) { + const executable = (commandPath || spawn.command).split(/[\\/]/u).at(-1) ?? ""; + if (!/^dsh(?:\.cmd|\.exe)?$/iu.test(executable)) return spawn; + + const argumentSeparator = spawn.args.indexOf("--"); + const launcherArgs = + argumentSeparator === -1 ? spawn.args : spawn.args.slice(0, argumentSeparator); + const usesAcpProfile = + launcherArgs[0] === "acp" || + launcherArgs.includes("--profile=acp") || + launcherArgs.some((arg, index) => arg === "--profile" && launcherArgs[index + 1] === "acp"); + if (!usesAcpProfile) return spawn; + + // DeepSeek persists session/new before any prompt and does not advertise session/delete. + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dsh-acp-probe-" }); + const patchPath = path.join(directory, "probe.json"); + const patch = yield* encodeJson([ + { id: "session-persistence-jsonl", config: { root: path.join(directory, "sessions") } }, + { id: "session-projection-cache", disabled: true }, + ]); + yield* fs.writeFileString(patchPath, patch); + return { + ...spawn, + args: [...launcherArgs, "--patch", patchPath, ...spawn.args.slice(launcherArgs.length)], + }; + }, +); + export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeConfiguration")( function* ( input: AcpRegistryConfigurationProbeInput, @@ -396,6 +431,8 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo AcpRegistryOperationError, | AcpRegistrySupport.AcpRegistryCatalog | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path | SecureRandom.SecureRandom > { const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; @@ -413,6 +450,19 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo const resolved = yield* catalog .resolve(input.settings, input.cwd, input.environment) .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)); + const spawn = yield* isolateDeepSeekProbeHistory( + input.settings.commandPath, + resolved.spawn, + ).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "probe_failed", + message: "Could not prepare temporary history for the DeepSeek Harness probe.", + cause, + }), + ), + ); const authMethodsRef = yield* Ref.make>([]); const authActionRef = yield* Ref.make(undefined); const runtimeCoordinator = yield* Effect.serviceOption( @@ -420,7 +470,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ); const runtimeContext = yield* Layer.build( AcpSessionRuntime.layer({ - spawn: resolved.spawn, + spawn, cwd: input.cwd, clientCapabilities: { auth: { terminal: Option.isSome(pty) }, From 7e3ae9c9fb853ef6e71fdd222810db4e132bdb8c Mon Sep 17 00:00:00 2001 From: "fable-5.2" Date: Fri, 20 Nov 2026 09:27:54 -0600 Subject: [PATCH 6/6] fix(web,mobile): recovering a conversation no longer shows a handoff from a model to itself Co-Authored-By: stefan --- .../features/threads/thread-handoff-row.tsx | 3 +- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + .../src/components/chat/V2LifecycleRow.tsx | 12 ++++++- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + packages/client-runtime/src/handoff.test.ts | 15 +++++++++ packages/client-runtime/src/handoff.ts | 31 +++++++++++++++++-- 24 files changed, 77 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/features/threads/thread-handoff-row.tsx b/apps/mobile/src/features/threads/thread-handoff-row.tsx index 7158a9968bcc6..eef5d1cc504ab 100644 --- a/apps/mobile/src/features/threads/thread-handoff-row.tsx +++ b/apps/mobile/src/features/threads/thread-handoff-row.tsx @@ -2,6 +2,7 @@ import * as Dialog from "../../components/ui/Dialog"; import { useAtomValue } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { + isRecoveryHandoff, resolveHandoffEndpoints, resolveModelSwitchChange, type HandoffEndpoints, @@ -100,7 +101,7 @@ export function ThreadHandoffRow(props: { endpoints={endpoints} iconColor={color} surfaceColor={props.surfaceColor} - label={gt("Context handoff")} + label={isRecoveryHandoff(item) ? gt("Recovered context") : gt("Context handoff")} failed={item.status === "failed"} /> ); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1b7bd82051d2e..c6315ff4305ce 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4694,6 +4694,7 @@ "97ad838fc2717591": "Ausgabe wird geladen…", "b2de62817c6ab53d": "Keine Ausgabe.", "346e42415ac6d374": "Frühere Ausgabe nicht angezeigt", + "b5a8acfa085f459a": "Wiederhergestellter Kontext", "4d765811334b8edf": "Kontextübergabe", "0e7207133e1d9277": "Anbieterkonto anzeigen", "3747414e652cca55": "Thread maximieren", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 9e14fe9b7a221..e6371983ecc3c 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4695,6 +4695,7 @@ "97ad838fc2717591": "Loading output…", "b2de62817c6ab53d": "No output.", "346e42415ac6d374": "Earlier output not shown", + "b5a8acfa085f459a": "Recovered context", "4d765811334b8edf": "Context handoff", "0e7207133e1d9277": "Show provider account", "3747414e652cca55": "Maximize thread", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index e1a9c5cf1b5a3..b049dbffaf2ab 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4687,6 +4687,7 @@ "97ad838fc2717591": "Cargando la salida…", "b2de62817c6ab53d": "Sin salida.", "346e42415ac6d374": "No se muestra la salida anterior", + "b5a8acfa085f459a": "Contexto recuperado", "4d765811334b8edf": "Traspaso de contexto", "0e7207133e1d9277": "Mostrar cuenta del proveedor", "3747414e652cca55": "Maximizar hilo", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index ef1ee0912d582..efa301b65f734 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4688,6 +4688,7 @@ "97ad838fc2717591": "Chargement de la sortie…", "b2de62817c6ab53d": "Aucune sortie.", "346e42415ac6d374": "Sortie antérieure non affichée", + "b5a8acfa085f459a": "Contexte récupéré", "4d765811334b8edf": "Transfert de contexte", "0e7207133e1d9277": "Afficher le compte du fournisseur", "3747414e652cca55": "Agrandir le fil", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index dd7f638cfca7a..dfc2ac08a331c 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4669,6 +4669,7 @@ "97ad838fc2717591": "出力を読み込んでいます…", "b2de62817c6ab53d": "出力はありません。", "346e42415ac6d374": "以前の出力は表示されていません", + "b5a8acfa085f459a": "復元されたコンテキスト", "4d765811334b8edf": "コンテキストの引き継ぎ", "0e7207133e1d9277": "プロバイダーのアカウントを表示", "3747414e652cca55": "スレッドを最大化", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index cbc39fa7feabb..25d8a766cd123 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4674,6 +4674,7 @@ "97ad838fc2717591": "출력을 불러오는 중…", "b2de62817c6ab53d": "출력이 없습니다.", "346e42415ac6d374": "이전 출력은 표시되지 않음", + "b5a8acfa085f459a": "복구된 컨텍스트", "4d765811334b8edf": "컨텍스트 인계", "0e7207133e1d9277": "제공자 계정 표시", "3747414e652cca55": "스레드 최대화", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index fc2ebadd1255f..51b674a56203b 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4688,6 +4688,7 @@ "97ad838fc2717591": "Carregando a saída…", "b2de62817c6ab53d": "Sem saída.", "346e42415ac6d374": "Saída anterior não mostrada", + "b5a8acfa085f459a": "Contexto recuperado", "4d765811334b8edf": "Transferência de contexto", "0e7207133e1d9277": "Mostrar conta do provedor", "3747414e652cca55": "Maximizar thread", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index b3c35b2d78daa..cce3ac401bfa5 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4766,6 +4766,7 @@ "97ad838fc2717591": "Загрузка вывода…", "b2de62817c6ab53d": "Нет вывода.", "346e42415ac6d374": "Более ранний вывод не показан", + "b5a8acfa085f459a": "Контекст восстановлен", "4d765811334b8edf": "Передача контекста", "0e7207133e1d9277": "Показать аккаунт провайдера", "3747414e652cca55": "Развернуть тред", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 50bf58982de2c..fe2e02f0d4bb2 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4694,6 +4694,7 @@ "97ad838fc2717591": "Läser in utdata…", "b2de62817c6ab53d": "Inga utdata.", "346e42415ac6d374": "Tidigare utdata visas inte", + "b5a8acfa085f459a": "Återställd kontext", "4d765811334b8edf": "Kontextöverlämning", "0e7207133e1d9277": "Visa leverantörskonto", "3747414e652cca55": "Maximera tråden", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index ec960fce61b75..68c38ad89b3c2 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4677,6 +4677,7 @@ "97ad838fc2717591": "正在加载输出…", "b2de62817c6ab53d": "没有输出。", "346e42415ac6d374": "更早的输出未显示", + "b5a8acfa085f459a": "已恢复上下文", "4d765811334b8edf": "上下文交接", "0e7207133e1d9277": "显示提供方账户", "3747414e652cca55": "最大化会话", diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 940e741b9c486..6cddb48befee5 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -16,6 +16,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import * as DateTime from "effect/DateTime"; import { WorkLogRow } from "./WorkLog"; import { + isRecoveryHandoff, resolveHandoffEndpoints, type HandoffEndpoints, type HandoffTimelineRun, @@ -96,6 +97,7 @@ export function V2LifecycleRow(props: { ); @@ -624,6 +626,7 @@ function EnvironmentHandoffRow({ }: { readonly environmentId: EnvironmentId; readonly endpoints: HandoffEndpoints; + readonly recovery: boolean; readonly failed: boolean; }) { const providers = @@ -666,6 +669,7 @@ export function HandoffRow(props: { readonly endpoints: HandoffEndpoints; readonly providers: ReadonlyArray; readonly pending?: boolean; + readonly recovery?: boolean; readonly failed?: boolean; }) { const gt = useGT(); @@ -675,7 +679,13 @@ export function HandoffRow(props: { const entries = settings ? applyProviderInstanceSettings(derived, settings, null) : derived; return ( { resolveHandoffEndpoints(item, [run("target", 2, from, "wrong-model")]).to.model, ).toBeUndefined(); }); + + it("treats a provider conversation restarted in a fresh session of itself as a recovery", () => { + const sameModel = { fromModelSelections: [{ instanceId: to, model: "same" }], toModel: "same" }; + const recovery = { ...item, ...sameModel, fromProviderThreadIds: [item.toProviderThreadId] }; + expect(isRecoveryHandoff(recovery)).toBe(true); + expect(resolveHandoffEndpoints(recovery, []).from).toEqual([]); + // A fork or merge-back between two conversations on one model is still a handoff. + const fork = { ...item, ...sameModel }; + expect(isRecoveryHandoff(fork)).toBe(false); + expect(resolveHandoffEndpoints(fork, []).from).toEqual(sameModel.fromModelSelections); + }); }); const projection = { diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index 48a1227429312..ce8b5f1ff4efe 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -52,7 +52,13 @@ export function resolvePendingHandoff( export function resolveHandoffEndpoints( item: Pick< Extract, - "runId" | "fromModelSelections" | "fromProviderInstanceIds" | "toModel" | "toProviderInstanceId" + | "runId" + | "fromProviderThreadIds" + | "toProviderThreadId" + | "fromModelSelections" + | "fromProviderInstanceIds" + | "toModel" + | "toProviderInstanceId" >, runs: ReadonlyArray, ) { @@ -72,7 +78,28 @@ export function resolveHandoffEndpoints( instanceId, model: latestRunModelBefore(runs, instanceId, handoffRun?.ordinal), })); - return { from: fromEndpoints, to: { instanceId: item.toProviderInstanceId, model: toModel } }; + return { + from: isRecoveryHandoff(item) ? [] : fromEndpoints, + to: { instanceId: item.toProviderInstanceId, model: toModel }, + }; +} + +/** + * Whether every source of the handoff is its own target conversation, as when a provider + * conversation restarts in a fresh session of itself after a failed resume or a rollback it + * cannot truncate. Nothing changed hands, so it has no source. Matching on the model instead + * would also catch a fork or a merge-back between two conversations that happen to share one. + */ +export function isRecoveryHandoff( + item: Pick< + Extract, + "fromProviderThreadIds" | "toProviderThreadId" + >, +): boolean { + return ( + item.fromProviderThreadIds.length > 0 && + item.fromProviderThreadIds.every((id) => id === item.toProviderThreadId) + ); } function latestRunModelBefore(