diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.ts index 029bcaac2b487..5d407feff79d1 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.test.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts @@ -211,3 +211,75 @@ it.effect.each([ }), ).pipe(Effect.provide(DesktopState.layer)), ); + +it.effect("installs the build the update action downloaded, not the one it offered", () => + Effect.scoped( + Effect.gen(function* () { + const installed = yield* Deferred.make(); + const shown = yield* Deferred.make(); + let navigate: ((event: { preventDefault: () => void }, url: string) => void) | undefined; + const recovery = { + isDestroyed: () => false, + loadURL: () => Promise.resolve(), + once: () => {}, + webContents: { + setWindowOpenHandler: () => {}, + on: (_event: string, listener: typeof navigate) => { + navigate = listener; + Deferred.doneUnsafe(shown, Effect.void); + }, + }, + } as unknown as Electron.BrowserWindow; + const offered = updateState({ status: "available", availableVersion: "0.1.4" }); + const state = yield* DesktopState.DesktopState; + yield* listen.pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ readFileString: () => Effect.succeed("0.1.3") }), + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + appVersion: "0.1.3", + stateDir: "/task/state", + logDir: "/task/logs", + path: { join: (...parts: string[]) => parts.join("/") }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Layer.succeed(ElectronApp.ElectronApp, { + on: () => Effect.void, + } as unknown as ElectronApp.ElectronApp["Service"]), + Layer.succeed( + ElectronShell.ElectronShell, + {} as ElectronShell.ElectronShell["Service"], + ), + Layer.succeed(ElectronTheme.ElectronTheme, { + shouldUseDarkColors: Effect.succeed(false), + } as ElectronTheme.ElectronTheme["Service"]), + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Effect.succeedNone, + create: () => Effect.succeed(recovery), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Layer.succeed(DesktopUpdates.DesktopUpdates, { + subscribe: Effect.succeed({ latest: offered, changes: Stream.empty }), + check: () => Effect.void, + getState: Effect.succeed(offered), + // A release published since the offer: the download fetches it instead. + download: Effect.succeed({ + accepted: true, + completed: true, + state: updateState({ status: "downloaded", downloadedVersion: "0.1.5" }), + }), + installPrepared: (version: string) => Deferred.succeed(installed, version), + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + ), + ), + ); + yield* SubscriptionRef.set(state.primaryBackendStartup, { + _tag: "Failing", + reason: "Server failed before readiness", + managedPolicy: false, + output: "Failure details", + }); + yield* Deferred.await(shown); + navigate!({ preventDefault: () => {} }, "https://startup-recovery.invalid/update"); + expect(yield* Deferred.await(installed)).toBe("0.1.5"); + }), + ).pipe(Effect.provide(DesktopState.layer)), +); diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index e6c210043cf26..769a30cf7680b 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -212,12 +212,15 @@ export const listen: Effect.Effect< switch (action) { case "update": { if (current._tag !== "Update") return; - const state = yield* updates.getState; - if (state.downloadedVersion === null) { + let { downloadedVersion } = yield* updates.getState; + if (downloadedVersion === null) { + // The download re-checks first, so it can fetch a newer build than the one offered. const download = yield* updates.download; if (!download.completed) return; + downloadedVersion = download.state.downloadedVersion; } - yield* updates.installPrepared(current.version); + if (downloadedVersion === null) return; + yield* updates.installPrepared(downloadedVersion); return; } case "reinstall": diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts index fdac65f86a595..5cdf2ba1b56dc 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts @@ -733,16 +733,15 @@ describe("DesktopRemoteUpdates", () => { it.effect("waits for a background check before installing a prepared update", () => { const backgroundCheckStarted = Deferred.makeUnsafe(); const releaseBackgroundCheck = Deferred.makeUnsafe(); - let checks = 0; + let blockCheck = false; const harness = makeHarness({ - checkForUpdates: Effect.suspend(() => { - checks += 1; - return checks === 2 + checkForUpdates: Effect.suspend(() => + blockCheck ? Deferred.succeed(backgroundCheckStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseBackgroundCheck)), ) - : Effect.void; - }), + : Effect.void, + ), }); return runRemoteUpdatesTest(harness, ({ requests, commits }) => @@ -755,6 +754,7 @@ describe("DesktopRemoteUpdates", () => { harness.emit("update-downloaded", { version: "1.2.4" }); yield* settle; + blockCheck = true; const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild); yield* Deferred.await(backgroundCheckStarted); assert.isTrue(yield* updates.isActionActive); diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 53bd956ca6da7..33ed00a764738 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -344,10 +344,11 @@ describe("DesktopUpdates", () => { const installFiber = yield* updates.install.pipe(Effect.forkScoped); yield* Deferred.await(installStarted); + const checksBefore = harness.checkCount(); const checkResult = yield* updates.check("manual"); assert.isFalse(checkResult.checked); - assert.equal(harness.checkCount(), 0); + assert.equal(harness.checkCount(), checksBefore); yield* Deferred.succeed(releaseInstall, undefined); const installResult = yield* Fiber.join(installFiber); @@ -358,7 +359,9 @@ describe("DesktopUpdates", () => { ); it.effect("preserves a queued installer after a background updater error", () => { - const harness = makeHarness(); + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-not-available")), + }); return Effect.scoped( Effect.gen(function* () { @@ -494,6 +497,145 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("downloads the newest release published since the last check", () => { + // electron-updater downloads the release its last checkForUpdates found. + let published = "1.2.4"; + let lastChecked: string | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + assert.equal((yield* updates.getState).availableVersion, "1.2.4"); + + published = "1.2.5"; + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("installs a release published after the retained download", () => { + let published = "1.2.4"; + let lastChecked: string | undefined; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + yield* updates.download; + yield* flushCallbacks; + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + + published = "1.2.5"; + const checksBefore = harness.checkCount(); + const result = yield* updates.installPrepared("1.2.4"); + assert.isTrue(result.accepted); + // A second check before downloading could find a stale feed's older release. + assert.equal(harness.checkCount(), checksBefore + 1); + assert.equal(harness.quitAndInstalls(), 1); + assert.equal(installedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("downloads the known offer when the check before downloading fails", () => { + let checks = 0; + const harness = makeHarness({ + checkForUpdates: Effect.suspend(() => { + checks += 1; + if (checks > 1) { + return Effect.fail( + new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({ + channel: null, + cause: new Error("offline"), + }), + ); + } + harness.emit("update-available", { version: "1.2.4" }); + return Effect.void; + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: "1.2.4" }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + // Remote requests treat a published error after their own check as final. + assert.notInclude( + harness.sentStates.map((state) => state.status), + "error", + ); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("installs the retained download when a stale feed offers an older release", () => { + let published = "1.2.5"; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: published })), + downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.5" })), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + + published = "1.2.4"; + const result = yield* updates.installPrepared("1.2.5"); + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 1); + assert.equal(installedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 055c6574391a6..775a9ff6b04ff 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -557,6 +557,17 @@ export const make = Effect.gen(function* () { }); }); + // The flag is shared updater state, so callers flip it only while holding a reservation. + const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* ( + allowDowngrade: boolean, + ) { + const restoreDowngrade = yield* electronUpdater.allowDowngrade; + if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); + return yield* electronUpdater.checkForUpdates.pipe( + Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + ); + }); + const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* ( reason: string, actionReservation: "acquire" | "held" = "acquire", @@ -586,11 +597,7 @@ export const make = Effect.gen(function* () { } yield* logUpdaterInfo("checking for updates", { reason }); - // The flag is shared updater state, so it flips only while this check holds the reservation. - const restoreDowngrade = yield* electronUpdater.allowDowngrade; - if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); - return yield* electronUpdater.checkForUpdates.pipe( - Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + return yield* runUpdaterCheck(allowDowngrade).pipe( Effect.as(true), Effect.catchTags({ ElectronUpdaterCheckForUpdatesError: Effect.fn( @@ -619,7 +626,10 @@ export const make = Effect.gen(function* () { ); }); - const downloadAvailableUpdate = Effect.gen(function* () { + // Install refreshes before downloading, and a second check could pick a stale, older release. + const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + refresh: boolean, + ) { const admission = yield* Effect.scoped( admitAfterCheck( Effect.gen(function* () { @@ -643,8 +653,29 @@ export const make = Effect.gen(function* () { return { accepted: false, completed: false }; } - const state = yield* Ref.get(updateStateRef); + const offered = yield* Ref.get(updateStateRef); + let state = offered; return yield* Effect.gen(function* () { + if (refresh) { + // electron-updater downloads what its last check found, which can be hours old. + yield* logUpdaterInfo("checking for updates", { reason: "download" }); + yield* runUpdaterCheck( + offered.channel !== desktopUpdateChannelOf(environment.appVersion), + ).pipe( + // A failed check keeps electron-updater's earlier result, so the known offer still downloads. + Effect.catchTags({ + ElectronUpdaterCheckForUpdatesError: (error) => + logUpdaterWarning(error.message, { + errorTag: error._tag, + cause: describeUpdateErrorCause(error.cause), + }), + }), + ); + } + state = yield* Ref.get(updateStateRef); + if (state.status !== "available") { + return { accepted: true, completed: false }; + } yield* setState(reduceDesktopUpdateStateOnDownloadStart(state)); yield* electronUpdater.setDisableDifferentialDownload( isArm64HostRunningIntelBuild(environment.runtimeInfo), @@ -693,7 +724,7 @@ export const make = Effect.gen(function* () { }), Effect.ensuring(finishUpdateAction("download")), ); - }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate")); + }); const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime"); const updateRestartMarkerPath = environment.path.join( @@ -948,7 +979,42 @@ export const make = Effect.gen(function* () { state: yield* Ref.get(updateStateRef), }; } - const result = yield* installDownloadedUpdate(expectedVersion); + let installVersion = expectedVersion; + // A download can be hours old: a release published since replaces it before restarting. + const retained = yield* Ref.get(updateStateRef); + if ( + retained.downloadedVersion !== null && + (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) && + (yield* checkForUpdates( + "install", + "acquire", + retained.channel !== desktopUpdateChannelOf(environment.appVersion), + )) && + (yield* Ref.get(updateStateRef)).status === "available" + ) { + const refreshed = yield* Ref.get(updateStateRef); + // electron-updater compares a stale feed with the running build, not the retained download. + if ( + refreshed.availableVersion === null || + compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + ) { + yield* setState(retained); + } else { + const download = yield* downloadAvailableUpdate(false); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + if (expectedVersion !== undefined) { + installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion; + } + } + } + const result = yield* installDownloadedUpdate(installVersion); return { accepted: result.accepted, completed: result.completed, @@ -1357,7 +1423,7 @@ export const make = Effect.gen(function* () { }; }), download: Effect.gen(function* () { - const result = yield* downloadAvailableUpdate; + const result = yield* downloadAvailableUpdate(true); return { accepted: result.accepted, completed: result.completed, diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 6f5db6a52f59c..88b4999c45532 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -62,6 +62,7 @@ import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches"; import { useThreadListV2 } from "../threads/useThreadListV2"; +import { useSidebarRowThreadKey } from "../threads/useSidebarRowThreadKey"; import { useThreadListNow } from "../threads/use-thread-list-now"; import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; @@ -203,7 +204,8 @@ export function HomeScreen(props: HomeScreenProps) { ); const columnMetrics = useNativeColumnLayoutMetrics(); const activeNewTask = useActiveNewTask(); - const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null); + const sidebarRowThreadKey = useSidebarRowThreadKey(primaryColumn?.selectedThreadKey ?? null); + const selectedThreadKey = activeNewTask ? null : sidebarRowThreadKey; const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined; const queuedThreadKeys = useQueuedThreadKeys(); const openSwipeableRef = useRef(null); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 2a173816d9981..aa551bd291569 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -85,6 +85,7 @@ import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { executeAtomQuery, + isAtomCommandInterrupted, settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; @@ -450,7 +451,14 @@ function AssistantForkButton(props: { }, }) .then(async (result) => { - if (result._tag !== "Success") return; + if (isAtomCommandInterrupted(result)) return; + if (result._tag !== "Success") { + Dialog.alert( + "Could not confirm fork", + "Reconnect and check the thread list before trying again.", + ); + return; + } const targetThreadReady = await waitForThreadShell( scopeThreadRef(props.environmentId, targetThreadId), ); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index b9c944ff2815b..6c854eaea3371 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -40,6 +40,7 @@ import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { useThreadListV2 } from "./useThreadListV2"; +import { useSidebarRowThreadKey } from "./useSidebarRowThreadKey"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; import { requestThreadMessageJump } from "./threadMessageJump"; import { useThreadListSearchMatches } from "./useThreadListSearchMatches"; @@ -127,6 +128,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { const { fabClearance, fabSize } = useAndroidControlSizing(); const projects = useProjects(); const threads = useAtomValue(steadyNavigationThreadShellsAtom); + const selectedThreadKey = useSidebarRowThreadKey(props.selectedThreadKey); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); const openSwipeableRef = useRef(null); @@ -288,7 +290,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded, - selectedThreadKey: props.selectedThreadKey ?? null, + selectedThreadKey, }); const listItems: readonly SidebarListItem[] = settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 @@ -351,7 +353,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { // Recycle equality needs project/search data for titles and favicons; keep the minute clock on items to limit updates. const listExtraData = { activeNewTask, - selectedThreadKey: props.selectedThreadKey ?? "", + selectedThreadKey: selectedThreadKey ?? "", projectByKey, projectTitleByProjectKey, savedConnectionsById, @@ -385,7 +387,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { scopedThreadKey( item.pendingTask.environmentId, item.pendingTask.message.threadId, - ) === props.selectedThreadKey) + ) === selectedThreadKey) } project={projectByKey.get(pendingScopeKey) ?? null} environmentLabel={ @@ -446,7 +448,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { pane="sidebar" selected={ !activeNewTask && - scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey + scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey } fullSwipeWidth={props.width - 20} onSelectThread={handleSelectThread} diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts new file mode 100644 index 0000000000000..0e72dad60ca0d --- /dev/null +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts @@ -0,0 +1,15 @@ +import { useAtomValue } from "@effect/atom-react"; +import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { resolveListedAncestorThreadRef } from "@t3tools/client-runtime/state/threads"; + +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { environmentThreadShells } from "../../state/threads"; + +/** An open subagent, side chat or delegated task has no row; its listed ancestor's row is selected. */ +export function useSidebarRowThreadKey(openThreadKey: string | null): string | null { + const threads = useAtomValue(environmentThreadShells.quietThreadShellsAtom); + const openThreadRef = openThreadKey === null ? null : parseScopedThreadKey(openThreadKey); + if (openThreadRef === null) return openThreadKey; + const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); + return scopedThreadKey(rowRef.environmentId, rowRef.threadId); +} diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index f53d124c1f152..97a2e97e78fad 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -687,6 +687,118 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("finds the newest Claude sessions in a large home beside empty ones", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-large-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const recentWorkspace = yield* makeTempDir("t3code-workspace-recent-"); + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-"); + // More project folders than the discovery budget reads, in an order unrelated to age. + const folderCount = 12_000; + const recentCount = 40; + const newestMs = Date.parse("2026-03-01T00:00:00.000Z"); + yield* Effect.sync(() => { + for (let index = 0; index < folderCount; index++) { + const age = (index * 7_919) % folderCount; + const directory = path.join(claudeHomePath, "projects", `-slug-${index}`); + const filePath = path.join(directory, `session-${index}.jsonl`); + const seconds = (newestMs - age * 60_000) / 1000; + NodeFS.mkdirSync(directory, { recursive: true }); + NodeFS.writeFileSync( + filePath, + claudeSessionLine(age < recentCount ? recentWorkspace : olderWorkspace), + ); + NodeFS.utimesSync(filePath, seconds, seconds); + NodeFS.utimesSync(directory, seconds, seconds); + } + }); + const emptyHomes = []; + for (let index = 0; index < 40; index++) { + emptyHomes.push([ + ProviderInstanceId.make(`claude-empty-${index}`), + { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: yield* makeTempDir(`t3code-claude-empty-${index}-`) }, + }, + ] as const); + } + + const result = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: Object.fromEntries(emptyHomes), + }); + + expect( + result.candidates.find((candidate) => candidate.path === recentWorkspace)?.threadCount, + ).toBe(recentCount); + }), + ); + + it.effect("passes budget a home frees while rescanning to the homes still short", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-empty-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const mediumHomePath = yield* makeTempDir("t3code-claude-medium-home-"); + const largeHomePath = yield* makeTempDir("t3code-claude-large-home-"); + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-"); + const lastWorkspace = yield* makeTempDir("t3code-workspace-last-"); + const newestMs = Date.parse("2026-03-01T00:00:00.000Z"); + // Both homes outgrow their first share; together they fit the source's budget, but only + // when what the medium home leaves over on its rescan reaches the large one, which is + // listed first and so needs a second pass. + yield* Effect.sync(() => { + const writeSessions = (directory: string, count: number, cwd: string, ageMs: number) => { + NodeFS.mkdirSync(directory, { recursive: true }); + const seconds = (newestMs - ageMs) / 1000; + for (let index = 0; index < count; index++) { + const filePath = path.join(directory, `session-${index}.jsonl`); + NodeFS.writeFileSync(filePath, claudeSessionLine(cwd)); + NodeFS.utimesSync(filePath, seconds, seconds); + } + }; + writeSessions( + path.join(mediumHomePath, "projects", "-medium"), + 8_000, + olderWorkspace, + 60_000, + ); + writeSessions( + path.join(largeHomePath, "projects", "-bulk"), + 11_000, + olderWorkspace, + 60_000, + ); + // Read last because its folder is oldest, yet it holds the newest session. + const lastDirectory = path.join(largeHomePath, "projects", "-last"); + writeSessions(lastDirectory, 1, lastWorkspace, 0); + const oldSeconds = (newestMs - 3_600_000) / 1000; + NodeFS.utimesSync(lastDirectory, oldSeconds, oldSeconds); + }); + + const result = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: { + [ProviderInstanceId.make("claude-large")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: largeHomePath }, + }, + [ProviderInstanceId.make("claude-medium")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: mediumHomePath }, + }, + }, + }); + + expect( + result.candidates.find((candidate) => candidate.path === lastWorkspace)?.threadCount, + ).toBe(1); + }), + ); + it.effect("honors provider instance home directory environment variables", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b32466487030f..c1f42586b2f33 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -273,6 +273,13 @@ interface MetadataReadBudget { truncated: boolean; } +function splitOperationBudget(budget: number, count: number): Array { + return Array.from( + { length: count }, + (_, index) => Math.floor(budget / count) + (index < budget % count ? 1 : 0), + ); +} + function selectMetadataTranscripts(transcripts: ReadonlyArray) { const selected: Array = []; let pending = Array.from( @@ -1395,7 +1402,35 @@ export const make = Effect.gen(function* () { operationsRemaining -= 1; return listDirectory(directory); }; - const projectDirectories = yield* readDirectory(projectsDir); + // Folder names carry no date, so read the newest folders first: a budget that runs out + // then drops the oldest sessions. Dating has its own allowance, apart from the reads. + let datesRemaining = operationBudget; + const dated: Array<{ readonly name: string; readonly mtimeMs: number }> = []; + const undated: Array = []; + for (const name of yield* readDirectory(projectsDir)) { + if (datesRemaining <= 0) { + undated.push(name); + continue; + } + datesRemaining -= 1; + const stats = yield* statOption(path.join(projectsDir, name)); + if (Option.isNone(stats) || stats.value.type !== "Directory") continue; + dated.push({ + name, + mtimeMs: Option.match(stats.value.mtime, { + onNone: () => 0, + onSome: (mtime) => mtime.getTime(), + }), + }); + } + const projectDirectories = [ + ...dated + .toSorted( + (left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name), + ) + .map((entry) => entry.name), + ...undated, + ]; const transcripts: Array = []; for (const projectDirectory of projectDirectories) { @@ -1431,7 +1466,7 @@ export const make = Effect.gen(function* () { }); } } - return { transcripts, truncated }; + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining }; }, ); @@ -1550,6 +1585,7 @@ export const make = Effect.gen(function* () { return roots === undefined ? transcript : { ...transcript, projectRoots: roots }; }), truncated, + operationsUsed: operationBudget - operationsRemaining, }; }, ); @@ -1605,7 +1641,7 @@ export const make = Effect.gen(function* () { } } } - return { transcripts, truncated }; + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining }; }); const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* ( @@ -1773,25 +1809,48 @@ export const make = Effect.gen(function* () { } const transcriptCandidates: Array = []; - const baseOperationBudget = Math.floor( - MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length), - ); - const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length); + const discover = + source === "claudeAgent" + ? discoverClaudeTranscripts + : source === "codex" + ? discoverCodexTranscripts + : discoverPiTranscripts; + const shares = splitOperationBudget(MAX_DISCOVERY_OPERATIONS_PER_SOURCE, homes.length); + const discovered: Array<{ + readonly transcripts: ReadonlyArray; + readonly truncated: boolean; + readonly operationsUsed: number; + }> = []; for (const [index, home] of homes.entries()) { - const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0); - if (operationBudget === 0) { - truncated = true; - continue; + const operationBudget = shares[index] ?? 0; + discovered.push( + operationBudget === 0 + ? { transcripts: [], truncated: true, operationsUsed: 0 } + : yield* discover(home.homePath, home.providerInstanceId, operationBudget), + ); + } + // Budget that small homes left unused goes to the homes that ran out, which rescan with it. + // Each takes an even split of what is still unused; a pass in which no home finishes spends + // it all, so every repeat has fewer starved homes. + let unused = + MAX_DISCOVERY_OPERATIONS_PER_SOURCE - + discovered.reduce((total, result) => total + result.operationsUsed, 0); + let starved = discovered.flatMap((result, index) => (result.truncated ? [index] : [])); + while (unused > 0 && starved.length > 0) { + for (const [position, index] of starved.entries()) { + if (unused <= 0) break; + const home = homes[index]!; + const before = discovered[index]!.operationsUsed; + const extra = Math.ceil(unused / (starved.length - position)); + const result = yield* discover(home.homePath, home.providerInstanceId, before + extra); + discovered[index] = result; + unused -= result.operationsUsed - before; } - const discover = - source === "claudeAgent" - ? discoverClaudeTranscripts - : source === "codex" - ? discoverCodexTranscripts - : discoverPiTranscripts; - const discovered = yield* discover(home.homePath, home.providerInstanceId, operationBudget); - truncated ||= discovered.truncated; - transcriptCandidates.push(...discovered.transcripts); + starved = starved.filter((index) => discovered[index]!.truncated); + } + for (const result of discovered) { + truncated ||= result.truncated; + transcriptCandidates.push(...result.transcripts); } transcriptCandidates.sort( diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 1acbf036fb52c..be5731795485c 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -154,6 +154,15 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +interface UntrackedBlobChange { + readonly git: Effect.Success>["git"]; + readonly write: ( + relativePath: string, + contents: string, + ) => Effect.Effect; + readonly checkpointRef: CheckpointRef; +} + const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* ( driver: Effect.Success>, cwd: string, @@ -529,6 +538,133 @@ it.effect("checkpoint capture ignores an inherited object directory", () => }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each([ + { name: "nothing changed", reuses: true, change: () => Effect.void }, + { + name: "its conversion attributes changed while it was being captured", + reuses: false, + change: () => Effect.void, + during: ({ write }: UntrackedBlobChange) => + Effect.orDie(write(".gitattributes", "*.txt text eol=lf\n")), + }, + { + name: "its conversion config changed while it was being captured", + reuses: false, + change: () => Effect.void, + during: ({ git }: UntrackedBlobChange) => + Effect.orDie(Effect.asVoid(git(["config", "core.autocrlf", "true"]))), + }, + { + name: "its conversion attributes changed", + reuses: false, + change: ({ write }: UntrackedBlobChange) => write(".gitattributes", "*.txt text eol=lf\n"), + }, + { + name: "a clean filter named like an unset attribute now applies to it", + reuses: false, + change: ({ git, write }: UntrackedBlobChange) => + write(".git/info/attributes", "*.txt filter=unspecified\n").pipe( + Effect.andThen(git(["config", "filter.unspecified.clean", "tr a-z A-Z"])), + ), + }, + { + name: "its conversion config changed", + reuses: false, + change: ({ git }: UntrackedBlobChange) => git(["config", "core.autocrlf", "true"]), + }, + { + name: "it was rewritten at the same size", + reuses: false, + change: ({ write }: UntrackedBlobChange) => + write("nested/large.txt", "LINE\r\n".repeat(3 * 1024 * 1024)), + }, + { + name: "it became ignored", + reuses: false, + change: ({ write }: UntrackedBlobChange) => write(".gitignore", "nested/\n"), + }, + { + name: "HEAD now tracks it", + reuses: false, + change: ({ git }: UntrackedBlobChange) => + git(["add", "nested/large.txt"]).pipe(Effect.andThen(git(["commit", "-m", "track"]))), + }, + { + name: "its directory became a repository", + reuses: false, + change: ({ git }: UntrackedBlobChange) => + git(["init", "nested"]).pipe( + Effect.andThen( + git( + ["-C", "nested", "-c", "user.name=Test", "-c", "user.email=test@test.com"].concat([ + "commit", + "--allow-empty", + "-m", + "nested", + ]), + ), + ), + ), + }, + { + name: "its blob was pruned", + reuses: false, + change: ({ git, checkpointRef }: UntrackedBlobChange) => + git(["update-ref", "-d", checkpointRef]).pipe(Effect.andThen(git(["prune", "--expire=now"]))), + }, +])( + "checkpoint capture skips hashing an untracked file only while a fresh hash would match: $name", + ({ reuses, change, during }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + let reused = 0; + let afterPublish: Effect.Effect = Effect.void; + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("core.ignorestat=true")) reused++; + // Only a capture whose staging took real time looks for files to remember. + if (input.args.includes("add")) + return liveProcess.run(input).pipe(Effect.tap(() => TestClock.adjust("1 second"))); + // The files are hashed and published by now, but not yet remembered. + return input.args.includes("update-ref") + ? liveProcess.run(input).pipe(Effect.tap(() => afterPublish)) + : liveProcess.run(input); + }, + }), + ); + // A driver that has never captured this workspace hashes every file, as a first capture does. + const fresh = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-untracked-blobs-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const write = (relativePath: string, contents: string) => + fs.writeFileString(path.join(cwd, relativePath), contents); + yield* fs.makeDirectory(path.join(cwd, "nested")); + yield* write("nested/large.txt", "line\r\n".repeat(3 * 1024 * 1024)); + // Only files left alone for a few seconds before a capture are remembered. + yield* TestClock.adjust("36500 days"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + // A file is remembered by the first capture that read its conversion rules before hashing it. + if (during !== undefined) afterPublish = during({ git, write, checkpointRef }); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + afterPublish = Effect.void; + + yield* change({ git, write, checkpointRef }); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const freshRef = CheckpointRef.make("refs/t3/checkpoints/fresh"); + yield* fresh.checkpoints.captureCheckpoint({ cwd, checkpointRef: freshRef }); + + assert.strictEqual(reused, reuses ? 1 : 0); + assert.strictEqual( + (yield* git(["rev-parse", `${checkpointRef}^{tree}`])).stdout, + (yield* git(["rev-parse", `${freshRef}^{tree}`])).stdout, + ); + yield* git(["fsck", "--connectivity-only"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["sha1", "sha256"] as const)( "checkpoint object isolation supports linked worktrees with $0 objects", (format) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index d1e9dae66f1fa..d0da1b3d09b3d 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,5 +1,6 @@ import * as NodeBuffer from "node:buffer"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -46,6 +47,7 @@ import { splitNullSeparatedGitStdoutPaths, } from "./GitVcsDriverCore.ts"; import * as CheckoutCloner from "./CheckoutCloner.ts"; +import * as CheckpointUntrackedBlobs from "./checkpointUntrackedBlobs.ts"; import * as VcsDriver from "./VcsDriver.ts"; import * as VcsProcess from "./VcsProcess.ts"; @@ -1066,6 +1068,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); + const untrackedBlobs = CheckpointUntrackedBlobs.make(execute, fileSystem); + const checkpoints: VcsDriver.VcsCheckpointOps = { captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; @@ -1091,6 +1095,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( lastMove !== undefined && lastMove.to === head ? `${lastMove.at} ${headMoves.filter((move) => move.at === lastMove.at).length}` : undefined; + const startedAt = yield* Clock.currentTimeMillis; const indexId = yield* random.uuidV4(); const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`); const hostEnv = yield* HostProcess.Environment; @@ -1379,6 +1384,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( } } + // Untracked files have no stat data in a new index, so git add would rehash every one. + const untracked = + topLevel === undefined || head === undefined || sparseCheckout || workspaceIgnored + ? undefined + : { cwd: input.cwd, topLevel, head, env: commitEnv }; + const { reused, before } = + untracked === undefined + ? CheckpointUntrackedBlobs.NOTHING + : yield* untrackedBlobs.reuse({ ...untracked, indexConfig }); + const stageFiles = (exclusions: ReadonlyArray) => execute({ operation, @@ -1400,6 +1415,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ], env: commitEnv, }); + const stagingAt = yield* Clock.currentTimeMillis; yield* stageFiles([]).pipe( Effect.catchTags({ VcsProcessExitError: (error) => @@ -1458,6 +1474,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); + const stagingMs = (yield* Clock.currentTimeMillis) - stagingAt; + const writeTreeResult = yield* execute({ operation, cwd: input.cwd, @@ -1723,6 +1741,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd: input.cwd, args: [...durableWrite, "update-ref", input.checkpointRef, commitOid], }); + if (untracked !== undefined) { + yield* untrackedBlobs.remember({ + ...untracked, + tree: treeOid, + startedAt, + stagingMs, + reused, + before, + }); + } }).pipe(Effect.ensuring(cleanupTempIndex)); // The tree records only each submodule's HEAD, so submodules keep their own ref. diff --git a/apps/server/src/vcs/checkpointUntrackedBlobs.ts b/apps/server/src/vcs/checkpointUntrackedBlobs.ts new file mode 100644 index 0000000000000..675dba0121615 --- /dev/null +++ b/apps/server/src/vcs/checkpointUntrackedBlobs.ts @@ -0,0 +1,456 @@ +// @effect-diagnostics nodeBuiltinImport:off - Comparing a file with its last capture needs bigint lstat, which FileSystem lacks. +import * as NodeFSP from "node:fs/promises"; + +import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; + +import type * as VcsDriver from "./VcsDriver.ts"; +import * as VcsProcess from "./VcsProcess.ts"; + +/** An untracked file's blob from the last capture, with everything that decided its content. */ +interface UntrackedBlob { + readonly path: string; + readonly mode: string; + readonly oid: string; + readonly size: bigint; + readonly stat: string; + readonly attributes: string; +} + +interface Snapshot { + readonly topLevel: string; + readonly head: string; + readonly config: string; + readonly blobs: ReadonlyArray; + /** Files hashed without a reading of their conversion state from before staging. */ + readonly pending: ReadonlyArray; +} + +/** The conversion state read before staging; a blob is remembered only if it reads the same after. */ +interface ConversionState { + readonly config: string; + readonly attributes: ReadonlyMap; +} + +export const NOTHING: { + readonly reused: ReadonlyArray; + readonly before: ConversionState | undefined; +} = { reused: [], before: undefined }; + +// Every attribute convert_to_git reads; a blob is reused only while all of them are unchanged. +const CONVERSION_ATTRIBUTES = [ + "text", + "eol", + "crlf", + "ident", + "working-tree-encoding", + "filter", +] as const; +const MAX_BLOBS = 20_000; +// Below this, hashing the files costs less than the Git processes that check them. +const MIN_TOTAL_BYTES = 16n * 1024n * 1024n; +// A capture that staged faster than this and reused nothing has nothing worth another Git process. +const MIN_STAGING_MS = 100; +// A file must have been left alone for this long before the capture, so an edit that lands +// while Git hashes it cannot hide inside one timestamp tick (two seconds on FAT). +const SETTLED_MS = 3_000; +const MAX_WORKSPACES = 64; +const STAT_BATCH = 512; +const LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; + +const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + +const lstatAll = (root: string, paths: ReadonlyArray) => + Effect.promise(async () => { + const stats: Array< + { stat: string; size: bigint; changedNs: bigint; regular: boolean } | undefined + > = []; + for (let start = 0; start < paths.length; start += STAT_BATCH) { + const batch = await Promise.all( + paths.slice(start, start + STAT_BATCH).map((entryPath) => + NodeFSP.lstat(`${root}/${entryPath}`, { bigint: true }).then( + (stat) => ({ + stat: `${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`, + size: stat.size, + changedNs: stat.mtimeNs > stat.ctimeNs ? stat.mtimeNs : stat.ctimeNs, + regular: stat.isFile(), + }), + () => undefined, + ), + ), + ); + stats.push(...batch); + } + return stats; + }); + +/** + * Lets a capture skip rehashing untracked files that have not changed since the last capture of + * the same workspace. A blob is reused only when a fresh `git add` would produce the same one: + * same file stat, same conversion attributes and config, still not ignored, still not tracked. + */ +export const make = ( + execute: VcsDriver.VcsDriver["Service"]["execute"], + fileSystem: FileSystem.FileSystem, +) => { + const snapshots = new Map(); + + // Worktree files only: an index copy of a deleted .gitattributes applies or not by staging order. + const readAttributes = Effect.fn("GitVcsDriver.checkpoints.readConversionAttributes")(function* ( + topLevel: string, + env: NodeJS.ProcessEnv, + paths: ReadonlyArray, + ) { + if (paths.length === 0) return []; + const stdin = `${paths.join("\0")}\0`; + const result = yield* execute({ + operation, + cwd: topLevel, + args: ["check-attr", "-z", "--stdin", ...CONVERSION_ATTRIBUTES], + stdin, + env: { ...env, GIT_INDEX_FILE: `${env.GIT_INDEX_FILE}.none` }, + maxOutputBytes: + CONVERSION_ATTRIBUTES.length * (Buffer.byteLength(stdin) + paths.length * 256), + outputMode: "error", + }); + // Records are " NUL NUL NUL", one per attribute, in input order. + const fields = result.stdout.split("\0"); + return paths.map((entryPath, index) => { + const values: string[] = []; + for (let attribute = 0; attribute < CONVERSION_ATTRIBUTES.length; attribute++) { + const field = (index * CONVERSION_ATTRIBUTES.length + attribute) * 3; + if (fields[field] !== entryPath || fields[field + 2] === undefined) return undefined; + values.push(fields[field + 2]!); + } + return values.join("\0"); + }); + }); + + // Config that changes the blob or mode `git add` records for an unchanged file. + const readConfig = (cwd: string) => + execute({ + operation, + cwd, + args: [ + "config", + "--null", + "--get-regexp", + "^(core\\.(autocrlf|eol|filemode)|filter\\.(unspecified|unset)\\..*)$", + ], + allowNonZeroExit: true, + }).pipe(Effect.map((result) => `${result.exitCode}\0${result.stdout}`)); + + /** + * Finds directories whose .gitattributes may have changed while Git hashed: a present file + * touched since just before the capture, or a missing one in a directory touched since then. + * Reading attributes before and after staging cannot see a change that was undone in between. + */ + const changingAttributeDirectories = Effect.fnUntraced(function* ( + topLevel: string, + paths: ReadonlyArray, + settledNs: bigint, + ) { + const directories = new Set(paths.length === 0 ? [] : [""]); + for (const entryPath of paths) { + for ( + let end = entryPath.lastIndexOf("/"); + end > 0 && !directories.has(entryPath.slice(0, end + 1)); + end = entryPath.lastIndexOf("/", end - 1) + ) { + directories.add(entryPath.slice(0, end + 1)); + } + } + const list = [...directories]; + const [files, parents] = yield* Effect.all([ + lstatAll( + topLevel, + list.map((directory) => `${directory}.gitattributes`), + ), + lstatAll(topLevel, list), + ]); + const changing = new Set( + list.filter((_, index) => { + const changedNs = (files[index] ?? parents[index])?.changedNs; + return changedNs === undefined || changedNs >= settledNs; + }), + ); + return (entryPath: string) => { + if (changing.has("")) return true; + for ( + let end = entryPath.lastIndexOf("/"); + end > 0; + end = entryPath.lastIndexOf("/", end - 1) + ) { + if (changing.has(entryPath.slice(0, end + 1))) return true; + } + return false; + }; + }); + + /** + * Adds the still-valid blobs to the scratch index, flagged so `git add` does not read their + * files. The index must hold exactly HEAD's paths. Returns the blobs it added, and the + * conversion state of every file this capture may remember, read before any of them is hashed. + */ + const reuse = Effect.fn("GitVcsDriver.checkpoints.reuseUntrackedBlobs")( + function* (input: { + readonly cwd: string; + readonly topLevel: string; + readonly head: string; + readonly env: NodeJS.ProcessEnv; + readonly indexConfig: ReadonlyArray; + }) { + const snapshot = snapshots.get(input.cwd); + // A capture that fails after this point hashes everything once more, then remembers again. + snapshots.delete(input.cwd); + if (snapshot === undefined || snapshot.topLevel !== input.topLevel) return NOTHING; + let blobs = snapshot.blobs; + if (snapshot.head !== input.head) { + // A path HEAD now tracks, or one below a path it changed, is no longer untracked. + const moved = yield* execute({ + operation, + cwd: input.cwd, + args: ["diff-tree", "-r", "-z", "--name-only", "--no-renames", snapshot.head, input.head], + maxOutputBytes: LIST_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + const changed = new Set(moved.stdout.split("\0")); + blobs = blobs.filter((blob) => { + for (let end = blob.path.length; end > 0; end = blob.path.lastIndexOf("/", end - 1)) { + if (changed.has(blob.path.slice(0, end))) return false; + } + return true; + }); + } + const stats = yield* lstatAll( + input.topLevel, + blobs.map((blob) => blob.path), + ); + blobs = blobs.filter((blob, index) => stats[index]?.stat === blob.stat); + // Git stages a directory that became a repository as one gitlink, not as its files. + const directories = new Set(); + for (const blob of blobs) { + for ( + let end = blob.path.lastIndexOf("/"); + end > 0 && !directories.has(blob.path.slice(0, end)); + end = blob.path.lastIndexOf("/", end - 1) + ) { + directories.add(blob.path.slice(0, end)); + } + } + const directoryList = [...directories]; + const repositories = yield* lstatAll( + input.topLevel, + directoryList.map((directory) => `${directory}/.git`), + ); + const nested = directoryList.filter((_, index) => repositories[index] !== undefined); + if (nested.length > 0) { + blobs = blobs.filter( + (blob) => !nested.some((directory) => blob.path.startsWith(`${directory}/`)), + ); + } + const paths = [...blobs.map((blob) => blob.path), ...snapshot.pending]; + if (paths.length === 0) return NOTHING; + const unchecked = Effect.succeed({ exitCode: 1, stdout: "" }); + const stdin = `${blobs.map((blob) => `${blob.path}\0`).join("")}`; + const [config, attributes, ignored, objects] = yield* Effect.all( + [ + readConfig(input.cwd), + readAttributes(input.topLevel, input.env, paths), + // Without --no-index this reports only untracked paths, which these are in this index. + blobs.length === 0 + ? unchecked + : execute({ + operation, + cwd: input.topLevel, + args: [...input.indexConfig, "check-ignore", "-z", "--stdin"], + stdin, + env: input.env, + allowNonZeroExit: true, + maxOutputBytes: Buffer.byteLength(stdin), + outputMode: "error", + }), + // Blobs of deleted checkpoints can be pruned while this process still remembers them. + blobs.length === 0 + ? unchecked + : execute({ + operation, + cwd: input.cwd, + args: ["cat-file", "--batch-check=%(objectname) %(objecttype)"], + stdin: `${[...new Set(blobs.map((blob) => blob.oid))].join("\n")}\n`, + maxOutputBytes: blobs.length * 128, + outputMode: "error", + }), + ], + { concurrency: "unbounded" }, + ); + const before: ConversionState = { + config, + attributes: new Map(paths.map((entryPath, index) => [entryPath, attributes[index]])), + }; + if (config !== snapshot.config || ignored.exitCode > 1) return { reused: [], before }; + const ignoredPaths = new Set(ignored.stdout.split("\0")); + const present = new Set(objects.stdout.split("\n")); + blobs = blobs.filter( + (blob, index) => + attributes[index] === blob.attributes && + !ignoredPaths.has(blob.path) && + present.has(`${blob.oid} blob`), + ); + if (blobs.length === 0) return { reused: [], before }; + + const indexFile = input.env.GIT_INDEX_FILE!; + const { mtime } = yield* fileSystem.stat(indexFile); + if (Option.isNone(mtime)) return { reused: [], before }; + yield* execute({ + operation, + cwd: input.cwd, + // core.ignorestat marks the new entries assume-unchanged, so git add trusts them as they are. + args: [ + ...input.indexConfig, + "-c", + "core.ignorestat=true", + "update-index", + "-z", + "--index-info", + ], + stdin: blobs.map((blob) => `${blob.mode} ${blob.oid}\t${blob.path}\0`).join(""), + env: input.env, + }); + // Tracked entries are racy against the index's old timestamp, not this rewrite's. + const indexTime = Math.floor(mtime.value.getTime() / 1000); + yield* fileSystem.utimes(indexFile, indexTime, indexTime); + return { reused: blobs, before }; + }, + Effect.orElseSucceed(() => NOTHING), + ); + + /** Records the untracked files the published checkpoint `tree` holds, for the next capture. */ + const remember = Effect.fn("GitVcsDriver.checkpoints.rememberUntrackedBlobs")( + function* (input: { + readonly cwd: string; + readonly topLevel: string; + readonly head: string; + readonly tree: string; + readonly env: NodeJS.ProcessEnv; + readonly startedAt: number; + readonly stagingMs: number; + readonly reused: ReadonlyArray; + readonly before: ConversionState | undefined; + }) { + if (input.reused.length === 0 && input.stagingMs < MIN_STAGING_MS) return; + const listed = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "diff-tree", + "-r", + "-z", + "--raw", + "--no-abbrev", + "--no-renames", + "--diff-filter=AD", + input.head, + input.tree, + ], + maxOutputBytes: LIST_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + const reused = new Map(input.reused.map((blob) => [blob.path, blob])); + const kept: UntrackedBlob[] = []; + const added: Array<{ path: string; mode: string; oid: string }> = []; + // Records are ": NUL NUL". + const fields = listed.stdout.split("\0"); + for (let field = 0; field + 1 < fields.length; field += 2) { + const [, mode = "", , oid = "", status] = fields[field]!.split(" "); + const entryPath = fields[field + 1]!; + if (status === "D") { + // Git may still apply a deleted .gitattributes from the index, depending on staging order. + if (entryPath === ".gitattributes" || entryPath.endsWith("/.gitattributes")) return; + continue; + } + // U+FFFD marks a name that is not UTF-8 and so cannot be addressed from here. + if ((mode !== "100644" && mode !== "100755") || entryPath.includes("\uFFFD")) continue; + const previous = reused.get(entryPath); + if (previous !== undefined && previous.oid === oid && previous.mode === mode) { + kept.push(previous); + } else { + added.push({ path: entryPath, mode, oid }); + } + } + const stats = yield* lstatAll( + input.topLevel, + added.map((entry) => entry.path), + ); + const settledNs = BigInt(input.startedAt - SETTLED_MS) * 1_000_000n; + const hashed = added.flatMap((entry, index) => { + const stat = stats[index]; + return stat !== undefined && stat.regular + ? [{ ...entry, size: stat.size, stat: stat.stat, settled: stat.changedNs < settledNs }] + : []; + }); + const largest = [...kept, ...hashed] + .sort((left, right) => (left.size < right.size ? 1 : left.size > right.size ? -1 : 0)) + .slice(0, MAX_BLOBS); + if (largest.reduce((total, blob) => total + blob.size, 0n) < MIN_TOTAL_BYTES) return; + + // Git hashed these under rules nobody recorded. Reading the rules now would pair the blob + // with whatever they have since become, so only a reading from before staging counts. + const before = input.before; + const candidates = largest.flatMap((blob) => + "settled" in blob && blob.settled && before?.attributes.get(blob.path) !== undefined + ? [blob] + : [], + ); + const candidatePaths = candidates.map((blob) => blob.path); + const [config, attributes, changing] = yield* Effect.all( + [ + readConfig(input.cwd), + readAttributes(input.topLevel, input.env, candidatePaths), + changingAttributeDirectories(input.topLevel, candidatePaths, settledNs), + ], + { concurrency: "unbounded" }, + ); + // check-attr prints a filter driver named "unspecified" or "unset" like no filter at all. + if (/\0filter\./.test(config)) return; + const sameConfig = before !== undefined && config === before.config; + const admitted = candidates.flatMap((blob, index): UntrackedBlob[] => { + const value = attributes[index]; + // A clean filter is a program whose output can depend on more than the file. + return sameConfig && + value !== undefined && + value === before.attributes.get(blob.path) && + /\0(?:unspecified|unset)$/.test(value) && + !changing(blob.path) + ? [ + { + path: blob.path, + mode: blob.mode, + oid: blob.oid, + size: blob.size, + stat: blob.stat, + attributes: value, + }, + ] + : []; + }); + // Reused blobs were checked against the earlier config; a different one now vouches for none. + const blobs = sameConfig + ? [...largest.flatMap((blob) => ("settled" in blob ? [] : [blob])), ...admitted] + : []; + const remembered = new Set(blobs.map((blob) => blob.path)); + snapshots.set(input.cwd, { + topLevel: input.topLevel, + head: input.head, + config, + blobs, + pending: largest.flatMap((blob) => (remembered.has(blob.path) ? [] : [blob.path])), + }); + if (snapshots.size > MAX_WORKSPACES) snapshots.delete(snapshots.keys().next().value!); + }, + (effect) => Effect.ignore(effect), + ); + + return { reuse, remember }; +}; diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 1bb6c9f2346d1..4380b80109446 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -11,7 +11,6 @@ import { deleteSelectedThreadEntries, getFallbackThreadIdAfterDelete, hasUnseenCompletion, - resolveSidebarRowThreadId, orderItemsByPreferredIds, pinOrderKeyBetween, resolveSidebarSweepKeys, @@ -138,48 +137,6 @@ describe("deleteSelectedThreadEntries", () => { }); }); -describe("sidebar thread lineage helpers", () => { - it("maps an open subagent to its nearest visible ancestor's sidebar row", () => { - const environmentId = EnvironmentId.make("environment-row"); - const otherEnvironmentId = EnvironmentId.make("environment-other"); - const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) => - makeThreadFixture({ - id: ThreadId.make(id), - environmentId: environment, - lineage: { - rootThreadId: parentId, - parentThreadId: parentId, - relationshipToParent: "subagent", - }, - }); - const root = makeThreadFixture({ id: ThreadId.make("thread-root"), environmentId }); - const fork = makeThreadFixture({ - id: ThreadId.make("thread-fork"), - environmentId, - lineage: { - rootThreadId: root.id, - parentThreadId: root.id, - relationshipToParent: "fork", - }, - }); - const child = subagentOf("thread-child", root.id); - const grandchild = subagentOf("thread-grandchild", child.id); - const forkChild = subagentOf("thread-fork-child", fork.id); - const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing")); - const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId); - const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere]; - - expect(resolveSidebarRowThreadId(child.id, environmentId, threads)).toBe(root.id); - expect(resolveSidebarRowThreadId(grandchild.id, environmentId, threads)).toBe(root.id); - expect(resolveSidebarRowThreadId(forkChild.id, environmentId, threads)).toBe(fork.id); - expect(resolveSidebarRowThreadId(elsewhere.id, otherEnvironmentId, threads)).toBe(elsewhere.id); - expect(resolveSidebarRowThreadId(orphan.id, environmentId, threads)).toBe(orphan.id); - const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b")); - const loopB = subagentOf("thread-loop-b", loopA.id); - expect(resolveSidebarRowThreadId(loopA.id, environmentId, [loopA, loopB])).toBe(loopA.id); - }); -}); - function makeLatestRun(overrides?: { completedAt?: string | null; startedAt?: string | null; diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 7bb9b514cc258..351505c4c666c 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -17,7 +17,6 @@ import { } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; import { - isListedThreadLineage, type ContextMenuItem, type EnvironmentId, type ResolvedKeybindingsConfig, @@ -582,30 +581,6 @@ export async function deleteSelectedThreadEntries< return { deletedThreadKeys, firstFailure }; } -function isSidebarHiddenThread(thread: Pick): boolean { - return !isListedThreadLineage(thread.lineage); -} - -// Subagent and side-chat threads have no sidebar row, so an open one is represented by -// its nearest listed ancestor. A broken chain (missing parent, cycle, -// other environment) resolves to the thread itself, which then matches no row. -export function resolveSidebarRowThreadId( - threadId: ThreadId, - environmentId: EnvironmentId, - threads: readonly Pick[], -): ThreadId { - const findThread = (id: ThreadId) => - threads.find((thread) => thread.id === id && thread.environmentId === environmentId); - const visited = new Set(); - let thread = findThread(threadId); - while (thread !== undefined && isSidebarHiddenThread(thread)) { - if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId; - visited.add(thread.id); - thread = findThread(thread.lineage.parentThreadId); - } - return thread?.id ?? threadId; -} - /** * `delegatedUnderParent` holds the tasks linked environments run for a thread * the sidebar lists, by thread key; they show under that thread, as subagents do. diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3314537973cbe..58cb50ae04e4e 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -59,7 +59,10 @@ import { type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; -import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; +import { + resolveListedAncestorThreadRef, + type OlderSettledScope, +} from "@t3tools/client-runtime/state/threads"; import { CheckIcon, @@ -208,7 +211,6 @@ import { useThreadJumpHintsVisible, type SidebarListItem, type SidebarSection, - resolveSidebarRowThreadId, } from "./Sidebar.logic"; import { createSidebarCollisionDetection, @@ -1108,16 +1110,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const routeRowThreadKey = routeThreadRef === null ? null - : scopedThreadKey( - scopeThreadRef( - routeThreadRef.environmentId, - resolveSidebarRowThreadId( - routeThreadRef.threadId, - routeThreadRef.environmentId, - threads, - ), - ), - ); + : scopedThreadKey(resolveListedAncestorThreadRef(routeThreadRef, threads)); const isSearchingThreads = threadSearchQuery.trim().length > 0; // History, the palette and links can open a thread the scope hides or the list diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.ts b/apps/web/src/components/chat/ComposerStashMenu.test.ts index efabfc93c42dd..b3d5016de6d1c 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.test.ts +++ b/apps/web/src/components/chat/ComposerStashMenu.test.ts @@ -1,3 +1,7 @@ +import { + formatComposerContextReference, + toComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; import { stashEntrySnippet } from "./ComposerStashMenu"; @@ -15,4 +19,13 @@ describe("stashEntrySnippet", () => { expect(stashEntrySnippet(entry(`${"a".repeat(89)}😀 and more`))).toBe(`${"a".repeat(89)}…`); expect(stashEntrySnippet(entry(`${"a".repeat(88)}😀 and more`))).toBe(`${"a".repeat(88)}😀…`); }); + + it("shows context chips by their label", () => { + const file = formatComposerContextReference({ + kind: "file", + contextId: toComposerContextId("readme"), + label: "README.md", + }); + expect(stashEntrySnippet(entry(`Summarize ${file} please`))).toBe("Summarize README.md please"); + }); }); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 15f19f0b3ed3f..4262d40bbc73b 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -1,6 +1,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; import { RelativeTime } from "../RelativeTime"; import { cn } from "~/lib/utils"; @@ -14,7 +15,11 @@ function missingImageCount(entry: PromptStashEntry): number { } export function stashEntrySnippet(entry: PromptStashEntry): string { - const trimmed = assistantCitationsToPlainText(entry.prompt).trim().replace(/\s+/g, " "); + const trimmed = assistantCitationsToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ) + .trim() + .replace(/\s+/g, " "); if (trimmed.length > 0) { if (trimmed.length <= SNIPPET_MAX_CHARS) return trimmed; // Never end on a lone high surrogate, the first half of an emoji. diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 9a91301465c54..f9ea5ee84503c 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -12,6 +12,7 @@ import type { } from "@t3tools/contracts"; import { useSettingsScope } from "./SettingsScopeContext"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; +import { useLiveRefresh } from "../../hooks/useLiveRefresh"; import { cn } from "../../lib/utils"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; @@ -414,6 +415,18 @@ export function SourceControlSettingsPanel() { const handleScan = () => { discovery.refresh(); }; + // A CLI login on the server host changes nothing the client reads, so returning to the window + // asks again. Discovery runs every hosting CLI, too costly for a timer nobody asked for. + useLiveRefresh( + () => { + if (!discovery.isPending) discovery.refresh(); + }, + { + enabled: environmentId !== null, + key: `source-control-discovery:${environmentId}`, + intervalMs: null, + }, + ); const offeredProviders = environment?.serverConfig?.settings.offeredSourceControlProviders; const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { label: "save source control providers", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index 4b5be38cc2928..647ec5921965f 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -85,6 +85,18 @@ describe("collectServerUpdateTargets", () => { ]); }); + it("does not offer a Nightly build to a Stable desktop app, whose own feed has nothing newer", () => { + const { targets, skipped } = collectServerUpdateTargets( + [machine("stable-desktop", "0.1.9", "desktop-managed")], + "0.1.10-nightly.20261116.4761", + ); + + expect(targets.map((target) => target.serverLabel)).toEqual([]); + expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([ + ["stable-desktop", "on the stable channel"], + ]); + }); + it("skips servers whose policy refuses the update, with the policy's message", () => { const managed = ( id: string, @@ -119,7 +131,10 @@ describe("collectServerUpdateTargets", () => { ...entry, serverConfig: { ...entry.serverConfig, - environment: { ...entry.serverConfig.environment, serverVersion: "0.0.49-nightly.1" }, + environment: { + ...entry.serverConfig.environment, + serverVersion: "0.0.49-nightly.20261027.1", + }, }, })), "0.0.50-nightly.20261028.1", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index a95a06084a320..d11292ab2a262 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -112,12 +112,14 @@ export function collectServerUpdateTargets( skip("needs a newer desktop app"); continue; } - const serverVersion = config.environment.serverVersion; + const serverChannel = cliReleaseChannelOf(config.environment.serverVersion); + // A desktop app installs its own track's newest release. Nightly builds run ahead of Stable, so a + // Nightly host behind a Stable target has something newer; a Stable host may not. if ( - selfUpdate !== "desktop-managed" && - cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion) + serverChannel !== cliReleaseChannelOf(targetVersion) && + (selfUpdate !== "desktop-managed" || serverChannel === "stable") ) { - skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`); + skip(`on the ${serverChannel} channel`); continue; } const target: ServerUpdateTarget = { diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index d18a3e3adae1c..de1bc04aeda8a 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -16,7 +16,11 @@ import { PrimaryConnectionTarget } from "../connection/model.ts"; import { v2Now, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; import { applyShellStreamEvent } from "./shellReducer.ts"; import { isThreadWorking } from "./threadInbox.ts"; -import { childThreadInputsTitle, createEnvironmentThreadShellAtoms } from "./threadShell.ts"; +import { + childThreadInputsTitle, + createEnvironmentThreadShellAtoms, + resolveListedAncestorThreadRef, +} from "./threadShell.ts"; const environmentId = EnvironmentId.make("environment-v2"); const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2"); @@ -679,3 +683,69 @@ describe("v2 thread shell lists", () => { } }); }); + +describe("resolveListedAncestorThreadRef", () => { + type Thread = Parameters[1][number]; + const otherEnvironmentId = EnvironmentId.make("environment-other"); + const ref = (environment: EnvironmentId, threadId: ThreadId) => ({ + environmentId: environment, + threadId, + }); + const listed = ( + id: string, + environment = environmentId, + overrides?: Partial, + ): Thread => ({ + id: ThreadId.make(id), + environmentId: environment, + lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null }, + archivedAt: null, + delegatedFrom: null, + ...overrides, + }); + const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) => + listed(id, environment, { + lineage: { + rootThreadId: parentId, + parentThreadId: parentId, + relationshipToParent: "subagent", + }, + }); + const rowOf = (threadId: ThreadId, environment: EnvironmentId, threads: readonly Thread[]) => + resolveListedAncestorThreadRef(ref(environment, threadId), threads); + + it("maps an open subagent to its nearest listed ancestor", () => { + const root = listed("thread-root"); + const fork = listed("thread-fork", environmentId, { + lineage: { rootThreadId: root.id, parentThreadId: root.id, relationshipToParent: "fork" }, + }); + const child = subagentOf("thread-child", root.id); + const grandchild = subagentOf("thread-grandchild", child.id); + const forkChild = subagentOf("thread-fork-child", fork.id); + const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing")); + const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId); + const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere]; + + expect(rowOf(child.id, environmentId, threads)).toEqual(ref(environmentId, root.id)); + expect(rowOf(grandchild.id, environmentId, threads)).toEqual(ref(environmentId, root.id)); + expect(rowOf(forkChild.id, environmentId, threads)).toEqual(ref(environmentId, fork.id)); + expect(rowOf(elsewhere.id, otherEnvironmentId, threads)).toEqual( + ref(otherEnvironmentId, elsewhere.id), + ); + expect(rowOf(orphan.id, environmentId, threads)).toEqual(ref(environmentId, orphan.id)); + const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b")); + const loopB = subagentOf("thread-loop-b", loopA.id); + expect(rowOf(loopA.id, environmentId, [loopA, loopB])).toEqual(ref(environmentId, loopA.id)); + }); + + it("maps an open task a linked environment delegated to its listed parent", () => { + const parent = listed("thread-parent", remoteEnvironmentId); + const task = listed("thread-task", environmentId, { + delegatedFrom: { environmentId: remoteEnvironmentId, threadId: parent.id, title: "Parent" }, + }); + + expect(rowOf(task.id, environmentId, [parent, task])).toEqual( + ref(remoteEnvironmentId, parent.id), + ); + }); +}); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 3aaaab30720ad..36998a906635d 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -69,6 +69,46 @@ export function isShownUnderParent( return !isListedThreadLineage(lineage) || delegatedUnderParent.has(threadKey(ref)); } +// Subagents, side chats and tasks delegated from a listed parent have no list row, +// so an open one is represented by its nearest listed ancestor. A broken chain +// (missing or archived parent, cycle) resolves to the thread itself, which then matches no row. +export function resolveListedAncestorThreadRef( + ref: ScopedThreadRef, + threads: readonly Pick< + EnvironmentThreadShell, + "id" | "environmentId" | "lineage" | "delegatedFrom" | "archivedAt" + >[], +): ScopedThreadRef { + const findThread = (target: ScopedThreadRef) => + threads.find( + (thread) => thread.id === target.threadId && thread.environmentId === target.environmentId, + ); + const visited = new Set(); + let current = ref; + let thread = findThread(current); + while (thread !== undefined) { + let parent: ScopedThreadRef; + if (!isListedThreadLineage(thread.lineage)) { + if (thread.lineage.parentThreadId === null) return ref; + parent = { environmentId: thread.environmentId, threadId: thread.lineage.parentThreadId }; + } else if (thread.delegatedFrom != null) { + parent = { + environmentId: thread.delegatedFrom.environmentId, + threadId: thread.delegatedFrom.threadId, + }; + // Mirrors delegatedUnderParent: a task whose parent is not listed keeps its own row. + if (findThread(parent)?.archivedAt !== null) return current; + } else { + return current; + } + if (visited.has(threadKey(current))) return ref; + visited.add(threadKey(current)); + current = parent; + thread = findThread(current); + } + return ref; +} + /** Provider-native subagents ask on their parent, so they are skipped. */ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {