From e1e520c93c997e07eebf135b12c89fad7fb35085 Mon Sep 17 00:00:00 2001 From: maria Date: Tue, 3 Nov 2026 02:17:20 +0000 Subject: [PATCH 01/37] fix(web): show the project pin before the remote badge (#29704) --- apps/web/src/components/Sidebar.tsx | 14 +++++++------- apps/web/src/components/chat/DraftHeroHeadline.tsx | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8eb32a605822a..cbf0191a7f40f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3138,13 +3138,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} {item.label} - {project && showProjectEnvironments ? ( - - ) : null} {project && canPinProject(project) ? ( toggleProjectGroupPin(project)} /> ) : null} + {project && showProjectEnvironments ? ( + + ) : null} {project ? ( `); + const failure = (selector: string) => + ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then( + () => expect.unreachable(), + ServerBrowserPage.toOperationError, + ); + + const absent = await failure(".definitely-no-such-t3-target"); + expect(absent.tag).toBe("PreviewAutomationTimeoutError"); + expect(absent.message).toBe( + 'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.', + ); + expect(absent.cause).toMatchObject({ name: "TimeoutError" }); + const hidden = await failure("button"); + expect(hidden.tag).toBe("PreviewAutomationTimeoutError"); + expect(hidden.message).toBe( + 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.', + ); + }); + it("does not retarget a removed ref to a replacement node", async () => { await page.setContent(""); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original"); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index d573cd6387c8b..f128bf445e603 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -33,8 +33,8 @@ export class ServerBrowserOperationError extends Error { readonly tag: string; readonly detail: unknown; - constructor(tag: string, message: string, detail?: unknown) { - super(message); + constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) { + super(message, options); this.tag = tag; this.detail = detail; } @@ -72,6 +72,8 @@ export const toOperationError = ( }; const DEFAULT_TIMEOUT_MS = 15_000; +const TARGET_COUNT_MS = 250; +const MAX_TARGET_CHARS = 200; const pageRefs = new WeakMap }>(); // A compact runtime namespace prevents old refs from aliasing after a server restart. @@ -634,6 +636,58 @@ export const click = async ( ): Promise<{ readonly x: number; readonly y: number }> => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); + try { + return await clickTarget(page, locator, input, timeout, pointer); + } catch (cause) { + throw locator === null ? cause : await namedTargetTimeout(locator, input, cause); + } +}; + +/** + * Playwright's timeout names neither the target nor why it waited. Counting only after the + * wait failed keeps auto-wait intact, but the count describes the page after the timeout, not + * what the click did: Playwright can dispatch the click and then time out waiting for the + * navigation it started. + */ +const namedTargetTimeout = async ( + locator: Locator, + input: { readonly locator?: string | undefined; readonly selector?: string | undefined }, + cause: unknown, +) => { + if (!(cause instanceof Error && cause.name === "TimeoutError")) return cause; + const selector = JSON.stringify(input.locator ?? input.selector); + // The warning leads and the target is capped, so a reply cut short still carries the warning. + const target = + selector.length > MAX_TARGET_CHARS ? `${selector.slice(0, MAX_TARGET_CHARS)}...` : selector; + // The host's reply must still beat the broker's short grace after the operation timeout. + let timer: ReturnType | undefined; + const matches = await Promise.race([ + locator.count().catch(() => undefined), + new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), TARGET_COUNT_MS); + }), + ]).finally(() => clearTimeout(timer)); + const reason = + matches === undefined + ? `The click may have happened; check the page before retrying. Whether ${target} still matches an element is unknown.` + : matches === 0 + ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` + : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; + return new ServerBrowserOperationError( + "PreviewAutomationTimeoutError", + reason, + { reason }, + { cause }, + ); +}; + +const clickTarget = async ( + page: Page, + locator: Locator | null, + input: PreviewAutomationClickInput, + timeout: number, + pointer: PointerReporter, +) => { const point = await targetPoint(page, locator, input, timeout); await pointer(point, "click"); const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const; diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts index 2ba62cd9ae280..bfeb5cf916672 100644 --- a/packages/contracts/src/previewAutomation.ts +++ b/packages/contracts/src/previewAutomation.ts @@ -766,11 +766,12 @@ export class PreviewAutomationTimeoutError extends Schema.TaggedError Date: Mon, 2 Nov 2026 18:52:31 -0800 Subject: [PATCH 31/37] fix(cursor): supporting files no longer hide sibling skills (#23326) Co-authored-by: Claude Fable 5.1 --- .../provider-cursor/src/server/skills.test.ts | 80 +++++++++++++++++++ packages/provider-cursor/src/server/skills.ts | 24 +++++- 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/packages/provider-cursor/src/server/skills.test.ts b/packages/provider-cursor/src/server/skills.test.ts index 8d1359b1f577e..0bbd1bfeb51ea 100644 --- a/packages/provider-cursor/src/server/skills.test.ts +++ b/packages/provider-cursor/src/server/skills.test.ts @@ -3,7 +3,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "vite-plus/test"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import type * as Scope from "effect/Scope"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; @@ -173,6 +175,84 @@ describe("Cursor skills", () => { }), )); + it("finds sibling skills when one skill ships more files than the scan budget", async () => + await runNode( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDirectory = (prefix: string) => + fileSystem + .makeTempDirectoryScoped({ directory: NodeOS.tmpdir(), prefix }) + .pipe(Effect.flatMap((directory) => fileSystem.realPath(directory))); + const userHome = yield* tempDirectory("cursor-skills-home-"); + const workspace = yield* tempDirectory("cursor-skills-workspace-"); + const root = path.join(workspace, ".cursor", "skills"); + const artifacts = path.join(root, "a-large", "artifacts"); + yield* fileSystem.makeDirectory(artifacts, { recursive: true }); + yield* fileSystem.writeFileString(path.join(root, "a-large", "SKILL.md"), "---\n---\n"); + yield* fileSystem.makeDirectory(path.join(root, "b-small"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(root, "b-small", "SKILL.md"), "---\n---\n"); + // More ordinary files than the whole-scan entry budget of 10,000. + yield* Effect.forEach( + Array.from({ length: 11_000 }, (_, index) => path.join(artifacts, `file-${index}.txt`)), + (file) => fileSystem.writeFileString(file, ""), + { concurrency: 64, discard: true }, + ); + + const expected = [ + { + name: "a-large", + path: path.join(root, "a-large", "SKILL.md"), + scope: "project", + enabled: true, + }, + { + name: "b-small", + path: path.join(root, "b-small", "SKILL.md"), + scope: "project", + enabled: true, + }, + ]; + expect(yield* discoverCursorSkills(workspace, { HOME: userHome })).toEqual(expected); + expect(yield* probeCursorSkills(workspace, { HOME: userHome })).toEqual(expected); + }), + )); + + it("stops a scan of a huge file tree instead of statting every file", async () => { + const root = "/workspace/.cursor/skills"; + let stats = 0; + const fileSystem = FileSystem.layerNoop({ + realPath: (path) => Effect.succeed(path), + readDirectory: (path) => + path === root + ? Effect.succeed(Array.from({ length: 200_000 }, (_, index) => `file-${index}`)) + : Effect.succeed([]), + stat: (path) => { + stats += 1; + if (path === root) return Effect.succeed({ type: "Directory" } as FileSystem.File.Info); + if (path.startsWith(`${root}/file-`)) { + return Effect.succeed({ type: "File" } as FileSystem.File.Info); + } + return Effect.fail( + PlatformError.systemError({ _tag: "NotFound", module: "FileSystem", method: "stat" }), + ); + }, + }); + + const result = await probeCursorSkills("/workspace", { HOME: "/home" }).pipe( + Effect.result, + Effect.provide(Layer.mergeAll(fileSystem, Path.layer)), + Effect.runPromise, + ); + + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: "scan-budget-exhausted" }, + }); + expect(stats).toBeGreaterThanOrEqual(100_000); + expect(stats).toBeLessThanOrEqual(100_000); + }); + it.skipIf(!symlinksSupported)( "treats a symlinked skill outside the root as a package boundary", async () => diff --git a/packages/provider-cursor/src/server/skills.ts b/packages/provider-cursor/src/server/skills.ts index bc89ee6e35fa3..5ef6888876036 100644 --- a/packages/provider-cursor/src/server/skills.ts +++ b/packages/provider-cursor/src/server/skills.ts @@ -17,6 +17,7 @@ const HAS_SKILL_MENTION_PATTERN = new RegExp(SKILL_MENTION_PATTERN.source, "u"); const MAX_SKILL_DEPTH = 10; const MAX_SKILL_BYTES = ByteSize.bytes(1_000_000); const MAX_SKILL_SCAN_ENTRIES = 10_000; +const MAX_SKILL_SCAN_STATS = 100_000; const MAX_SKILL_SCAN_BYTES = ByteSize.bytes(8_000_000); interface CursorSkillFrontmatter { @@ -29,6 +30,7 @@ interface CursorSkillFrontmatter { interface CursorSkillScanBudget { remainingEntries: number; + remainingStats: number; remainingBytes: bigint; exhausted: boolean; incomplete: boolean; @@ -153,6 +155,11 @@ const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* ( resolvedDirectory === rootDirectory || resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`); + if (input.budget.remainingStats === 0) { + input.budget.exhausted = true; + return; + } + input.budget.remainingStats -= 1; const skillPath = path.join(directory, "SKILL.md"); const skillInfo = yield* orUndefined(fileSystem.stat(skillPath), input.budget); if (skillInfo?.type === "File") { @@ -189,17 +196,25 @@ const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* ( return; } for (const entry of [...entries].sort()) { - if (input.budget.remainingEntries === 0) { + // Installed dependencies can exhaust the shared budget and hide unrelated skills. + if (entry === "node_modules") continue; + // Files spend no directory budget, so a separate cap keeps a huge file tree bounded. + if (input.budget.remainingStats === 0) { input.budget.exhausted = true; return; } - input.budget.remainingEntries -= 1; - // Installed dependencies can exhaust the shared budget and hide unrelated skills. - if (entry === "node_modules") continue; + input.budget.remainingStats -= 1; const child = path.join(directory, entry); const info = yield* orUndefined(fileSystem.stat(child), input.budget); + // Only directories can hold skills, so only they spend the budget: a skill + // shipping many ordinary files must not hide its siblings. if (info?.type !== "Directory") continue; if (depth >= MAX_SKILL_DEPTH) continue; + if (input.budget.remainingEntries === 0) { + input.budget.exhausted = true; + return; + } + input.budget.remainingEntries -= 1; yield* visit(child, depth + 1); } }); @@ -233,6 +248,7 @@ const inspectCursorSkills = Effect.fn("inspectCursorSkills")(function* ( const skillsByName = new Map(); const budget: CursorSkillScanBudget = { remainingEntries: MAX_SKILL_SCAN_ENTRIES, + remainingStats: MAX_SKILL_SCAN_STATS, remainingBytes: MAX_SKILL_SCAN_BYTES, exhausted: false, incomplete: false, From 689bdb82e95e6ebc2c23ae5222422a1941cdcf9f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 18:52:37 -0800 Subject: [PATCH 32/37] fix(web): usage-limit retry notice shows the timezone (#23029) Co-authored-by: Claude Opus 5.5 --- .../src/features/threads/thread-work-log.tsx | 5 +- .../chat/MessagesTimeline.browser.test.tsx | 72 +++++++++++++- .../components/chat/TimelineWorkEntryRow.tsx | 7 +- apps/web/src/timestampFormat.test.ts | 21 +++++ apps/web/src/timestampFormat.ts | 93 ++++++++++++------- 5 files changed, 163 insertions(+), 35 deletions(-) create mode 100644 apps/web/src/timestampFormat.test.ts diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index f83382d7531e3..0ff0271f44fb2 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -937,13 +937,14 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( const warning = failureItem.failure.class === "usage_limit"; const timestamp = new Date(row.createdAt); const resetAt = failureItem.failure.resetAt; + // The reset time is the viewer's local time; naming the zone keeps it unambiguous. const resetTime = resetAt - ? new Date(resetAt).toLocaleString(undefined, { + ? `${new Date(resetAt).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", - }) + })} (${new Intl.DateTimeFormat().resolvedOptions().timeZone})` : null; const label = warning ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}` diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 9b156deaed8a2..6b1df4ca16927 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1,6 +1,6 @@ import { flushSync } from "react-dom"; import { AudioPreview } from "../files/AudioPreview"; -import { page } from "vite-plus/test/browser"; +import { cdp, page } from "vite-plus/test/browser"; import { ComposerContextId, EnvironmentId, @@ -565,6 +565,76 @@ describe("MessagesTimeline messages", () => { }); }); +function usageLimitEntries(resetAt: string) { + const threadId = ThreadId.make("usage-limit-thread"); + const at = DateTime.makeUnsafe(CREATED_AT); + return deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: TurnItemId.make("usage-limit"), + item: { + id: TurnItemId.make("usage-limit"), + threadId, + runId: RunId.make("usage-limit-run"), + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + title: null, + startedAt: at, + completedAt: at, + updatedAt: at, + type: "error", + status: "failed", + failure: { + class: "usage_limit", + message: "You've hit your usage limit.", + code: null, + retryable: true, + resetAt, + }, + }, + }, + ], + optimisticMessages: [], + }); +} + +describe("MessagesTimeline usage limit notice", () => { + it("labels the retry time with the viewer's timezone", async () => { + await using screen = await renderTimeline(usageLimitEntries("2026-03-17T19:30:00.000Z")); + const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; + expect(screen.text()).toMatch(/Usage limit reached\. Retry after .+\./); + expect(screen.text()).toContain(`(${timeZone})`); + }); + + it("keeps the retry time in the named zone after the viewer's timezone changes", async () => { + const resetAt = "2026-07-01T19:30:00.000Z"; + const session = cdp(); + await session.send("Emulation.setTimezoneOverride", { timezoneId: "Europe/Madrid" }); + try { + { + await using _madrid = await renderTimeline(usageLimitEntries(resetAt)); + } + await session.send("Emulation.setTimezoneOverride", { timezoneId: "America/New_York" }); + await using screen = await renderTimeline(usageLimitEntries(resetAt)); + const newYorkTime = new Date(resetAt).toLocaleTimeString(undefined, { + hour: "numeric", + minute: "2-digit", + timeZone: "America/New_York", + }); + expect(screen.text()).toContain(`${newYorkTime} (America/New_York)`); + } finally { + await session.send("Emulation.setTimezoneOverride", { timezoneId: "" }); + } + }); +}); + const CITATION_REQUEST = { key: "activation-1", citation: { diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 76f2f604ba85f..95661d16b9307 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -209,7 +209,12 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { if (failureItem?.type === "error" && failureItem.status === "failed") { const warning = failureItem.failure.class === "usage_limit"; const resetAt = failureItem.failure.resetAt; - const resetTime = resetAt ? formatUpcomingTimestamp(resetAt, timestampFormat) : null; + // The reset time is the viewer's local time; naming the zone keeps it + // unambiguous. Both read the zone now, since the device's can change. + const timeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; + const resetTime = resetAt + ? `${formatUpcomingTimestamp(resetAt, timestampFormat, undefined, timeZone)} (${timeZone})` + : null; const label = warning ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}` : workEntry.label; diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts new file mode 100644 index 0000000000000..5b5e11d812027 --- /dev/null +++ b/apps/web/src/timestampFormat.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { formatDayAwareTimestamp, formatUpcomingTimestamp } from "./timestampFormat"; + +describe("timestamps in an explicit time zone", () => { + // 23:00 UTC on July 1 is 7 PM on July 1 in New York, whatever the host zone. + const now = Date.parse("2026-07-01T23:00:00.000Z"); + const zone = "America/New_York"; + + it("picks relative days from the calendar in that zone", () => { + expect(formatUpcomingTimestamp("2026-07-02T00:30:00.000Z", "12-hour", now, zone)).not.toMatch( + /tomorrow/, + ); + expect(formatUpcomingTimestamp("2026-07-02T05:30:00.000Z", "12-hour", now, zone)).toMatch( + /^tomorrow at /, + ); + expect(formatDayAwareTimestamp("2026-07-01T03:30:00.000Z", "12-hour", now, zone)).toMatch( + /^yesterday at /, + ); + }); +}); diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index b1a8121677a5e..abad91401ccbe 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -73,17 +73,18 @@ const timestampFormatterCache = new Map(); function getTimestampFormatter( timestampFormat: TimestampFormat, includeSeconds: boolean, + timeZone?: string, ): Intl.DateTimeFormat { - const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`; + const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone ?? ""}`; const cachedFormatter = timestampFormatterCache.get(cacheKey); if (cachedFormatter) { return cachedFormatter; } - const formatter = new Intl.DateTimeFormat( - timestampLocale, - getTimestampFormatOptions(timestampFormat, includeSeconds), - ); + const formatter = new Intl.DateTimeFormat(timestampLocale, { + ...getTimestampFormatOptions(timestampFormat, includeSeconds), + ...(timeZone ? { timeZone } : {}), + }); timestampFormatterCache.set(cacheKey, formatter); return formatter; } @@ -136,58 +137,88 @@ export function formatShortTimestamp(isoDate: string, timestampFormat: Timestamp return getTimestampFormatter(timestampFormat, false).format(date); } -const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, { - month: "numeric", - day: "numeric", -}); -const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, { - month: "numeric", - day: "numeric", +const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" }; +const numericDateWithYearOptions: Intl.DateTimeFormatOptions = { + ...numericDateOptions, year: "numeric", -}); +}; +const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, numericDateOptions); +const numericDateWithYearFormatter = new Intl.DateTimeFormat( + timestampLocale, + numericDateWithYearOptions, +); + +interface CalendarDay { + year: number; + /** Days since the epoch, so differences are whole days across DST shifts. */ + index: number; +} + +function calendarDay(date: Date, timeZone: string | undefined): CalendarDay { + if (!timeZone) { + const year = date.getFullYear(); + return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 }; + } + const parts = new Intl.DateTimeFormat("en-US", { + timeZone, + year: "numeric", + month: "numeric", + day: "numeric", + }).formatToParts(date); + const part = (type: Intl.DateTimeFormatPartTypes) => + Number(parts.find((entry) => entry.type === type)?.value); + const year = part("year"); + return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 }; +} + +function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string { + if (!timeZone) { + return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format(date); + } + return new Intl.DateTimeFormat(timestampLocale, { + ...(sameYear ? numericDateOptions : numericDateWithYearOptions), + timeZone, + }).format(date); +} export function formatDayAwareTimestamp( isoDate: string, timestampFormat: TimestampFormat, nowMs: number = Date.now(), + timeZone?: string, ): string { const date = parseTimestampDate(isoDate); if (!date) return ""; - const time = getTimestampFormatter(timestampFormat, false).format(date); + const time = getTimestampFormatter(timestampFormat, false, timeZone).format(date); - const now = new Date(nowMs); - const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); - // Round so DST-shifted 23/25 hour days still count as whole days. - const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000); + const today = calendarDay(new Date(nowMs), timeZone); + const messageDay = calendarDay(date, timeZone); + const dayDiff = today.index - messageDay.index; if (dayDiff <= 0) return time; if (dayDiff === 1) return `yesterday at ${time}`; - const dateFormatter = - date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter; - return `${dateFormatter.format(date)} ${time}`; + return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`; } +/** `timeZone` overrides the zone the formatters cached when they were built. */ export function formatUpcomingTimestamp( isoDate: string, timestampFormat: TimestampFormat, nowMs: number = Date.now(), + timeZone?: string, ): string { const date = parseTimestampDate(isoDate); if (!date) return ""; - const time = getTimestampFormatter(timestampFormat, false).format(date); + const time = getTimestampFormatter(timestampFormat, false, timeZone).format(date); - const now = new Date(nowMs); - const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); - const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000); + const today = calendarDay(new Date(nowMs), timeZone); + const targetDay = calendarDay(date, timeZone); + const dayDiff = targetDay.index - today.index; - if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs); + if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone); if (dayDiff === 0) return time; if (dayDiff === 1) return `tomorrow at ${time}`; - const dateFormatter = - date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter; - return `${dateFormatter.format(date)} ${time}`; + return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`; } type RelativeTimeParts = { value: string; suffix: string | null }; From bb221f0e1f50001e296fa3269bb75e2ea88e573a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 18:59:04 -0800 Subject: [PATCH 33/37] fix(server): preserve nested Claude subagent completion across turns (#23561) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 192 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 30 ++- 2 files changed, 218 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 796e3655de7fb..daff636c77eee 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -12733,6 +12733,198 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("keeps an idle-launched nested subagent completed through a sibling's wake", () => + Effect.scoped( + Effect.gen(function* () { + const OUTER_TASK_ID = "task-16355-outer"; + const OUTER_TOOL_USE_ID = "toolu-16355-outer"; + const NESTED_TASK_ID = "task-16355-nested"; + const NESTED_TOOL_USE_ID = "toolu-16355-nested"; + const SIBLING_TASK_ID = "task-16355-sibling"; + const SIBLING_TOOL_USE_ID = "toolu-16355-sibling"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const nestedStatuses = () => + harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID + ? [event.subagent.status] + : [], + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-1"), + text: "Run two audits in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016301", + }), + makeSubagentTaskStartedFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016302", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016303", + result: "Both audits run in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + // The background subagent launches a foreground nested one while the root is idle. + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_16355_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Sleep, then reply NESTED_OK" }, + }, + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016304", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Sleep, then reply NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016305", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: NESTED_TASK_ID, + description: "Sleeping", + uuid: "00000000-0000-4000-8000-000000016306", + session_id: WAKE_NATIVE_SESSION, + }), + ]) { + yield* harness.offerAndWait(frame); + } + + // A user turn runs while the nested and then the outer subagent finish. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-2"), + text: "Sleep for a while.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016307", + }), + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016308", + toolUseId: NESTED_TOOL_USE_ID, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016309", + text: "OUTER_DONE", + }), + makeSubagentNotificationFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + summary: "OUTER_DONE", + uuid: "00000000-0000-4000-8000-000000016310", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016311", + result: "Slept.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(2); + + // The sibling's completion wakes a continuation while the root is idle. + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + summary: "SIBLING_DONE", + uuid: "00000000-0000-4000-8000-000000016312", + }), + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000016313", + text: "Both audits finished.", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016314", + result: "Both audits finished.", + origin: { kind: "task-notification" }, + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + + assert.equal(nestedStatuses().at(-1), "completed"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect.each(["exit", "Stop"] as const)( "settles a plain background subagent and its open call on %s after the root turn completes", (reason) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 3f4f418657485..1abac1cf5de98 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -9201,10 +9201,32 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } if (message.type === "system" && message.subtype === "task_notification") { - if ( - !appliedSubagentOutcomes.has(message) && - (yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id) - ) { + const isRegistered = (yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id); + // A task whose start is still held for the next wake drain has no + // node to finish yet; hold its outcome behind that start, or the + // drain replays the start alone and the task stays running. + if (!isRegistered) { + yield* Ref.update(wakeBuffers, (current) => { + const entry = current.get(liveQuery.nativeThreadId); + if ( + entry === undefined || + entry.messages.includes(message) || + !entry.messages.some( + (buffered) => + buffered.type === "system" && + buffered.subtype === "task_started" && + buffered.task_id === message.task_id, + ) + ) { + return current; + } + return new Map(current).set(liveQuery.nativeThreadId, { + ...entry, + messages: [...entry.messages, message], + }); + }); + } + if (!appliedSubagentOutcomes.has(message) && isRegistered) { yield* discardBufferedSubagentStarts( liveQuery.nativeThreadId, message.task_id, From c3e1e0a4e9c38af7383b3b85406daab31e695fa7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 19:00:00 -0800 Subject: [PATCH 34/37] fix(opencode): publish ordered pending-work snapshots (#21460) Co-authored-by: Exotic209093 <134711311+Exotic209093@users.noreply.github.com> Co-authored-by: Issue triage verification Co-authored-by: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 299 +++++++++++++++--- ...OpenCode2PendingSnapshots.evidence.test.ts | 159 ++++++++++ .../src/server/ProviderAdapter.ts | 2 + .../src/server/v2/adapter.ts | 89 ++++-- 4 files changed, 473 insertions(+), 76 deletions(-) create mode 100644 apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index f39f2dcf98ebe..0ee94d494394a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -72,11 +72,18 @@ const event = ( type: string, data: Record, label?: string, + version = 1, ): ProviderReplayEntry => ({ type: "emit_inbound", frame: { type: "sdk.event", - event: { id: `evt_${type.replaceAll(".", "")}0000`, created: 1, type, data, ...durable }, + event: { + id: `evt_${type.replaceAll(".", "")}0000`, + created: 1, + type, + data, + durable: { ...durable.durable, version }, + }, }, ...(label === undefined ? {} : { label }), }); @@ -943,47 +950,85 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); - it.effect("keeps a finished background subagent's queued report as pending work", () => - Effect.gen(function* () { - const { runtime, thread } = yield* resumed([ - ...backgroundLaunch(CHILD), - event("session.execution.succeeded", { sessionID: SESSION }), - event("session.execution.succeeded", { sessionID: CHILD }), - event("session.inbox.enqueued", { - inboxID: "msg_report", - sessionID: SESSION, - item: { - type: "synthetic", - payload: { - text: `\nCHILD_OK\n`, - description: "Sleep", - metadata: { - source: "subagent", - childID: CHILD, - agent: "General", - state: "completed", - }, - }, - delivery: "steer", - }, - }), - event("session.usage.updated", { sessionID: SESSION }), - ]); - const reported = yield* Deferred.make(); - yield* runtime.events.pipe( - Stream.tap((event) => - event.type === "subagent.updated" && event.subagent.status === "completed" - ? Deferred.succeed(reported, undefined) - : Effect.void, - ), - Stream.runDrain, - Effect.forkScoped, - ); - yield* runtime.startTurn(withLineage(thread)); - yield* Deferred.await(reported); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); - }).pipe(Effect.scoped), + it.effect( + "keeps a finished background subagent's queued report pending until its native continuation ends", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["continue"]); + const { runtime, thread } = yield* resumed( + [ + ...nestedLaunch, + event("session.execution.succeeded", { sessionID: DEEP }), + deepReport("completed"), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" }, + }), + event("session.execution.started", { sessionID: MIDDLE }, "continue"), + event("session.inbox.delivered", { sessionID: MIDDLE, inboxID: "msg_deep_report" }), + event("session.text.ended", { + sessionID: MIDDLE, + assistantMessageID: "msg_native_continuation", + ordinal: 0, + text: "GRANDCHILD_OK", + }), + event("session.execution.succeeded", { sessionID: MIDDLE }), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }), + ], + { replayGate: gate }, + ); + const queued = yield* Deferred.make(); + const drained = yield* Deferred.make(); + const timeline: Array = []; + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.gen(function* () { + if (event.type === "provider_thread.updated") { + if ( + event.providerThread.nativeThreadRef?.nativeId === MIDDLE && + event.pendingBackgroundWork !== undefined + ) { + timeline.push(event.pendingBackgroundWork); + } + if (event.providerThread.id === thread.id) { + const variant = + event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value; + if (variant === "thinking") yield* Deferred.succeed(queued, undefined); + if (variant === "none") yield* Deferred.succeed(drained, undefined); + } + } + if ( + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === `${MIDDLE}:turn:2` + ) { + timeline.push(event.providerTurn.status); + } + if (event.type === "message.updated" && event.message.text === "GRANDCHILD_OK") { + timeline.push(event.message.text); + } + }), + ), + Effect.forkScoped, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(queued); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + assert.strictEqual(timeline.at(-1), true); + timeline.length = 0; + gate.release("continue"); + yield* Deferred.await(drained); + assert.deepEqual( + timeline.filter((entry) => typeof entry === "string"), + ["running", "GRANDCHILD_OK", "completed"], + ); + assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed")); + assert.strictEqual(timeline.at(-1), false); + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + }).pipe(Effect.scoped), ); const returnedRunning = (id: string): ProviderReplayEntry => ({ @@ -1283,6 +1328,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { Effect.gen(function* () { const deep: Array = []; const middleTurns = new Map(); + const pendingSnapshots = new Map(); + const variants = new Map(); + let rootVariant: unknown; const terminals: Array = []; const changed = yield* Deferred.make(); let wake = changed; @@ -1290,6 +1338,16 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { Stream.tap((event) => Effect.gen(function* () { if (event.type === "turn.terminal") terminals.push(event.status); + if (event.type === "provider_thread.updated") { + const nativeId = event.providerThread.nativeThreadRef?.nativeId; + if (nativeId != null && event.pendingBackgroundWork !== undefined) { + pendingSnapshots.set(nativeId, event.pendingBackgroundWork); + } + const variant = + event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value; + if (nativeId != null) variants.set(nativeId, variant); + if (nativeId === SESSION) rootVariant = variant; + } if (event.type === "subagent.updated" && event.subagent.title === "Deep") { deep.push(event.subagent.status); } @@ -1314,9 +1372,164 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { deep, middleTurns, terminals, until }; + return { + deep, + middleTurns, + terminals, + pendingSnapshots, + variants, + get rootVariant() { + return rootVariant; + }, + until, + }; }); + it.effect("clears a nested report cancelled during a held wake", () => + Effect.gen(function* () { + const offers: Array = []; + const gate = makeProviderReplayGate(["drained"]); + const { runtime, thread } = yield* resumed( + [ + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report", "CHILD_OK"), + event("session.execution.started", { sessionID: SESSION }), + ...nestedLaunch.slice(3, -2), + event( + "session.tool.success", + { + ...toolOf(SESSION, "call-middle"), + content: [{ type: "text", text: "MIDDLE_OK" }], + metadata: { sessionID: MIDDLE, status: "completed", truncated: false }, + executed: false, + }, + undefined, + 2, + ), + event("session.execution.succeeded", { sessionID: DEEP }), + deepReport("completed"), + event("session.inbox.cancelled", { sessionID: MIDDLE, inboxID: "msg_deep_report" }), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" }, + }), + event( + "session.model.selected", + { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }, + "drained", + ), + ], + { replayGate: gate }, + ).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => { + offers.push(request); + }), + take: Effect.never, + }), + ); + const watch = yield* watchNested(runtime); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained"))); + yield* watch.until(() => watch.rootVariant === "thinking"); + assert.lengthOf(offers, 1); + yield* runtime.startTurn(continuationTurn(thread, offers[0]!)); + gate.release("drained"); + yield* watch.until(() => watch.rootVariant === "none"); + assert.isFalse(yield* runtime.hasPendingBackgroundWork!); + assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false); + }).pipe(Effect.scoped), + ); + + it.effect("clears the caller's pending work when a called session's held wake runs", () => + Effect.gen(function* () { + const OTHER = "ses_other00000000000000000000"; + const offers: Array = []; + const gate = makeProviderReplayGate(["drained"]); + const { runtime, thread } = yield* resumed( + [ + out("session.get", { sessionID: OTHER }), + replyData("session.get", sessionInfo({ id: OTHER })), + out("permission.list", { sessionID: OTHER }), + replyData("permission.list", []), + out("session.form.list", { sessionID: OTHER }), + replyData("session.form.list", []), + event("session.execution.started", { sessionID: OTHER }), + event("session.execution.succeeded", { sessionID: OTHER }), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + event("session.tool.input.started", { + ...toolOf(SESSION, "call-other"), + name: "subagent", + }), + event("session.tool.called", { + ...toolOf(SESSION, "call-other"), + name: "subagent", + input: { description: "Other", prompt: "again" }, + executed: false, + }), + event("session.tool.progress", { + ...toolOf(SESSION, "call-other"), + metadata: { sessionID: OTHER, status: "running" }, + }), + event("session.tool.success", { + ...toolOf(SESSION, "call-other"), + content: [{ type: "text", text: "OTHER_OK" }], + metadata: { sessionID: OTHER, status: "completed", truncated: false }, + executed: false, + }), + event("session.execution.succeeded", { sessionID: SESSION }), + event( + "session.model.selected", + { + sessionID: OTHER, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }, + "drained", + ), + ], + { replayGate: gate }, + ).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => { + offers.push(request); + }), + take: Effect.never, + }), + ); + const other = yield* runtime.resumeThread({ + providerThread: { + ...thread, + id: ProviderThreadId.make("provider-thread:opencode2-adapter:other"), + nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: OTHER, strength: "strong" }, + }, + threadId, + modelSelection: bigPickle, + runtimePolicy: policy(), + }); + const watch = yield* watchNested(runtime); + yield* watch.until(() => offers.length === 1); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained"))); + // The called session's held wake is its caller's pending work too. + yield* watch.until(() => watch.pendingSnapshots.get(SESSION) === true); + yield* runtime.startTurn(continuationTurn(other, offers[0]!)); + gate.release("drained"); + yield* watch.until(() => watch.variants.get(OTHER) === "none"); + assert.isFalse(watch.pendingSnapshots.get(OTHER)); + assert.isFalse(watch.pendingSnapshots.get(SESSION)); + }).pipe(Effect.scoped), + ); + it.effect("stops a foreground subagent's background subagent after the turn ended", () => Effect.gen(function* () { const offered = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts b/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts new file mode 100644 index 0000000000000..c22913a23f5a6 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts @@ -0,0 +1,159 @@ +import { assert, describe, it } from "@effect/vitest"; +import type { ProviderInstanceId } from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { OpenCode2OrchestratorReplayHarness } from "../Adapters/OpenCode2AdapterV2.testkit.ts"; +import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; +import { findReplayFixture, runReplayFixture } from "./ProviderReplayFixtures.ts"; + +// Evidence driver: replays recorded OpenCode 2 fixtures through +// OrchestratorV2 and records the adapter's own event stream, because the +// `pendingBackgroundWork` flag is dropped before it reaches domain events. +// Set EV_TRANSCRIPT to a file path to append the transcript there. + +type Row = { + readonly id: string; + readonly fixture: string; + /** True when every native thread must end on a `pendingBackgroundWork: false` snapshot. */ + readonly requireSettledSnapshots: boolean; +}; + +const ROWS: ReadonlyArray = [ + { id: "R1", fixture: "opencode2_nested_background", requireSettledSnapshots: true }, + { id: "R1-compat", fixture: "opencode2_background", requireSettledSnapshots: true }, + { id: "R2c-compat", fixture: "opencode2_resume_after_restart", requireSettledSnapshots: false }, + { id: "R2c-compat", fixture: "opencode2_interrupt", requireSettledSnapshots: false }, + { id: "R3", fixture: "opencode2_simple", requireSettledSnapshots: false }, + { id: "R3", fixture: "opencode2_tool_call", requireSettledSnapshots: false }, +]; + +const tasksOf = (tasks: ReadonlyArray<{ readonly taskId: string }> | undefined) => + `[${(tasks ?? []).map((task) => task.taskId).join(",")}]`; + +const describeEvent = (event: ProviderAdapter.ProviderAdapterV2Event): string | undefined => { + switch (event.type) { + case "provider_thread.updated": + return `provider_thread.updated native=${event.providerThread.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundWork=${String(event.pendingBackgroundWork)} pendingBackgroundTasks=${tasksOf(event.providerThread.pendingBackgroundTasks)}`; + case "provider_turn.updated": + return `provider_turn.updated native=${event.providerTurn.nativeTurnRef?.nativeId ?? "?"} status=${event.providerTurn.status}`; + case "subagent.updated": + return `subagent.updated title=${event.subagent.title ?? "?"} status=${event.subagent.status}`; + case "turn.terminal": + return `turn.terminal status=${event.status}`; + default: + return undefined; + } +}; + +const tappedHarness = ( + record: (event: ProviderAdapter.ProviderAdapterV2Event) => void, +): typeof OpenCode2OrchestratorReplayHarness => ({ + ...OpenCode2OrchestratorReplayHarness, + makeProviderAdapterRegistryLayer: ( + ...args: Parameters + ) => + Layer.effect( + ProviderAdapterRegistry.ProviderAdapterRegistryV2, + Effect.gen(function* () { + const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + return ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({ + ...registry, + get: (instanceId: ProviderInstanceId) => + registry.get(instanceId).pipe( + Effect.map((adapter) => + ProviderAdapter.ProviderAdapterV2.of({ + ...adapter, + openSession: (input) => + adapter.openSession(input).pipe( + Effect.map((runtime) => ({ + ...runtime, + events: runtime.events.pipe( + Stream.tap((event) => Effect.sync(() => record(event))), + ), + })), + ), + }), + ), + ), + }); + }), + ).pipe( + Layer.provide(OpenCode2OrchestratorReplayHarness.makeProviderAdapterRegistryLayer(...args)), + ), +}); + +const runRow = (row: Row) => + Effect.gen(function* () { + const fixture = findReplayFixture(row.fixture); + const driver = fixture?.providers.find((provider) => provider.driver === "opencode"); + assert.isDefined(fixture); + assert.isDefined(driver); + const events: Array = []; + const lines: Array = []; + const emit = (line: string) => lines.push(line); + emit(`== ${row.id} ${row.fixture} (recorded fixture) ==`); + const exit = yield* runReplayFixture({ + fixtureName: row.fixture, + buildInput: fixture.buildInput, + driver, + harness: tappedHarness((event) => events.push(event)), + }).pipe(Effect.exit); + let index = 0; + for (const event of events) { + const line = describeEvent(event); + if (line !== undefined) emit(` adapter[${index}] ${line}`); + index += 1; + } + const lastSnapshot = new Map(); + let everPending = false; + for (const event of events) { + if (event.type !== "provider_thread.updated") continue; + const nativeId = event.providerThread.nativeThreadRef?.nativeId ?? "?"; + lastSnapshot.set(nativeId, event.pendingBackgroundWork); + if (event.pendingBackgroundWork === true) everPending = true; + } + const finals = [...lastSnapshot].map(([id, flag]) => `${id}=${String(flag)}`).join(" "); + emit(` final snapshot per native thread: ${finals}`); + if (exit._tag === "Success") { + for (const domain of exit.value.domainEvents) { + if (domain.type !== "provider-thread.updated") continue; + emit( + ` domain provider-thread.updated native=${domain.payload.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundTasks=${tasksOf(domain.payload.pendingBackgroundTasks)}`, + ); + } + } + const failures: Array = []; + if (exit._tag === "Failure") failures.push("fixture output assertions failed"); + if (row.requireSettledSnapshots) { + if (!everPending) failures.push("no pendingBackgroundWork=true snapshot was published"); + for (const [id, flag] of lastSnapshot) { + if (flag !== false) failures.push(`${id} ended on pendingBackgroundWork=${String(flag)}`); + } + } else if ([...lastSnapshot.values()].includes(true)) { + failures.push("a native thread ended with pending work"); + } + emit( + ` ${row.id} ${row.fixture}: ${failures.length === 0 ? "PASS" : `FAIL (${failures.join("; ")})`}`, + ); + const transcript = yield* Config.String("EV_TRANSCRIPT").pipe(Config.withDefault("")); + if (transcript !== "") { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(transcript, `${lines.join("\n")}\n`, { flag: "a" }); + } + return failures; + }).pipe(Effect.provide(NodeServices.layer)); + +describe("OpenCode 2 pending-work snapshots (#19228 evidence)", () => { + it.effect.each(ROWS.map((row) => [`${row.id} ${row.fixture}`, row] as const))("%s", ([, row]) => + runRow(row).pipe( + Effect.map((failures) => assert.deepEqual(failures, [])), + Effect.scoped, + ), + ); +}); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index a92256d7dd791..9d83da489b306 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -96,6 +96,8 @@ export const ProviderAdapterV2Event = Schema.Union([ type: Schema.Literal("provider_thread.updated"), driver: ProviderDriverKind, providerThread: OrchestrationV2ProviderThread, + /** Work remaining at this point in the event stream, including native continuations. */ + pendingBackgroundWork: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), }), Schema.Struct({ diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 71bceb594757f..2e0f76c34ea74 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -278,6 +278,7 @@ interface OpenBlock { interface ThreadState { readonly sessionId: string; providerThread: OrchestrationV2ProviderThread; + publishedBackgroundWork?: boolean; readonly providerTurns: Map; active: ActiveTurn | undefined; model: ModelRef | undefined; @@ -833,6 +834,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork); + const emitProviderThread = Effect.fnUntraced(function* (state: ThreadState) { + const pendingBackgroundWork = hasBackground(state); + state.publishedBackgroundWork = pendingBackgroundWork; + yield* emit({ + type: "provider_thread.updated", + driver, + providerThread: state.providerThread, + pendingBackgroundWork, + }); + }); + const setSessionStatus = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* ( @@ -1232,7 +1244,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr result: call.result, }, }); - yield* syncRoster(rootOf(call.state)); + yield* syncRosterAncestors(call.state); }); const syncRoster = Effect.fnUntraced(function* (state: ThreadState) { @@ -1248,6 +1260,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr })); const current = state.providerThread.pendingBackgroundTasks ?? []; if ( + state.publishedBackgroundWork === hasBackground(state) && current.length === roster.length && current.every( (task, index) => @@ -1264,11 +1277,15 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr pendingBackgroundTasks: roster, updatedAt: yield* DateTime.now, }; - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: state.providerThread, - }); + yield* emitProviderThread(state); + }); + + const syncRosterAncestors = Effect.fnUntraced(function* (state: ThreadState) { + let current: ThreadState | undefined = state; + while (current !== undefined) { + yield* syncRoster(current); + current = current.subagent?.call.state; + } }); const withReportedModel = ( @@ -1378,11 +1395,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr childOwners.set(childId, rootOf(call.state)); call.child = child; yield* emit({ type: "app_thread.created", driver, appThread }); - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: child.providerThread, - }); + yield* emitProviderThread(child); yield* emitSubagent(call); // Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them. if (info === undefined) { @@ -1417,11 +1430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr status: "idle", updatedAt: call.completedAt, }; - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: child.providerThread, - }); + yield* emitProviderThread(child); } yield* emitSubagent(call); }); @@ -1635,11 +1644,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr status: threadDisposition === "broken" ? "error" : "idle", updatedAt: completedAt, }; - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: state.providerThread, - }); + yield* emitProviderThread(state); const anyActive = [...threads.values()].some( (candidate) => candidate.subagent === undefined && candidate.active !== undefined, ); @@ -2406,11 +2411,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const providerThread = withReportedModel(state.providerThread, event.data.model); if (providerThread !== state.providerThread) { state.providerThread = { ...providerThread, updatedAt: yield* DateTime.now }; - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: state.providerThread, - }); + yield* emitProviderThread(state); } } if ( @@ -2621,10 +2622,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* settleCall(call, "interrupted", LOST_BACKGROUND); } } - for (const session of sessionsOf(state)) { + const sessions = sessionsOf(state); + for (const session of sessions) { discardWakes(session, session.wakes.splice(0)); session.reports.clear(); } + for (const session of sessions.toReversed()) yield* syncRoster(session); } // Stopped off the lock this reconcile holds; one still running waits for a Stop. for (const thread of new Set([...strays.values()].map(rootOf))) { @@ -2680,7 +2683,26 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr stream: Stream.Stream, ): Effect.Effect => stream.pipe( - Stream.runForEach((event) => lock.withPermit(handleEvent(event))), + Stream.runForEach((event) => + lock.withPermit( + Effect.gen(function* () { + yield* handleEvent(event); + if ( + event.type === "session.execution.started" || + event.type === "unreadable.execution.started" || + executionEnd(event.type) || + event.type === "unreadable.execution.ended" || + event.type === "session.inbox.enqueued" || + event.type === "session.inbox.delivered" || + event.type === "session.inbox.cancelled" + ) { + const sessionId = sessionOfEvent(event); + const state = sessionId === undefined ? undefined : threads.get(sessionId); + if (state !== undefined) yield* syncRosterAncestors(state); + } + }), + ), + ), Effect.exit, Effect.flatMap(() => Effect.gen(function* () { @@ -3158,11 +3180,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr lastRunOrdinal: turnInput.runOrdinal, updatedAt: startedAt, }; - yield* emit({ - type: "provider_thread.updated", - driver, - providerThread: state.providerThread, - }); + yield* emitProviderThread(state); yield* setSessionStatus("running", null); return turn; }); @@ -3218,6 +3236,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (wake?.running !== true) return; state.wakes.pop(); yield* replay(wake); + for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session); + yield* syncRosterAncestors(state); }); const runWake = Effect.fnUntraced(function* ( @@ -3243,6 +3263,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } if (wake.running) state.unsettled = false; yield* replay(wake); + for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session); + yield* syncRosterAncestors(state); }), ); }); @@ -3305,6 +3327,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const running = state.wakes.some((wake) => wake.running); discardWakes(state, state.wakes.splice(0)); + yield* syncRosterAncestors(state); if (running) { markUnsettled(state); yield* client.session From 53e168fef5efa6141c89c1775e0630d6dc488f49 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 19:01:06 -0800 Subject: [PATCH 35/37] fix(opencode): decode compaction history from OpenCode 2.1 (#22661) Co-authored-by: Claude Fable 5.1 --- .../Adapters/OpenCode2AdapterV2.test.ts | 1 + .../src/server/v2/OpenCode2Client.test.ts | 88 +++++++++++++++++++ .../src/server/v2/OpenCode2Client.ts | 58 +++++++++++- 3 files changed, 146 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 0ee94d494394a..c334af4fad113 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -3630,6 +3630,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: "completed", reason: "auto", summary: "First turn summary", + recent: 42, }, { id: "msg_dropped", time: { created: 3 }, text: "second", type: "user" }, ], diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index cee3372e14699..cf99beeecb256 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -1,7 +1,9 @@ import { assert, it } from "@effect/vitest"; +import { Session } from "@opencode/client/effect"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import { describe } from "vite-plus/test"; @@ -45,3 +47,89 @@ describe("OpenCode2Client authorization", () => { }), ); }); + +const previous = { + id: "msg_repro088", + type: "synthetic", + text: "Fixture message 88", + time: { created: 1088 }, +}; + +const compaction = (fields: Record) => ({ + type: "compaction", + id: "msg_repro089", + time: { created: 1089 }, + reason: "manual", + summary: "Fixture compaction", + ...fields, +}); + +const listHistory = (messages: ReadonlyArray) => + Effect.gen(function* () { + const transport = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + assert.include(request.url, "/api/session/ses_repro/message"); + return HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify({ data: messages, cursor: {} }), { + headers: { "content-type": "application/json" }, + }), + ); + }), + ), + ); + const opencode = yield* OpenCode2Client.OpenCode2Client.pipe( + Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(transport))), + ); + const { client } = yield* opencode.connect({ + baseUrl: "http://127.0.0.1:4096", + password: "test-password", + }); + return yield* client.message.list({ sessionID: Session.ID.make("ses_repro"), order: "asc" }); + }); + +describe("OpenCode2Client message history", () => { + it.effect.each([ + { status: "running", shape: "native keepID", fields: { metadata: { keepID: previous.id } } }, + { status: "completed", shape: "native keepID", fields: { metadata: { keepID: previous.id } } }, + { status: "running", shape: "native without metadata", fields: {} }, + { status: "completed", shape: "native without metadata", fields: {} }, + { + status: "completed", + shape: "legacy metadata", + fields: { metadata: { recent: previous.id } }, + }, + { status: "running", shape: "top-level", fields: { recent: previous.id } }, + ] as const)("decodes a $status compaction in the $shape format", ({ status, fields }) => + Effect.gen(function* () { + const history = yield* listHistory([previous, compaction({ status, ...fields })]); + + assert.deepStrictEqual( + history.data.map((message) => message.id), + [previous.id, "msg_repro089"], + ); + assert.deepInclude(history.data[1], { + type: "compaction", + status, + summary: "Fixture compaction", + recent: + "metadata" in fields && "recent" in fields.metadata ? previous.id : (fields.recent ?? ""), + }); + }), + ); + + it.effect.each([ + { field: "recent", fields: { status: "completed", recent: 42 } }, + { field: "reason", fields: { status: "completed", reason: "scheduled", recent: previous.id } }, + ] as const)("keeps a compaction with an invalid $field an error", ({ field, fields }) => + Effect.gen(function* () { + const error = yield* listHistory([compaction(fields)]).pipe(Effect.flip); + + assert.strictEqual(error._tag, "ClientError"); + assert.isTrue(Schema.isSchemaError(error.cause)); + assert.include(String(error.cause), field); + }), + ); +}); diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts index 79f6d5f917366..dc7de72ae13f9 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts @@ -142,6 +142,62 @@ const basicAuthorization = (password: string | Redacted.Redacted) => { return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`; }; +const MESSAGE_LIST_URL = /\/api\/session\/[^/?#]+\/message(?:[?#]|$)/; + +/** Reads only the page's shape; each message stays opaque for the real schema to judge. */ +const MessagePage = Schema.fromJsonString( + Schema.StructWithRest(Schema.Struct({ data: Schema.Array(Schema.Unknown) }), [ + Schema.Record(Schema.String, Schema.Unknown), + ]), +); +const decodePage = Schema.decodeUnknownOption(MessagePage); +const encodePage = Schema.encodeSync(MessagePage); + +const CompactionWithRecent = Schema.Struct({ + type: Schema.Literal("compaction"), + status: Schema.Literals(["running", "completed"]), + metadata: Schema.optionalKey(Schema.Unknown), +}); +const isCompactionWithRecent = Schema.is(CompactionWithRecent); +const isLegacyMetadata = Schema.is(Schema.Struct({ recent: Schema.String })); + +const fillCompactionRecent = (message: unknown) => + isCompactionWithRecent(message) && !("recent" in message) + ? { ...message, recent: isLegacyMetadata(message.metadata) ? message.metadata.recent : "" } + : message; + +/** + * OpenCode 2.1 dropped a compaction's `recent`, which the bundled 2.0.28 schema requires. + * Migrated pre-2.1 compactions keep it under `metadata.recent`; native 2.1 ones have none. + * T3 never reads it, so fill the gap; every other field still validates downstream. + */ +const fillCompactionRecents = HttpClient.transformResponse( + Effect.fnUntraced(function* ( + pending: Effect.Effect, + ) { + const response = yield* pending; + const { request } = response; + if ( + request.method !== "GET" || + response.status !== 200 || + !MESSAGE_LIST_URL.test(request.url) + ) { + return response; + } + const text = yield* response.text; + const page = decodePage(text); + // The response caches its body, so the untouched one still decodes downstream. + if (Option.isNone(page)) return response; + const filled = encodePage({ ...page.value, data: page.value.data.map(fillCompactionRecent) }); + // The filled body is longer than the one the server measured. + const { "content-length": _, ...headers } = response.headers; + return HttpClientResponse.fromWeb( + request, + new Response(filled, { status: response.status, headers }), + ); + }), +); + /** @public */ export const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; @@ -152,7 +208,7 @@ export const make = Effect.gen(function* () { HttpClientRequest.setHeader("Authorization", basicAuthorization(password)), ); return OpenCode.make({ baseUrl }).pipe( - Effect.provideService(HttpClient.HttpClient, authenticated), + Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)), Effect.map((client) => ({ client, events: readEvents.pipe( From 3e1e776af3f69f95ef180535c128a0c5127ab2c3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 19:05:15 -0800 Subject: [PATCH 36/37] fix(server): import valid conversations within each transcript record limit (#23192) Co-authored-by: Claude Opus 5.5 --- .../src/project/AgentSessionScanner.test.ts | 59 ++++++++++++++++--- .../server/src/project/AgentSessionScanner.ts | 20 ++----- 2 files changed, 55 insertions(+), 24 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 88408c69c7b64..ce1830b8c5710 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1450,9 +1450,11 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const claudeHomePath = yield* makeTempDir("t3code-record-budget-claude-"); const codexHomePath = yield* makeTempDir("t3code-record-budget-codex-"); const workspace = yield* makeTempDir("t3code-record-budget-workspace-"); - for (const [sessionId, padding, mtimeMs] of [ - ["excessive", "\n".repeat(100_001), nowMs], - ["older", "", nowMs - 1_000], + const exactLimit = makeRecordLimitTranscript(workspace, false); + // The newer transcript has 100,001 records; the older one has exactly 100,000. + for (const [sessionId, contents, mtimeMs] of [ + ["excessive", exactLimit.replace("record-limit-session", "excessive") + "{}\n", nowMs], + ["older", exactLimit, nowMs - 1_000], ] as const) { yield* writeTranscript({ filePath: path.join( @@ -1463,18 +1465,56 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { "24", `rollout-${sessionId}.jsonl`, ), + contents, + mtimeMs, + }); + } + const outcomes = yield* runRecentThreadOutcomes({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); + expect(outcomes[1]).toMatchObject({ + thread: { providerSessionId: "record-limit-session" }, + }); + }), + ); + + it.effect("imports every transcript that fits the per-file record limit", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-shared-records-claude-"); + const codexHomePath = yield* makeTempDir("t3code-shared-records-codex-"); + const workspace = yield* makeTempDir("t3code-shared-records-workspace-"); + // Together these exceed 100,000 records, but each one is individually valid. + const recordCounts = [20_000, 20_000, 20_000, 58_000]; + for (const [index, recordCount] of recordCounts.entries()) { + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-${index}.jsonl`, + ), contents: [ encodeTranscriptRecord({ type: "session_meta", - payload: { id: sessionId, cwd: workspace }, + payload: { id: `session-${index}`, cwd: workspace }, }), encodeTranscriptRecord({ type: "event_msg", payload: { type: "user_message", message: "Imported prompt" }, }), - ].join("\n") + padding, - mtimeMs, + ].join("\n") + + "\n" + + "{}\n".repeat(recordCount - 2), + mtimeMs: nowMs - index * 1_000, }); } const outcomes = yield* runRecentThreadOutcomes({ @@ -1482,8 +1522,11 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { codexHomePath, workspaceRoot: workspace, }); - expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); - expect(outcomes[1]).toMatchObject({ thread: { providerSessionId: "older" } }); + expect( + outcomes.map((outcome) => + outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag, + ), + ).toEqual(["session-0", "session-1", "session-2", "session-3"]); }), ); diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 6b75ca91e3b33..3ed97f8a7d8f4 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -996,7 +996,6 @@ export const make = Effect.gen(function* () { const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* ( filePath: string, expected: ReturnType, - recordLimit: number, source: AgentSessionSource, ) { if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; @@ -1030,7 +1029,7 @@ export const make = Effect.gen(function* () { const finishRecord = () => { reader.write(decoder.decode()); recordCount += 1; - if (recordCount > recordLimit) return false; + if (recordCount > MAX_IMPORT_RECORDS) return false; const value = reader.finish(); const decoded = decodeTranscriptValue(value); if (Option.isNone(decoded) && source === "pi") { @@ -1090,7 +1089,7 @@ export const make = Effect.gen(function* () { if (recordStarted && !(yield* Effect.try(finishRecord))) return null; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) - ? { records, recordCount, cwd, claudeFields } + ? { records, cwd, claudeFields } : null; }), ), @@ -1668,17 +1667,13 @@ export const make = Effect.gen(function* () { const codexThreadNamesByHome = new Map>(); let bytesRemaining = MAX_IMPORT_BYTES; let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS; - let recordsRemaining = MAX_IMPORT_RECORDS; return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe( Stream.mapEffect(({ candidate, transcript }) => Effect.gen(function* () { const completed = completedByFile.get( `${candidate.providerInstanceId}\0${transcript.filePath}`, ); - if ( - completed === undefined && - (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0) - ) { + if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining === 0)) { return Option.some({ _tag: "Skipped" }); } const stats = yield* statOption(transcript.filePath); @@ -1701,7 +1696,6 @@ export const make = Effect.gen(function* () { } if ( transcriptsRemaining === 0 || - recordsRemaining === 0 || identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES || identity.size > bytesRemaining ) { @@ -1709,16 +1703,10 @@ export const make = Effect.gen(function* () { } transcriptsRemaining -= 1; bytesRemaining -= identity.size; - const snapshot = yield* readTranscript( - transcript.filePath, - identity, - recordsRemaining, - candidate.source, - ); + const snapshot = yield* readTranscript(transcript.filePath, identity, candidate.source); if (snapshot === null) { return Option.some({ _tag: "Skipped" }); } - recordsRemaining -= snapshot.recordCount; if (Option.isNone(snapshot.cwd)) { return Option.some({ _tag: "Skipped" }); From 61c3794c32b0eeebfac09add43e403618c65d2d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 19:06:01 -0800 Subject: [PATCH 37/37] fix(server): imported Claude sessions resume on their first turn (#23219) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 80 ++++++++++++-- .../Adapters/ClaudeAdapterV2.ts | 101 ++++++++++-------- 2 files changed, 130 insertions(+), 51 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index daff636c77eee..45d21b5944e24 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2715,22 +2715,40 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { }); describe("ClaudeAdapterV2 native session identity", () => { - const openTurnWithOrdinal = (providerTurnOrdinal: number, nativeThreadHasTurns?: boolean) => + const openTurnWithOrdinal = ( + providerTurnOrdinal: number, + nativeThreadHasTurns?: boolean, + importedNativeThreadId?: string, + ) => Effect.scoped( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-v2-session-identity-", }); + if (importedNativeThreadId !== undefined) { + // An unreadable copy in another project must not hide the readable one. + yield* fileSystem.makeDirectory( + path.join(attachmentsDir, "projects", "-other", `${importedNativeThreadId}.jsonl`), + { recursive: true }, + ); + const projectDir = path.join(attachmentsDir, "projects", "-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(projectDir, `${importedNativeThreadId}.jsonl`), + `{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"${importedNativeThreadId}"}\n`, + ); + } const openedQueries: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, + environment: { CLAUDE_CONFIG_DIR: attachmentsDir }, attachmentsDir, fileSystem, - path: yield* Path.Path, + path, random: yield* SecureRandom.SecureRandom, idAllocator, queryRunner: { @@ -2763,12 +2781,49 @@ describe("ClaudeAdapterV2 native session identity", () => { modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); const now = yield* DateTime.now; + // Mirrors the provider thread a session import records: a strong native + // ref with no conversation head and no provider turns. + const providerThread = + importedNativeThreadId === undefined + ? yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }) + : yield* runtime.resumeThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + providerThread: { + id: idAllocator.derive.providerThread({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + nativeThreadId: importedNativeThreadId, + }), + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: importedNativeThreadId, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + contextUsage: null, + nativeMetadata: null, + goal: null, + createdAt: now, + updatedAt: now, + }, + }); yield* runtime.startTurn( makeClaudeTestTurnInput({ threadId, @@ -2814,6 +2869,15 @@ describe("ClaudeAdapterV2 native session identity", () => { assert.equal(openedQueries[0]?.options.title, "Claude attachment test"); }), ); + + it.effect("resumes an imported native session on its first T3 turn", () => + Effect.gen(function* () { + const openedQueries = yield* openTurnWithOrdinal(1, false, "imported-native-session"); + assert.equal(openedQueries.length, 1); + assert.equal(openedQueries[0]?.options.resume, "imported-native-session"); + assert.equal(openedQueries[0]?.options.sessionId, undefined); + }), + ); }); const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1abac1cf5de98..674f55c524d75 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -11301,41 +11301,47 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Effect.addFinalizer(() => closeSession()); // Metadata-only transcripts cannot be resumed or recreated; fail resumeThread to trigger a fresh session and handoff. - const hasEmptyClaudeTranscript = Effect.fn("ClaudeAdapterV2.hasEmptyClaudeTranscript")( - function* (nativeThreadId: string) { - const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; - const projectsDir = path.join( - configuredDir.length > 0 - ? path.resolve(session.cwd, configuredDir) - : path.join(yield* HostProcess.HomeDirectory, ".claude"), - "projects", - ); - // Any message in any transcript copy means Claude may still resume it. - let found = false; - for (const project of yield* fileSystem.readDirectory(projectsDir)) { - const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); - // Stray files beside the project dirs fail with ENOTDIR. - if ( - !(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false))) - ) { - continue; - } - const conversationLine = yield* fileSystem - .stream(transcriptPath) - .pipe( - Stream.decodeText, - Stream.splitLines, - Stream.filter(isClaudeConversationLine), - Stream.runHead, - ); - if (Option.isSome(conversationLine)) { - return false; - } - found = true; + const claudeTranscriptState = Effect.fn("ClaudeAdapterV2.claudeTranscriptState")(function* ( + nativeThreadId: string, + ) { + const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; + const projectsDir = path.join( + configuredDir.length > 0 + ? path.resolve(session.cwd, configuredDir) + : path.join(yield* HostProcess.HomeDirectory, ".claude"), + "projects", + ); + // Any message in any transcript copy means Claude may still resume it. + let found = false; + let unreadable = false; + for (const project of yield* fileSystem.readDirectory(projectsDir)) { + const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); + // Stray files beside the project dirs fail with ENOTDIR. + if ( + !(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false))) + ) { + continue; } - return found; - }, - ); + const conversationLine = yield* fileSystem + .stream(transcriptPath) + .pipe( + Stream.decodeText, + Stream.splitLines, + Stream.filter(isClaudeConversationLine), + Stream.runHead, + Effect.option, + ); + if (Option.isNone(conversationLine)) { + unreadable = true; + continue; + } + if (Option.isSome(conversationLine.value)) { + return "conversation" as const; + } + found = true; + } + return found && !unreadable ? ("empty" as const) : ("missing" as const); + }); const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, @@ -11427,16 +11433,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId !== undefined && nativeThreadId !== null && // A live process holds the conversation even before saving it. - (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId && - // An unreadable transcript leaves the resume to the CLI. - (yield* hasEmptyClaudeTranscript(nativeThreadId).pipe( - Effect.orElseSucceed(() => false), - )) + (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId ) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver: CLAUDE_PROVIDER, - detail: `Claude session ${nativeThreadId} has no conversation to resume.`, - }); + // An unreadable transcript leaves the resume to the CLI. + const transcript = yield* claudeTranscriptState(nativeThreadId).pipe( + Effect.orElseSucceed(() => "missing" as const), + ); + if (transcript === "empty") { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude session ${nativeThreadId} has no conversation to resume.`, + }); + } + // A session imported from the terminal has history but no T3 + // provider turns; opening it with sessionId fails "already in use". + if (transcript === "conversation") { + yield* Ref.update(openedNativeThreads, (current) => + current.has(nativeThreadId) ? current : new Set(current).add(nativeThreadId), + ); + } } const updatedAt = yield* DateTime.now; return {