diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index f7db3c277810..18813eb9025a 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -357,6 +357,34 @@ describe("DesktopSettings", () => { ), ); + it.effect("saves through a symlinked settings file without replacing the link", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + const dotfiles = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-settings-dotfiles-", + }); + const linkedSettingsPath = `${dotfiles}/desktop-settings.json`; + yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n"); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.symlink(linkedSettingsPath, environment.desktopSettingsPath); + + yield* settings.setServerExposureMode("network-accessible"); + + assert.equal( + yield* fileSystem.readLink(environment.desktopSettingsPath), + linkedSettingsPath, + ); + const persisted = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(linkedSettingsPath), + ); + assert.equal(persisted.serverExposureMode, "network-accessible"); + }), + ), + ); + it.effect("migrates legacy implicit update channels to the runtime default", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 19fcf0e75962..efd9fbfbfd3b 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -5,6 +5,7 @@ import { type DesktopUpdateChannel, } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; @@ -130,6 +131,7 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet const DesktopSettingsWriteOperation = Schema.Literals([ "create-temporary-file-name", + "resolve-symlink", "encode-document", "create-directory", "write-temporary-file", @@ -421,8 +423,20 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp readonly defaultSettings: DesktopSettings; readonly suffix: string; }): Effect.fn.Return { - const directory = input.path.dirname(input.settingsPath); - const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`; + const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe( + Effect.provideService(FileSystem.FileSystem, input.fileSystem), + Effect.provideService(Path.Path, input.path), + Effect.mapError( + (cause) => + new DesktopSettingsWriteError({ + operation: "resolve-symlink", + path: input.settingsPath, + cause, + }), + ), + ); + const directory = input.path.dirname(targetPath); + const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`; const encoded = yield* encodeDesktopSettingsJson( toDesktopSettingsDocument(input.settings, input.defaultSettings), ).pipe( @@ -455,7 +469,7 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp }), ), ); - yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe( + yield* input.fileSystem.rename(tempPath, targetPath).pipe( Effect.mapError( (cause) => new DesktopSettingsWriteError({ diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 94fe587136ef..2d88fb80a670 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -149,6 +149,34 @@ describe("DesktopClientSettings", () => { ), ); + it.effect("saves through a symlinked client settings file without replacing the link", () => + withClientSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopClientSettings.DesktopClientSettings; + const dotfiles = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-client-settings-dotfiles-", + }); + const linkedSettingsPath = `${dotfiles}/client-settings.json`; + yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n"); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.symlink(linkedSettingsPath, environment.clientSettingsPath); + + yield* settings.set(clientSettings); + + assert.equal( + yield* fileSystem.readLink(environment.clientSettingsPath), + linkedSettingsPath, + ); + assert.deepEqual( + yield* decodeClientSettingsJson(yield* fileSystem.readFileString(linkedSettingsPath)), + clientSettings, + ); + }), + ), + ); + it.effect.each([ { label: "permission", reason: "PermissionDenied" }, { label: "I/O", reason: "Unknown" }, diff --git a/apps/desktop/src/settings/DesktopClientSettings.ts b/apps/desktop/src/settings/DesktopClientSettings.ts index cd7fea6ca116..50b1e09aacee 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.ts @@ -1,5 +1,6 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; @@ -41,6 +42,7 @@ export class DesktopClientSettingsReadError extends Schema.TaggedError { - const directory = input.path.dirname(input.settingsPath); - const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`; + const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe( + Effect.provideService(FileSystem.FileSystem, input.fileSystem), + Effect.provideService(Path.Path, input.path), + Effect.mapError( + (cause) => + new DesktopClientSettingsWriteError({ + operation: "resolve-symlink", + path: input.settingsPath, + cause, + }), + ), + ); + const directory = input.path.dirname(targetPath); + const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`; const encoded = yield* encodeClientSettingsJson(input.settings).pipe( Effect.mapError( (cause) => @@ -158,7 +172,7 @@ const writeClientSettings = Effect.fnUntraced(function* (input: { }), ), ); - yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe( + yield* input.fileSystem.rename(tempPath, targetPath).pipe( Effect.mapError( (cause) => new DesktopClientSettingsWriteError({ diff --git a/apps/mobile/package.json b/apps/mobile/package.json index d1bd5c810894..b5f0d49d2bc1 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -114,7 +114,7 @@ "react-native": "0.88.0-rc.3", "react-native-gesture-handler": "~3.2.1", "react-native-image-viewing": "^0.2.2", - "react-native-keyboard-controller": "1.22.4", + "react-native-keyboard-controller": "1.22.6", "react-native-nitro-markdown": "^0.5.0", "react-native-nitro-modules": "0.35.9", "react-native-reanimated": "4.7.0", diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index a7623b7543aa..e01c51d8f82f 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -45,6 +45,7 @@ import { ThreadListV2SettledShelfHeader, ThreadListV2ShowMoreRow, ThreadListV2SnoozedShelfHeader, + ThreadListV2WorkingShelfHeader, } from "../threads/thread-list-v2-items"; import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance"; import { @@ -52,6 +53,7 @@ import { getThreadListV2OrderedSection, buildThreadListV2ListItems, threadListV2ListItemsAreEqual, + threadListInboxReturns, THREAD_LIST_V2_SETTLED_INITIAL_COUNT, THREAD_LIST_V2_SETTLED_PAGE_COUNT, type ThreadListV2ListItem, @@ -467,8 +469,11 @@ export function HomeScreen(props: HomeScreenProps) { loaded: shelfPreferencesLoaded, settledShelfExpanded, snoozedShelfExpanded, + workingShelfEnabled, + workingShelfExpanded, toggleSettledShelf, toggleSnoozedShelf, + toggleWorkingShelf, } = useThreadListV2ShelfPreferences(); // The queued-start and snooze helpers need a clock while the list stays open. const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); @@ -524,8 +529,13 @@ export function HomeScreen(props: HomeScreenProps) { queuedThreadKeys, }), }); - return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]); + // The Working beta orders the inbox by time, so only pins can move. + return new Map([ + ...sectionAvailability("pinned"), + ...(workingShelfEnabled ? [] : sectionAvailability("active")), + ]); }, [ + workingShelfEnabled, pinReorderEnvironmentIds, activeReorderEnvironmentIds, props.threads, @@ -537,6 +547,7 @@ export function HomeScreen(props: HomeScreenProps) { snoozeWakeTick, ]); const threadListV2Layout = useMemo(() => { + threadListInboxReturns.observe(workingShelfEnabled ? props.threads : null); // Settled threads are live shells; archived threads keep their original // "hidden from lists" meaning. return buildThreadListV2Items({ @@ -551,11 +562,16 @@ export function HomeScreen(props: HomeScreenProps) { queuedThreadKeys, settledLimit: settledVisibleCount, now: new Date().toISOString(), + workingShelfEnabled, + workingShelfExpanded, + inboxReturnAt: threadListInboxReturns.returnedAt, snoozedShelfExpanded, settledShelfExpanded, selectedThreadKey: null, }); }, [ + workingShelfEnabled, + workingShelfExpanded, pendingOrder, queuedThreadKeys, nowMinute, @@ -610,6 +626,9 @@ export function HomeScreen(props: HomeScreenProps) { buildThreadListV2ListItems({ items: threadListV2Layout.items, pendingTasks: v2PendingTasks, + workingCount: threadListV2Layout.workingCount, + workingShelfExpanded, + workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex, snoozedCount: threadListV2Layout.snoozedCount, snoozedShelfExpanded, snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex, @@ -632,6 +651,7 @@ export function HomeScreen(props: HomeScreenProps) { snoozeEnvironmentIds, threadListV2Layout, v2PendingTasks, + workingShelfExpanded, ], ); @@ -666,6 +686,16 @@ export function HomeScreen(props: HomeScreenProps) { /> ); } + if (item.type === "v2-working-shelf") { + return ( + + ); + } if (item.type === "v2-snoozed-shelf") { return ( item.key, []); @@ -804,6 +836,8 @@ export function HomeScreen(props: HomeScreenProps) { savedConnectionsById: props.savedConnectionsById, searchQuery: props.searchQuery, threadSearchMatchByKey, + // Rows read it for their reorder menu items. + workingShelfEnabled, }), [ projectByKey, @@ -812,6 +846,7 @@ export function HomeScreen(props: HomeScreenProps) { listEnvironments, threadSearchMatchByKey, v2ProjectTitleByProjectKey, + workingShelfEnabled, ], ); diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx index 5ff83dea728f..dab724e236a3 100644 --- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx @@ -45,6 +45,7 @@ export function SettingsThreadsRouteScreen() { contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} > + @@ -239,6 +240,35 @@ function AutoSettleSettingsRows() { ); } +/** + * Device-local beta toggles, the counterpart of web's Working section (beta) + * in Settings → General. + */ +function BetaSettingsSection() { + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const preferences = useAtomValue(mobilePreferencesAtom); + const workingShelfEnabled = + AsyncResult.isSuccess(preferences) && preferences.value.workingShelfEnabled === true; + + return ( + + + savePreferences({ workingShelfEnabled: value })} + /> + + + Fold working and monitoring threads into a Working section. They return to the top of the + list when they need you. While this is on, active threads are ordered by time and cannot be + moved. + + + ); +} + /** * Device-local legacy toggles. Mobile has no client-settings sync, so this is * the counterpart of web's Settings → General → Legacy features backed by diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx new file mode 100644 index 000000000000..bef52c4b7c75 --- /dev/null +++ b/apps/mobile/src/features/threads/SubagentRow.tsx @@ -0,0 +1,154 @@ +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { resolveSubagentMetadata } from "@t3tools/client-runtime/state/subagent-display"; +import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts"; +import type { ReactNode } from "react"; +import { View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { SymbolView } from "../../components/AppSymbol"; +import { ProviderIcon } from "../../components/ProviderIcon"; +import { cn } from "../../lib/cn"; +import { useEnvironmentServerConfig, useProject, useThreadShell } from "../../state/entities"; +import { subagentCardDetail } from "./subagent-card-presentation"; +import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot"; +import { resolveSubagentRowPresentation } from "./threadAgentsPresentation"; + +type SubagentRowSubagent = Pick< + OrchestrationV2Subagent, + | "threadId" + | "childThreadId" + | "model" + | "driver" + | "providerInstanceId" + | "title" + | "prompt" + | "status" + | "progress" + | "result" +>; + +/** + * One agent as shown in the Agents sheet and transcript cards: status, model, + * workspace changes, and recent progress or result. Callers own the press + * target and pass their own elapsed timer so ticking stays isolated. + */ +export function SubagentRow(props: { + readonly environmentId: EnvironmentId; + readonly subagent: SubagentRowSubagent; + readonly elapsed: ReactNode; +}) { + const presentation = resolveSubagentRowPresentation(props.subagent); + const detail = subagentCardDetail(presentation.detail); + return ( + + + + + + + + + {presentation.title} + + + · + + + {presentation.statusLabel} + + + {props.elapsed} + {presentation.canOpenThread ? ( + + ) : null} + + + {detail ? ( + + {detail} + + ) : null} + + + ); +} + +/** Uses shell data already held by the client, without loading child transcripts. */ +function SubagentMetadata(props: { + readonly environmentId: EnvironmentId; + readonly subagent: SubagentRowSubagent; +}) { + const { environmentId, subagent } = props; + const config = useEnvironmentServerConfig(environmentId); + const provider = config?.providers.find( + (candidate) => candidate.instanceId === subagent.providerInstanceId, + ); + const parent = useThreadShell(scopeThreadRef(environmentId, subagent.threadId))?.source; + const child = useThreadShell( + subagent.childThreadId === null ? null : scopeThreadRef(environmentId, subagent.childThreadId), + )?.source; + const parentProject = useProject( + parent ? scopeProjectRef(environmentId, parent.projectId) : null, + ); + const childProject = useProject(child ? scopeProjectRef(environmentId, child.projectId) : null); + const { modelLabel, workspace } = resolveSubagentMetadata({ + model: subagent.model, + provider, + parentThread: parent, + childThread: child, + parentProject, + childProject, + }); + return ( + + + + {provider?.displayName ? `${provider.displayName} · ` : ""} + {modelLabel} + + {workspace.map(({ label, value }) => ( + // The row reads this label in place of the icon. collapsable keeps the + // view (and label) from being flattened away without making it a + // separate accessibility stop. + + · + + + {value} + + + ))} + + ); +} diff --git a/apps/mobile/src/features/threads/SubagentStatusDot.tsx b/apps/mobile/src/features/threads/SubagentStatusDot.tsx index a08355effb50..348f6e534b6c 100644 --- a/apps/mobile/src/features/threads/SubagentStatusDot.tsx +++ b/apps/mobile/src/features/threads/SubagentStatusDot.tsx @@ -10,19 +10,25 @@ const TONE_CLASS = { stopped: "bg-foreground-muted", } as const satisfies Record; +export const SUBAGENT_TONE_TEXT_CLASS = { + working: "text-adaptive-sky-600-400", + completed: "text-adaptive-emerald-600-400", + failed: "text-adaptive-rose-600-400", + stopped: "text-foreground-muted", +} as const satisfies Record; + export function SubagentStatusDot({ tone, placement = "inline", }: { readonly tone: SubagentRowTone; - readonly placement?: "inline" | "provider" | "sheet"; + readonly placement?: "inline" | "sheet"; }) { return ( diff --git a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx index 7d7c825aaa08..1d082515172d 100644 --- a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx @@ -17,13 +17,10 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AndroidSheetHeader } from "../../components/AndroidScreenHeader"; import { AppText as Text } from "../../components/AppText"; -import { SymbolView } from "../../components/AppSymbol"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { environmentThreadDetails } from "../../state/threads"; import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; -import { resolveSubagentRowPresentation } from "./threadAgentsPresentation"; - -import { SubagentStatusDot } from "./SubagentStatusDot"; +import { SubagentRow } from "./SubagentRow"; const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); @@ -72,6 +69,7 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { @@ -121,32 +119,21 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { } function AgentRow(props: { + readonly environmentId: EnvironmentId; readonly subagent: OrchestrationV2Subagent; readonly tickSeconds: boolean; readonly onOpen: (childThreadId: ThreadId) => void; }) { const { subagent } = props; - const presentation = resolveSubagentRowPresentation(subagent); const childThreadId = subagent.childThreadId; - const elapsed = useSubagentElapsed(subagent, props.tickSeconds); const row = ( - - - - - {presentation.title} - - - {presentation.detail ?? presentation.statusLabel} - - - {elapsed === null ? null : ( - {elapsed} - )} - {presentation.canOpenThread ? ( - - ) : null} + + } + /> ); @@ -154,7 +141,6 @@ function AgentRow(props: { return ( {row} @@ -165,7 +151,6 @@ function AgentRow(props: { return ( props.onOpen(childThreadId)} className="active:opacity-70" @@ -175,9 +160,19 @@ function AgentRow(props: { ); } +function AgentElapsed(props: { + readonly subagent: OrchestrationV2Subagent; + readonly tickSeconds: boolean; +}) { + const elapsed = useSubagentElapsed(props.subagent, props.tickSeconds); + return elapsed === null ? null : ( + {elapsed} + ); +} + /** - * Elapsed time for one agent. Only a roster with live work subscribes to the - * shared second tick, so a settled sheet never repaints. + * Elapsed time for one agent. Only live work ticks, inside AgentElapsed, + * so the timer never repaints the metadata or a settled sheet. */ function useSubagentElapsed( subagent: Pick, diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx index 411c53a1cc35..f95f9a763ccd 100644 --- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx @@ -6,6 +6,7 @@ import { effectiveSnoozed, environmentAllowsThreadSettlement, } from "@t3tools/client-runtime/state/thread-settled"; +import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox"; import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { Animated, FlatList, Modal, Pressable, View } from "react-native"; import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler"; @@ -30,7 +31,8 @@ import { threadDragAction, type ThreadMoveDestination, } from "./threadOrder"; -import { getThreadListV2OrderedSection } from "./threadListV2"; +import { getThreadListV2OrderedSection, threadListInboxReturns } from "./threadListV2"; +import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; const ROW_HEIGHT = 56; const HEADER_HEIGHT = 48; @@ -158,6 +160,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) { const pendingOrder = useAtomValue(pendingThreadOrderAtom); const dropBusy = useAtomValue(threadDropBusyAtom); const { moveThread } = useThreadListActions(); + const { workingShelfEnabled } = useThreadListV2ShelfPreferences(); const [now, setNow] = useState(() => new Date().toISOString()); const [expanded, setExpanded] = useState({ snoozed: false, settled: false }); useEffect(() => { @@ -198,23 +201,28 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) { ); return { pinned, - active, + // The Working beta orders the inbox by time; show that order here too. + active: workingShelfEnabled + ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt) + : active, snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })), settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })), }; - }, [threads, configs, now, queuedThreadKeys, pendingOrder]); + }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]); const planners = useMemo(() => { const planner = (section: "pinned" | "active") => createThreadMovePlanner({ ordered: sections[section], allThreads: threads, section, + // A time-ordered inbox has no slots, so Active takes no drops while + // the Working beta is on. The saved arrangement stays untouched. reorderableEnvironmentIds: new Set( [...configs].flatMap(([id, config]) => ( section === "pinned" ? config.environment.capabilities.threadPinReorder - : config.environment.capabilities.threadActiveReorder + : !workingShelfEnabled && config.environment.capabilities.threadActiveReorder ) ? [id] : [], @@ -222,7 +230,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) { ), }); return { pinned: planner("pinned"), active: planner("active") }; - }, [sections, threads, configs]); + }, [sections, threads, configs, workingShelfEnabled]); const rows = useMemo(() => { const result: Row[] = []; let offset = 0; diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 80189fa85a35..dca49b7c55af 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -476,11 +476,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread } if (pendingBackgroundWork !== null && contentPresentationKind === "ready") { return { - kind: "waiting", + kind: "background", label: pendingBackgroundWork.title, accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items .map((item) => item.label) .join(", ")}`, + waiting: pendingBackgroundWork.waiting, }; } return null; diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 639d14cea5b5..4de1d1523526 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -62,6 +62,7 @@ import { ThreadListV2SettledShelfHeader, ThreadListV2ShowMoreRow, ThreadListV2SnoozedShelfHeader, + ThreadListV2WorkingShelfHeader, } from "./thread-list-v2-items"; import { useThreadRowProviderInstanceResolver } from "./thread-provider-instance"; import { @@ -70,6 +71,7 @@ import { buildThreadListV2ListItems, isThreadListV2ListItem, threadListV2ListItemsAreEqual, + threadListInboxReturns, THREAD_LIST_V2_SETTLED_INITIAL_COUNT, THREAD_LIST_V2_SETTLED_PAGE_COUNT, type ThreadListV2ListItem, @@ -292,8 +294,11 @@ function ThreadNavigationSidebarPane( loaded: shelfPreferencesLoaded, settledShelfExpanded, snoozedShelfExpanded, + workingShelfEnabled, + workingShelfExpanded, toggleSettledShelf, toggleSnoozedShelf, + toggleWorkingShelf, } = useThreadListV2ShelfPreferences(); // The queued-start and snooze helpers need a clock while the pane stays open. const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); @@ -347,8 +352,13 @@ function ThreadNavigationSidebarPane( queuedThreadKeys, }), }); - return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]); + // The Working beta orders the inbox by time, so only pins can move. + return new Map([ + ...sectionAvailability("pinned"), + ...(workingShelfEnabled ? [] : sectionAvailability("active")), + ]); }, [ + workingShelfEnabled, pinReorderEnvironmentIds, activeReorderEnvironmentIds, threads, @@ -360,6 +370,7 @@ function ThreadNavigationSidebarPane( snoozeWakeTick, ]); const threadListV2Layout = useMemo(() => { + threadListInboxReturns.observe(workingShelfEnabled ? threads : null); return buildThreadListV2Items({ pendingOrder, threads: threads.filter((thread) => thread.archivedAt === null), @@ -372,11 +383,16 @@ function ThreadNavigationSidebarPane( queuedThreadKeys, settledLimit: settledVisibleCount, now: new Date().toISOString(), + workingShelfEnabled, + workingShelfExpanded, + inboxReturnAt: threadListInboxReturns.returnedAt, snoozedShelfExpanded, settledShelfExpanded, selectedThreadKey: props.selectedThreadKey ?? null, }); }, [ + workingShelfEnabled, + workingShelfExpanded, pendingOrder, queuedThreadKeys, nowMinute, @@ -428,6 +444,9 @@ function ThreadNavigationSidebarPane( const items: SidebarListItem[] = buildThreadListV2ListItems({ items: threadListV2Layout.items, pendingTasks: v2PendingTasks, + workingCount: threadListV2Layout.workingCount, + workingShelfExpanded, + workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex, snoozedCount: threadListV2Layout.snoozedCount, snoozedShelfExpanded, snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex, @@ -461,6 +480,7 @@ function ThreadNavigationSidebarPane( snoozedShelfExpanded, snoozeEnvironmentIds, threadListV2Layout, + workingShelfExpanded, ]); const listMenuActions = useMemo( () => [ @@ -591,6 +611,8 @@ function ThreadNavigationSidebarPane( savedConnectionsById, listEnvironments, threadSearchMatchByKey, + // Rows read it for their reorder menu items. + workingShelfEnabled, }), [ props.selectedThreadKey, @@ -599,6 +621,7 @@ function ThreadNavigationSidebarPane( savedConnectionsById, listEnvironments, threadSearchMatchByKey, + workingShelfEnabled, ], ); useThreadJumpShortcuts(listItems, handleSelectThread); @@ -716,7 +739,7 @@ function ThreadNavigationSidebarPane( reorderSupported={ item.item.pinned ? pinReorderEnvironmentIds.has(thread.environmentId) - : activeReorderEnvironmentIds.has(thread.environmentId) + : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId) } canMoveUp={item.canMoveUp} canMoveDown={item.canMoveDown} @@ -733,6 +756,16 @@ function ThreadNavigationSidebarPane( /> ); } + case "v2-working-shelf": + return ( + + ); case "v2-snoozed-shelf": return ( ); } - if (props.status.kind === "waiting") { + if (props.status.kind === "background") { return ( + {/* A dev server can run for hours after the agent is done, so only work + that will wake the agent gets the bolt. */} { void tryOpenExternalUrl(link.url, "pull-request").then((opened) => { if (!opened) diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index e37f2da7c131..d8b0e8791b73 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -191,10 +191,12 @@ type ThreadListV2ShelfHeaderProps = { readonly pane?: "screen" | "sidebar"; }; +const SHELF_LABEL = { working: "Working", snoozed: "Snoozed", settled: "Settled" } as const; + function ThreadListV2ShelfHeader( - props: ThreadListV2ShelfHeaderProps & { readonly kind: "snoozed" | "settled" }, + props: ThreadListV2ShelfHeaderProps & { readonly kind: keyof typeof SHELF_LABEL }, ) { - const label = props.kind === "snoozed" ? "Snoozed" : "Settled"; + const label = SHELF_LABEL[props.kind]; return ( ; +}); + export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader( props: ThreadListV2ShelfHeaderProps, ) { diff --git a/apps/mobile/src/features/threads/thread-subagent-group.tsx b/apps/mobile/src/features/threads/thread-subagent-group.tsx index 0c51c6195b75..c0f1adf4736e 100644 --- a/apps/mobile/src/features/threads/thread-subagent-group.tsx +++ b/apps/mobile/src/features/threads/thread-subagent-group.tsx @@ -2,10 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { useIsFocused, useNavigation } from "@react-navigation/native"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { summarizeSubagentStatuses } from "@t3tools/client-runtime/state/subagent-display"; -import { - isActiveSubagentStatus, - isTerminalSubagentStatus, -} from "@t3tools/client-runtime/state/subagentRuntime"; +import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime"; import type { EnvironmentId, OrchestrationV2Subagent, @@ -21,9 +18,8 @@ import { cn } from "../../lib/cn"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; import { serverEnvironment } from "../../state/server"; import { environmentThreadDetails } from "../../state/threads"; -import { SubagentStatusDot } from "./SubagentStatusDot"; -import { subagentCardDetail, subagentCardElapsed } from "./subagent-card-presentation"; -import { resolveSubagentRowPresentation } from "./threadAgentsPresentation"; +import { subagentCardElapsed } from "./subagent-card-presentation"; +import { SubagentRow } from "./SubagentRow"; import { WorkLogBlock } from "./work-log-layout"; type SubagentItem = Extract; @@ -47,27 +43,20 @@ function SubagentElapsed({ agents }: { readonly agents: ReadonlyArray{elapsed} + {elapsed} ) : null; } function SubagentAvatar(props: { readonly item: SubagentItem; readonly iconUrl?: string | null | undefined; - readonly status?: OrchestrationV2Subagent["status"]; }) { return ( - {props.status ? ( - - ) : null} ); } @@ -99,6 +88,7 @@ export function ThreadSubagentGroup(props: { completedAt: live?.completedAt ?? item.completedAt, result: live?.result ?? item.result, progress: live?.progress ?? item.progress, + model: live?.model ?? null, }; }); const grouped = agents.length > 1; @@ -157,19 +147,12 @@ export function ThreadSubagentGroup(props: { {!grouped || expanded ? ( {agents.map((agent) => { - const presentation = resolveSubagentRowPresentation(agent); - const detail = subagentCardDetail( - isTerminalSubagentStatus(agent.status) - ? agent.result?.trim() || agent.progress || null - : agent.progress?.trim() || agent.result, - ); const threadId = agent.childThreadId; return ( - } /> - - - - {presentation.title} - - {detail && agent.status !== "completed" ? ( - - {presentation.statusLabel} - - ) : null} - - - {detail ?? presentation.statusLabel} - - - - {threadId !== null ? ( - - ) : null} ); })} diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 826b9205ac75..b9ca6d4eaa56 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1009,7 +1009,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow( entering={WORK_LOG_DETAIL_ENTER_TRANSITION} exiting={WORK_LOG_DETAIL_EXIT_TRANSITION} layout={WORK_LOG_LAYOUT_TRANSITION} - className={reasoning ? "ml-7 py-1" : "ml-7 border-l border-border pb-1 pl-3 pt-0.5"} + className={reasoning ? "ml-7 py-1" : "pb-1 pt-0.5"} > {row.workEntry.questionAnswer ? ( { expect(row.detail).toBeNull(); expect(row.statusLabel).toBe("Working"); }); + + it("bounds long result previews without dropping the agent's status", () => { + const row = resolveSubagentRowPresentation({ + ...base, + status: "failed", + result: "x".repeat(400), + }); + expect(row.detail).toBe(`${"x".repeat(280)}…`); + expect(row.statusLabel).toBe("Failed"); + }); }); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.ts index d1b85b896470..9605891143b4 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts @@ -1,8 +1,8 @@ -import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { - isActiveSubagentStatus, - isTerminalSubagentStatus, -} from "@t3tools/client-runtime/state/subagentRuntime"; + formatSubagentDisplayTitle, + subagentDetailPreview, +} from "@t3tools/client-runtime/state/subagent-display"; +import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime"; import type { OrchestrationV2Subagent } from "@t3tools/contracts"; const PROMPT_TITLE_LIMIT = 80; @@ -64,13 +64,9 @@ export function resolveSubagentRowPresentation( >, ): SubagentRowPresentation { const live = isActiveSubagentStatus(subagent.status); - const progress = subagent.progress?.trim() ?? ""; - const result = subagent.result?.trim() ?? ""; - const settled = isTerminalSubagentStatus(subagent.status); - const detail = settled ? result || progress : progress || result; return { title: rowTitle(subagent), - detail: detail.length > 0 ? detail.replace(/\s+/gu, " ") : null, + detail: subagentDetailPreview(subagent), statusLabel: rowStatusLabel(subagent.status), tone: rowTone(subagent.status), live, diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 166baa9d2e46..7459b17672f9 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1,3 +1,5 @@ +import { presentThreadShell } from "@t3tools/client-runtime/state/models"; +import * as DateTime from "effect/DateTime"; import { planPinnedMove } from "@t3tools/client-runtime/state/thread-sort"; import { createPendingThreadOrder, @@ -23,7 +25,7 @@ import { import { describe, expect, it, vi } from "vite-plus/test"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; -import { makeThreadShellFixture } from "../../test-fixtures"; +import { makeRawThreadShell, makeThreadShellFixture } from "../../test-fixtures"; import { threadJumpTarget } from "../keyboard/threadKeyboardShortcuts"; import { buildThreadListV2Items, @@ -36,6 +38,7 @@ import { resolveThreadListV2SwipeActions, sortThreadsForListV2, threadListV2ListItemsAreEqual, + threadHasUnseenCompletion, type ThreadListV2ListItem, } from "./threadListV2"; @@ -160,9 +163,7 @@ describe("resolveThreadListV2Status", () => { makeThread({ id: ThreadId.make("t"), title: "t", - pendingBackgroundTasks: [ - { taskId: "bg-1", description: "Run Codex review", kind: "command" }, - ], + pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }], runtime: { status: "idle", activeRunId: null, @@ -176,6 +177,28 @@ describe("resolveThreadListV2Status", () => { ).toBe("waiting"); }); + it.each([ + { kind: "command", status: "ready" }, + { kind: "monitor", status: "waiting" }, + ] as const)( + "presents an unseen completion with a $kind roster as $status", + ({ kind, status }) => { + const thread = presentThreadShell( + environmentId, + makeRawThreadShell({ + latestRunId: RunId.make("run-background-completion"), + status: "completed", + latestRunCompletedAt: DateTime.makeUnsafe(NOW), + lastVisitedAt: DateTime.makeUnsafe("2026-06-01T23:59:00.000Z"), + pendingBackgroundTasks: [{ taskId: "background-work", kind }], + }), + ); + + expect(resolveThreadListV2Status(thread)).toBe(status); + expect(threadHasUnseenCompletion(thread)).toBe(true); + }, + ); + it("resolves ready for quiescent threads", () => { expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe( "ready", @@ -2135,3 +2158,147 @@ describe("buildThreadListV2ListItems row-state stamps", () => { expect(threadListV2ListItemsAreEqual(shelfLoading, shelfLoaded)).toBe(false); }); }); + +describe("Working section beta", () => { + const running = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: NOW, + }; + const finishedAt = (id: string, completedAt: string) => + makeThread({ + id: ThreadId.make(id), + title: id, + createdAt: "2026-06-01T00:00:00.000Z", + latestRun: { + runId: RunId.make(`run-${id}`), + status: "completed", + requestedAt: "2026-06-01T00:00:00.000Z", + startedAt: "2026-06-01T00:00:00.000Z", + completedAt, + assistantMessageId: null, + }, + }); + const threads = [ + finishedAt("finished-early", "2026-06-01T01:00:00.000Z"), + finishedAt("finished-late", "2026-06-01T03:00:00.000Z"), + makeThread({ id: ThreadId.make("working"), title: "working", runtime: running }), + makeThread({ + id: ThreadId.make("asks-approval"), + title: "asks-approval", + createdAt: "2026-06-01T02:00:00.000Z", + runtime: running, + hasPendingApprovals: true, + }), + makeThread({ + id: ThreadId.make("pinned-working"), + title: "pinned-working", + runtime: running, + pinnedAt: "2026-06-01T00:00:00.000Z", + }), + ]; + const build = (input: Partial[0]> = {}) => + buildThreadListV2Items({ + threads, + environmentId: null, + searchQuery: "", + now: NOW, + workingShelfEnabled: true, + ...input, + }); + const ids = (layout: ReturnType) => + layout.items.map((item) => item.thread.id); + + it("folds unpinned working threads into a collapsed shelf", () => { + const layout = build(); + expect(ids(layout)).toEqual([ + "pinned-working", + "finished-late", + "asks-approval", + "finished-early", + ]); + expect(layout.workingCount).toBe(1); + expect(layout.workingShelfHeaderIndex).toBe(4); + + const off = build({ workingShelfEnabled: false }); + expect(ids(off)).toContain("working"); + expect(off.workingCount).toBe(0); + }); + + it("shows working rows as cards when expanded, or only the selected one when collapsed", () => { + expect(build({ workingShelfExpanded: true }).items.at(-1)).toMatchObject({ + thread: { id: "working" }, + variant: "card", + }); + expect(ids(build({ selectedThreadKey: `${environmentId}:working` })).at(-1)).toBe("working"); + }); + + it("orders the inbox by the latest return this device observed", () => { + const layout = build({ + inboxReturnAt: (thread) => + thread.id === "finished-early" ? Date.parse("2026-06-01T04:00:00.000Z") : undefined, + }); + expect(ids(layout).slice(1)).toEqual(["finished-early", "finished-late", "asks-approval"]); + }); + + it("places the shelf after queued tasks and before snoozed and settled threads", () => { + const layout = buildThreadListV2Items({ + threads: [ + makeThread({ id: ThreadId.make("active"), title: "active" }), + makeThread({ id: ThreadId.make("working"), title: "working", runtime: running }), + makeThread({ + id: ThreadId.make("snoozed"), + title: "snoozed", + runtime: running, + snoozedUntil: "2026-06-03T09:00:00.000Z", + snoozedAt: "2026-06-01T12:00:00.000Z", + }), + makeThread({ + id: ThreadId.make("settled"), + title: "settled", + settledOverride: "settled", + settledAt: NOW, + }), + ], + environmentId: null, + searchQuery: "", + now: NOW, + workingShelfEnabled: true, + workingShelfExpanded: true, + snoozedShelfExpanded: true, + }); + const items = buildThreadListV2ListItems({ + items: layout.items, + pendingTasks: [makePendingTask("queued")], + workingCount: layout.workingCount, + workingShelfExpanded: true, + workingShelfHeaderIndex: layout.workingShelfHeaderIndex, + snoozedCount: layout.snoozedCount, + snoozedShelfExpanded: true, + snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex, + settledCount: layout.settledCount, + settledShelfHeaderIndex: layout.settledShelfHeaderIndex, + }); + expect( + items.map((item) => + item.type === "v2-thread" + ? item.item.thread.id + : item.type === "v2-pending" + ? item.pendingTask.title + : item.type, + ), + ).toEqual([ + "active", + "queued", + "v2-working-shelf", + "working", + "v2-snoozed-shelf", + "snoozed", + "v2-settled-shelf", + "settled", + ]); + }); +}); diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index f0b2459301ae..f06f649793b1 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -11,6 +11,11 @@ import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled" import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { resolveThreadProviderStack } from "@t3tools/client-runtime/state/models"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { + createInboxReturnTracker, + isThreadWorking, + sortInboxThreadsByReturn, +} from "@t3tools/client-runtime/state/thread-inbox"; import { sortActiveThreadsByOrderKey, resolveSettledThreadTimestamp, @@ -33,6 +38,11 @@ import { export { snoozeWakeLabel }; +/** Working section beta: when this device saw each thread leave the Working + shelf. One instance for Home and the iPad sidebar, so both lists order the + inbox the same way and the order survives screens that unmount. */ +export const threadListInboxReturns = createInboxReturnTracker(); + /** * Provider drivers for a row's trailing icon stack, back to front. Instances * missing from the environment's config are skipped, and an unresolved @@ -62,7 +72,8 @@ export function resolveThreadListV2ProviderDrivers( * failures. Ready is the unlabeled resting state; waiting (runtime status "idle") is the agent * parked on open background tasks, grey like working rather than a false Done. * The orchestrator v2 presentation bridge parks runtime at idle when the - * post-settlement background roster is nonempty. + * post-settlement background roster holds the run's completion (subagents, + * monitors); commands left running, such as a dev server, read as ready. */ export type ThreadListV2Status = | "approval" @@ -268,6 +279,10 @@ export interface ThreadListV2Layout { readonly items: ThreadListV2Item[]; /** Settled threads beyond the render limit (behind "Show more"). */ readonly hiddenSettledCount: number; + /** Working threads folded away by the Working section beta. */ + readonly workingCount: number; + /** Index in `items` where the Working shelf header belongs. */ + readonly workingShelfHeaderIndex: number | null; /** Snoozed threads matching the current filters. */ readonly snoozedCount: number; /** Index in `items` where the Snoozed shelf header belongs. The header is @@ -324,6 +339,15 @@ export interface ThreadListV2PendingListItem { readonly showTrailingDivider: boolean; } +export interface ThreadListV2WorkingShelfListItem { + readonly type: "v2-working-shelf"; + readonly key: "v2-working-shelf"; + readonly count: number; + readonly expanded: boolean; + /** See the snoozed shelf header's field. */ + readonly disabled: boolean; +} + export interface ThreadListV2SnoozedShelfListItem { readonly type: "v2-snoozed-shelf"; readonly key: "v2-snoozed-shelf"; @@ -348,6 +372,7 @@ export interface ThreadListV2SettledShelfListItem { export type ThreadListV2ListItem = | ThreadListV2ThreadListItem | ThreadListV2PendingListItem + | ThreadListV2WorkingShelfListItem | ThreadListV2SnoozedShelfListItem | ThreadListV2SettledShelfListItem; @@ -359,6 +384,7 @@ export function isThreadListV2ListItem(value: { return ( value.type === "v2-thread" || value.type === "v2-pending" || + value.type === "v2-working-shelf" || value.type === "v2-snoozed-shelf" || value.type === "v2-settled-shelf" ); @@ -400,6 +426,13 @@ export function threadListV2ListItemsAreEqual( previous.showPendingDivider === item.showPendingDivider && previous.showTrailingDivider === item.showTrailingDivider ); + case "v2-working-shelf": + return ( + previous.type === "v2-working-shelf" && + previous.count === item.count && + previous.expanded === item.expanded && + previous.disabled === item.disabled + ); case "v2-snoozed-shelf": return ( previous.type === "v2-snoozed-shelf" && @@ -440,13 +473,17 @@ function resolveThreadListV2ItemTimeLabel( } /** - * Builds the shared mobile order: active → pending → snoozed shelf → settled. - * Pending tasks are waiting rather than asking, and parked work remains - * reachable without competing with either the inbox or settled history. + * Builds the shared mobile order: active → pending → working shelf (beta) → + * snoozed shelf → settled. Pending tasks are waiting rather than asking, and + * busy or parked work remains reachable without competing with either the + * inbox or settled history. */ export function buildThreadListV2ListItems(input: { readonly items: ReadonlyArray; readonly pendingTasks: ReadonlyArray; + readonly workingCount?: number; + readonly workingShelfExpanded?: boolean; + readonly workingShelfHeaderIndex?: number | null; readonly snoozedCount?: number; readonly snoozedShelfExpanded?: boolean; readonly snoozedShelfHeaderIndex?: number | null; @@ -513,14 +550,27 @@ export function buildThreadListV2ListItems(input: { showPendingDivider: index === 0, showTrailingDivider: false, })); + const workingCount = input.workingCount ?? 0; + const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null; const snoozedCount = input.snoozedCount ?? 0; const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null; const settledCount = input.settledCount ?? 0; const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null; - const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length; const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length; + const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd; + const activeEnd = workingShelfHeaderIndex ?? workingEnd; const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems]; const shelfDisabled = input.shelfPreferencesLoading === true; + if (workingShelfHeaderIndex !== null && workingCount > 0) { + result.push({ + type: "v2-working-shelf", + key: "v2-working-shelf", + count: workingCount, + expanded: input.workingShelfExpanded === true, + disabled: shelfDisabled, + }); + result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd)); + } if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) { result.push({ type: "v2-snoozed-shelf", @@ -579,6 +629,15 @@ export function buildThreadListV2Items(input: { readonly settledLimit?: number; /** Second-precise clock used for time-based classification. */ readonly now: string; + /** Working section beta: unpinned working threads fold into the Working + shelf, and the inbox orders by when each thread came back to the user + instead of the saved arrangement. */ + readonly workingShelfEnabled?: boolean; + /** Expands the Working shelf into rows. Collapsed is the default. */ + readonly workingShelfExpanded?: boolean; + /** Returns this device observed but the server does not stamp, such as an + approval request mid-turn. Only read while the beta is on. */ + readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined; /** Expands the snoozed shelf into rows. Collapsed is the default. */ readonly snoozedShelfExpanded?: boolean; /** Expands the settled shelf into rows. Expanded is the default. */ @@ -608,8 +667,10 @@ export function buildThreadListV2Items(input: { ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`)) : null; + const workingShelfEnabled = input.workingShelfEnabled === true; const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; + const working: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = []; const snoozed: EnvironmentThreadShell[] = []; let nextSnoozeWakeAt: string | null = null; @@ -655,17 +716,31 @@ export function buildThreadListV2Items(input: { settled.push(thread); } else if (thread.pinnedAt != null) { pinned.push(thread); + } else if (workingShelfEnabled && isThreadWorking(thread)) { + working.push(thread); } else { active.push(thread); } } - const orderedActive = applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending); + // The beta inbox is time-ordered, so the saved arrangement (and any move in + // flight) is kept but not applied until the beta is off again. + const orderedActive = workingShelfEnabled + ? sortInboxThreadsByReturn(active, input.inboxReturnAt) + : applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending); + // Newest work first, by the same clock as the inbox. + const orderedWorking = sortInboxThreadsByReturn(working); const orderedSnoozed = [...snoozed].sort( (left, right) => parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""), ); const selectedThreadKey = input.selectedThreadKey ?? null; + const visibleWorking = + input.workingShelfExpanded === true + ? orderedWorking + : orderedWorking.filter( + (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey, + ); const visibleSnoozed = input.snoozedShelfExpanded === true ? orderedSnoozed @@ -710,6 +785,16 @@ export function buildThreadListV2Items(input: { isLast: false, }); } + const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null; + for (const thread of visibleWorking) { + items.push({ + thread, + variant: "card", + snoozed: false, + pinned: false, + isLast: false, + }); + } const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null; for (const thread of visibleSnoozed) { items.push({ @@ -737,6 +822,8 @@ export function buildThreadListV2Items(input: { return { items, hiddenSettledCount: orderedSettled.length - pagedSettled.length, + workingCount: orderedWorking.length, + workingShelfHeaderIndex, snoozedCount: orderedSnoozed.length, snoozedShelfHeaderIndex, settledCount: orderedSettled.length, diff --git a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts index 8ffab4e045b4..b32d9ad40043 100644 --- a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts +++ b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts @@ -17,10 +17,16 @@ export function useThreadListV2ShelfPreferences() { loaded && preferencesResult.value.threadListSnoozedShelfExpanded === true; const settledShelfExpanded = loaded && preferencesResult.value.threadListSettledShelfExpanded === true; + // Working section beta: off until the preference loads and is enabled. + const workingShelfEnabled = loaded && preferencesResult.value.workingShelfEnabled === true; + const workingShelfExpanded = + loaded && preferencesResult.value.threadListWorkingShelfExpanded === true; const snoozedShelfExpandedRef = useRef(snoozedShelfExpanded); const settledShelfExpandedRef = useRef(settledShelfExpanded); + const workingShelfExpandedRef = useRef(workingShelfExpanded); snoozedShelfExpandedRef.current = snoozedShelfExpanded; settledShelfExpandedRef.current = settledShelfExpanded; + workingShelfExpandedRef.current = workingShelfExpanded; const toggleSnoozedShelf = useCallback(() => { if (!loaded) return; @@ -34,12 +40,21 @@ export function useThreadListV2ShelfPreferences() { settledShelfExpandedRef.current = expanded; savePreferences({ threadListSettledShelfExpanded: expanded }); }, [loaded, savePreferences]); + const toggleWorkingShelf = useCallback(() => { + if (!loaded) return; + const expanded = !workingShelfExpandedRef.current; + workingShelfExpandedRef.current = expanded; + savePreferences({ threadListWorkingShelfExpanded: expanded }); + }, [loaded, savePreferences]); return { loaded, settledShelfExpanded, snoozedShelfExpanded, + workingShelfEnabled, + workingShelfExpanded, toggleSettledShelf, toggleSnoozedShelf, + toggleWorkingShelf, } as const; } diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 5bb2713d6c8d..3022b9fe2208 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -42,7 +42,7 @@ import { UsageLimitsSection } from "./UsageLimitsPooled"; import { ControlPillMenu } from "../../components/ControlPill"; import { SymbolView } from "../../components/AppSymbol"; import type { UsageChartMetric } from "./usageChartData"; -import { PROVIDER_LABEL, useProviderColors } from "./usageProviders"; +import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders"; type UsageTab = "usage" | "limits"; const TAB_OPTIONS = [ @@ -360,6 +360,7 @@ export function UsageRouteScreen() { onCursorEnabled={refreshAfterCursorEnable} /> + )} @@ -688,6 +689,84 @@ function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24H ); } +function CostSection(props: { readonly merged: MergedUsage }) { + const { categoryCost, speedCost } = props.merged; + const colors = useUsageMixColors(); + const byType = [ + { label: "Input", value: categoryCost.input, color: colors.input }, + { label: "Cache read", value: categoryCost.cacheRead, color: colors.cacheRead }, + { label: "Cache write", value: categoryCost.cacheWrite, color: colors.cacheWrite }, + { label: "Output", value: categoryCost.output, color: colors.output }, + // Reported cost with no rates to split it, or from older servers. Below a + // cent it is rounding, not usage. + { + label: "Other", + value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0, + color: colors.other, + }, + ]; + const bySpeed = [ + { label: "Standard", value: speedCost.standard, color: colors.standard }, + { label: "Fast", value: speedCost.fast, color: colors.fast }, + { label: "Ultrafast", value: speedCost.ultrafast, color: colors.ultrafast }, + ]; + if (props.merged.costUsd <= 0) return null; + + return ( + + + {speedCost.fast + speedCost.ultrafast > 0 ? ( + + + + ) : null} + + ); +} + +/** One part-to-whole cost bar with its legend. Empty segments are left out. */ +function ShareBar(props: { + readonly label: string; + readonly segments: readonly { label: string; value: number; color: string }[]; + readonly aside?: string; +}) { + const visible = props.segments.filter((segment) => segment.value > 0); + if (visible.length === 0) return null; + + return ( + + + {props.label} + {props.aside ? ( + {props.aside} + ) : null} + + + {visible.map((segment) => ( + + ))} + + + {visible.map((segment) => ( + + + {segment.label} + {formatUsd(segment.value)} + + ))} + + + ); +} + function MetricCell(props: { readonly label: string; readonly value: string; diff --git a/apps/mobile/src/features/usage/usageProviders.ts b/apps/mobile/src/features/usage/usageProviders.ts index 45a94ddae1f7..5742cbca1043 100644 --- a/apps/mobile/src/features/usage/usageProviders.ts +++ b/apps/mobile/src/features/usage/usageProviders.ts @@ -38,3 +38,23 @@ export function useProviderColors(): Record { antigravity: "#8c7bd1", }; } + +/** + * Neutral steps for cost and token mixes, so they never borrow a provider's + * color. Matches the web steps: oklab mixes of the codex ink into the + * background, above the 15 ΔE separation floor for adjacent segments. + */ +export function useUsageMixColors() { + const { themeAppearance: scheme } = useAppearancePreferences(); + const dark = scheme === "dark"; + return { + input: dark ? "#737373" : "#848484", + cacheRead: dark ? "#282828" : "#c0c0c0", + cacheWrite: dark ? "#949494" : "#6d6d6d", + output: dark ? "#e6e6e6" : "#3c3c43", + other: dark ? "#494949" : "#a3a3a3", + standard: dark ? "#313131" : "#b8b8b8", + fast: dark ? "#838383" : "#797979", + ultrafast: dark ? "#e6e6e6" : "#3c3c43", + }; +} diff --git a/apps/mobile/src/lib/storage.test.ts b/apps/mobile/src/lib/storage.test.ts index 78a165c5ff1d..f56c3a7eff0e 100644 --- a/apps/mobile/src/lib/storage.test.ts +++ b/apps/mobile/src/lib/storage.test.ts @@ -232,24 +232,32 @@ describe("mobile connection storage", () => { expect(fallback.updatedAt).toEqual(expect.any(Number)); }); - it("persists thread list shelf expansion preferences", async () => { + it("persists thread list shelf preferences", async () => { await expect( savePreferencesPatch({ threadListSettledShelfExpanded: false, threadListSnoozedShelfExpanded: true, + threadListWorkingShelfExpanded: true, + workingShelfEnabled: true, }), ).resolves.toEqual({ threadListSettledShelfExpanded: false, threadListSnoozedShelfExpanded: true, + threadListWorkingShelfExpanded: true, + workingShelfEnabled: true, }); await expect(loadPreferences()).resolves.toEqual({ threadListSettledShelfExpanded: false, threadListSnoozedShelfExpanded: true, + threadListWorkingShelfExpanded: true, + workingShelfEnabled: true, }); expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ threadListSettledShelfExpanded: false, threadListSnoozedShelfExpanded: true, + threadListWorkingShelfExpanded: true, + workingShelfEnabled: true, }); }); diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 7868d53f9b93..ee96bce2d5ce 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -41,6 +41,8 @@ export interface Preferences { readonly projectGroupingMode?: SidebarProjectGroupingMode; /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */ readonly planModeEnabled?: boolean; + /** Device-local counterpart of web's `sidebarWorkingShelfEnabled` beta. */ + readonly workingShelfEnabled?: boolean; /** Model favorites belong to this device, like the web client setting. */ readonly modelFavorites?: ReadonlyArray<{ readonly provider: ProviderInstanceId; @@ -49,6 +51,7 @@ export interface Preferences { /** Fresh keys reset both shelves to collapsed when users update. */ readonly threadListSettledShelfExpanded?: boolean; readonly threadListSnoozedShelfExpanded?: boolean; + readonly threadListWorkingShelfExpanded?: boolean; } export class MobilePreferencesLoadError extends Schema.TaggedError()( @@ -107,9 +110,11 @@ function sanitizePreferences(parsed: Preferences): Preferences { projectGroupingEnabled?: boolean; projectGroupingMode?: SidebarProjectGroupingMode; planModeEnabled?: boolean; + workingShelfEnabled?: boolean; modelFavorites?: Preferences["modelFavorites"]; threadListSettledShelfExpanded?: boolean; threadListSnoozedShelfExpanded?: boolean; + threadListWorkingShelfExpanded?: boolean; } = {}; if (typeof parsed.liveActivitiesEnabled === "boolean") { @@ -180,6 +185,9 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (typeof parsed.planModeEnabled === "boolean") { preferences.planModeEnabled = parsed.planModeEnabled; } + if (typeof parsed.workingShelfEnabled === "boolean") { + preferences.workingShelfEnabled = parsed.workingShelfEnabled; + } if (Array.isArray(parsed.modelFavorites)) { preferences.modelFavorites = parsed.modelFavorites.filter( (favorite) => @@ -197,6 +205,9 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") { preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded; } + if (typeof parsed.threadListWorkingShelfExpanded === "boolean") { + preferences.threadListWorkingShelfExpanded = parsed.threadListWorkingShelfExpanded; + } return preferences; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 71a2c769ef4e..a596ca55c32a 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -713,6 +713,49 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(testLayer)), ); + it.effect("previews workspace files with literal fragment characters in their paths", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" }); + const directory = path.join(root, "assets#archive"); + yield* fileSystem.makeDirectory(directory); + + for (const name of ["icon#v2.png", "report#draft.pdf"]) { + const filePath = path.join(directory, name); + yield* fileSystem.writeFileString(filePath, "preview fixture"); + const canonicalFile = yield* fileSystem.realPath(filePath); + const result = yield* issueAssetUrl({ + resource: { + _tag: "workspace-file", + threadId: ThreadId.make("thread-1"), + path: filePath, + }, + workspaceRoot: root, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const token = suffix.slice(0, suffix.indexOf("/")); + + expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile }); + if (name.endsWith(".png")) { + expect(yield* resolveAsset(token, "other.png")).toBeNull(); + } + } + + const disguisedPath = path.join(root, "image.png#notes.txt"); + yield* fileSystem.writeFileString(disguisedPath, "not an image"); + const error = yield* issueAssetUrl({ + resource: { + _tag: "workspace-file", + threadId: ThreadId.make("thread-1"), + path: disguisedPath, + }, + workspaceRoot: root, + }).pipe(Effect.flip); + expect(error).toBeInstanceOf(AssetPreviewTypeValidationError); + }).pipe(Effect.provide(testLayer)), + ); + it.effect("issues exact attachment capabilities by attachment id", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/atomicWrite.test.ts b/apps/server/src/atomicWrite.test.ts new file mode 100644 index 000000000000..172c9703a304 --- /dev/null +++ b/apps/server/src/atomicWrite.test.ts @@ -0,0 +1,139 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +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 { writeFileStringAtomically } from "./atomicWrite.ts"; + +it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => { + it.effect("keeps a symlinked file linked and rewrites its destination", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const destination = path.join(root, "dotfiles", "settings.json"); + const link = path.join(root, "home", "settings.json"); + yield* fs.makeDirectory(path.dirname(destination), { recursive: true }); + yield* fs.makeDirectory(path.dirname(link), { recursive: true }); + yield* fs.writeFileString(destination, "before"); + yield* fs.symlink(destination, link); + + yield* writeFileStringAtomically({ filePath: link, contents: "after" }); + + assert.strictEqual(yield* fs.readLink(link), destination); + assert.strictEqual(yield* fs.readFileString(destination), "after"); + }), + ); + + it.effect("keeps a dangling symlink linked and creates its destination", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const destination = path.join(root, "dotfiles", "settings.json"); + const link = path.join(root, "home", "settings.json"); + yield* fs.makeDirectory(path.dirname(link), { recursive: true }); + yield* fs.symlink(destination, link); + + yield* writeFileStringAtomically({ filePath: link, contents: "fresh" }); + + assert.strictEqual(yield* fs.readLink(link), destination); + assert.strictEqual(yield* fs.readFileString(destination), "fresh"); + }), + ); + + it.effect("fails on a symlink cycle without replacing either link", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const first = path.join(root, "first.json"); + const second = path.join(root, "second.json"); + yield* fs.symlink(second, first); + yield* fs.symlink(first, second); + + const result = yield* Effect.exit( + writeFileStringAtomically({ filePath: first, contents: "after" }), + ); + + assert.isTrue(Exit.isFailure(result)); + assert.strictEqual(yield* fs.readLink(first), second); + assert.strictEqual(yield* fs.readLink(second), first); + }), + ); + + it.effect("resolves a relative link through a symlinked parent directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const destination = path.join(root, "dotfiles", "config", "settings.json"); + const linkedState = path.join(root, "dotfiles", "state"); + const home = path.join(root, "home"); + const link = path.join(home, "state", "settings.json"); + yield* fs.makeDirectory(path.dirname(destination), { recursive: true }); + yield* fs.makeDirectory(linkedState, { recursive: true }); + yield* fs.makeDirectory(home, { recursive: true }); + yield* fs.symlink(linkedState, path.join(home, "state")); + yield* fs.writeFileString(destination, "before"); + yield* fs.symlink("../config/settings.json", link); + + yield* writeFileStringAtomically({ filePath: link, contents: "after" }); + + assert.strictEqual(yield* fs.readLink(link), "../config/settings.json"); + assert.strictEqual(yield* fs.readFileString(destination), "after"); + }), + ); + + it.effect("creates a missing file and its directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "nested", "settings.json"); + + yield* writeFileStringAtomically({ filePath, contents: "fresh" }); + + assert.strictEqual(yield* fs.readFileString(filePath), "fresh"); + }), + ); +}); + +it.effect("surfaces an unreadable link instead of writing over it", () => + Effect.gen(function* () { + const readLinkFailure = PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "readLink", + pathOrDescriptor: "/home/settings.json", + }); + + const result = yield* Effect.exit( + writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }), + ); + + assert.deepStrictEqual(result, Exit.fail(readLinkFailure)); + }).pipe( + Effect.provide( + Layer.mergeAll( + Path.layer, + FileSystem.layerNoop({ + readLink: () => + Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "readLink", + pathOrDescriptor: "/home/settings.json", + }), + ), + rename: () => Effect.die("an unreadable link must not be replaced"), + }), + ), + ), + ), +); diff --git a/apps/server/src/atomicWrite.ts b/apps/server/src/atomicWrite.ts index fcd0345fc8d6..8a7fb20f2aea 100644 --- a/apps/server/src/atomicWrite.ts +++ b/apps/server/src/atomicWrite.ts @@ -1,7 +1,13 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; +/** + * Replaces a file's contents via a sibling temp file and rename. A symlinked + * target is resolved first so the link survives and its destination is + * rewritten, since renaming over the link itself would swap it for a regular file. + */ export const writeFileStringAtomically = (input: { readonly filePath: string; readonly contents: string; @@ -10,16 +16,17 @@ export const writeFileStringAtomically = (input: { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const targetDirectory = path.dirname(input.filePath); + const targetPath = yield* resolveSymlinkTarget(input.filePath); + const targetDirectory = path.dirname(targetPath); yield* fs.makeDirectory(targetDirectory, { recursive: true }); const tempDirectory = yield* fs.makeTempDirectoryScoped({ directory: targetDirectory, - prefix: `${path.basename(input.filePath)}.`, + prefix: `${path.basename(targetPath)}.`, }); const tempPath = path.join(tempDirectory, "contents.tmp"); yield* fs.writeFileString(tempPath, input.contents); - yield* fs.rename(tempPath, input.filePath); + yield* fs.rename(tempPath, targetPath); }), ); diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index d5b165865ab2..fc355f66a9eb 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -7,11 +7,15 @@ import { WsRpcGroup, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as RpcTest from "effect/unstable/rpc/RpcTest"; import { RPC_REQUIRED_SCOPES, requiredScopeForRpcMethod, requiredScopeForDeviceList, + rpcScopeAuthorizationLayer, } from "./RpcAuthorization.ts"; describe("RPC authorization scopes", () => { @@ -116,3 +120,39 @@ it("requires operate permission for tool updates even alongside a read-only chec ); expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope); }); + +describe("RPC scope middleware", () => { + const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const; + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + (tag): tag is Exclude => + !(tested as ReadonlyArray).includes(tag), + ), + ); + + it.effect("checks each RPC's declared scope before its handler runs", () => + Effect.gen(function* () { + const handled: Array = []; + const client = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.mergeAll( + group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})), + group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => + Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)), + ), + rpcScopeAuthorizationLayer([AuthOrchestrationReadScope]), + ), + ), + ); + + expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({}); + expect( + yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip), + ).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredScope: AuthOrchestrationOperateScope, + }); + expect(handled).toEqual([]); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index fb8fdedede88..970ba88050b9 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -9,9 +9,13 @@ import { AuthTerminalOperateScope, ORCHESTRATION_V2_WS_METHODS, type AuthEnvironmentScope, + EnvironmentAuthorizationError, + RpcScopeAuthorization, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import type * as RpcGroup from "effect/unstable/rpc/RpcGroup"; import { ENVIRONMENT_CONTROL_REQUIRED_SCOPES } from "./environmentControlScopes.ts"; @@ -215,6 +219,21 @@ export function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope return requiredScope; } +export const rpcAuthorizationError = (requiredScope: AuthEnvironmentScope) => + new EnvironmentAuthorizationError({ + message: `The authenticated token is missing required scope: ${requiredScope}.`, + requiredScope, + }); + +/** Authorizes every RPC on one connection against that connection's session scopes. */ +export const rpcScopeAuthorizationLayer = (scopes: ReadonlyArray) => + Layer.succeed(RpcScopeAuthorization)((effect, { rpc }) => { + const requiredScope = requiredScopeForRpcMethod(rpc._tag); + return scopes.includes(requiredScope) + ? effect + : Effect.fail(rpcAuthorizationError(requiredScope)); + }); + /** Retrying can install or restart tools even though ordinary listing is readable. */ export const requiredScopeForDeviceList = (input: DeviceListInput): AuthEnvironmentScope => input.retryHostId || input.updateTool diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 91ab19b55e01..16a4a93b3f20 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -233,6 +233,7 @@ export const make = Effect.gen(function* () { environmentThemes: true, usageLimitSources: true, usagePriceOverrides: true, + usageModelAliases: true, threadPinning: true, threadPinReorder: true, threadActiveReorder: true, @@ -240,6 +241,7 @@ export const make = Effect.gen(function* () { threadTitleRegeneration: true, threadVisitedTracking: true, threadPullRequests: true, + threadPullRequestWatch: true, pullRequestStackActions: true, threadPullRequestLinking: true, serverResolvedCommandContext: true, diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index fb256f25500a..202b5de45c5b 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -11,7 +11,7 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as ServerConfig from "./config.ts"; import * as Keybindings from "./keybindings.ts"; -import { KeybindingsConfigError } from "@t3tools/contracts"; +import { KeybindingsConfigError, MAX_KEYBINDINGS_COUNT } from "@t3tools/contracts"; import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); @@ -283,6 +283,76 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(makeKeybindingsLayer())), ); + it.effect("adds a late default to an existing command once", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const when = "composerFocus && draftThreadRoute"; + const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const; + const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => + rules.filter((entry) => entry.command === "composer.sendBackground"), + ); + yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + + yield* keybindings.syncDefaultKeybindingsOnStartup; + assert.deepStrictEqual(yield* backgroundRules, [ + existing, + { key: "mod+enter", command: "composer.sendBackground", when }, + ]); + + // Removing the added rule later must survive the next startup. + yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* keybindings.syncDefaultKeybindingsOnStartup; + assert.deepStrictEqual(yield* backgroundRules, [existing]); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("leaves a customized command without the late default", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const custom = { + key: "alt+b", + command: "composer.sendBackground", + when: "composerFocus && draftThreadRoute", + } as const; + yield* writeKeybindingsConfig(keybindingsConfigPath, [custom]); + + yield* keybindings.syncDefaultKeybindingsOnStartup; + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + assert.deepStrictEqual( + persisted.filter((entry) => entry.command === "composer.sendBackground"), + [custom], + ); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("keeps a late default pending while the config is full", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const when = "composerFocus && draftThreadRoute"; + const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const; + const fillers = Array.from({ length: MAX_KEYBINDINGS_COUNT - 1 }, (_, index) => ({ + key: "mod+alt+f1", + command: `script.filler-${index}.run` as const, + })); + const hasModEnter = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => + rules.some( + (entry) => entry.command === "composer.sendBackground" && entry.key === "mod+enter", + ), + ); + + yield* writeKeybindingsConfig(keybindingsConfigPath, [existing, ...fillers]); + yield* keybindings.syncDefaultKeybindingsOnStartup; + assert.isFalse(yield* hasModEnter); + + yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* keybindings.syncDefaultKeybindingsOnStartup; + assert.isTrue(yield* hasModEnter); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => { const messages: string[] = []; const logger = Logger.make(({ message }) => { diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 7a1bcd7f356a..0484296edd7e 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -104,6 +104,31 @@ function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): bool ); } +// Default rules added to a command after startup sync had already persisted +// that command. Backfill skips commands a config already has, so startup adds +// each rule once per config, only next to the untouched earlier default +// (`alongside`), and records its id. Customized commands and later removals +// stay as the user set them. +const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ + readonly id: string; + readonly alongside: KeybindingRule; + readonly rule: KeybindingRule; +}> = [ + { + id: "composer.sendBackground:mod+enter", + alongside: { + key: "mod+alt+enter", + command: "composer.sendBackground", + when: "composerFocus && draftThreadRoute", + }, + rule: { + key: "mod+enter", + command: "composer.sendBackground", + when: "composerFocus && draftThreadRoute", + }, + }, +]; + function keybindingShortcutContext(rule: KeybindingRule): string | null { const parsed = parseKeybindingShortcut(rule.key); if (!parsed) return null; @@ -399,6 +424,32 @@ const make = Effect.gen(function* () { return { keybindings, issues }; }); + // One applied migration id per line, next to the config file. + const appliedMigrationsPath = path.join( + path.dirname(keybindingsConfigPath), + "keybindings-migrations", + ); + const readAppliedMigrationIds = fs.readFileString(appliedMigrationsPath).pipe( + Effect.map((contents) => new Set(contents.split("\n").filter((line) => line.length > 0))), + Effect.orElseSucceed(() => new Set()), + ); + const recordAppliedMigrations = (ids: Iterable) => + writeFileStringAtomically({ + filePath: appliedMigrationsPath, + contents: `${[...new Set(ids)].join("\n")}\n`, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "failed to record keybinding migrations", + cause, + }), + ), + ); + const writeConfigAtomically = (rules: readonly KeybindingRule[]) => { return encodeKeybindingsConfigPrettyJson(rules).pipe( Effect.map((encoded) => `${encoded}\n`), @@ -450,9 +501,19 @@ const make = Effect.gen(function* () { const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)( Effect.gen(function* () { + const appliedMigrationIds = yield* readAppliedMigrationIds; + const pendingLateDefaults = LATE_DEFAULT_KEYBINDINGS.filter( + (late) => !appliedMigrationIds.has(late.id), + ); const configExists = yield* readConfigExists; if (!configExists) { yield* writeConfigAtomically(DEFAULT_KEYBINDINGS); + if (pendingLateDefaults.length > 0) { + yield* recordAppliedMigrations([ + ...appliedMigrationIds, + ...LATE_DEFAULT_KEYBINDINGS.map((late) => late.id), + ]); + } yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); return; } @@ -496,6 +557,16 @@ const make = Effect.gen(function* () { } missingDefaults.push(defaultRule); } + // The loop above backfills whole missing commands. Late defaults join + // an untouched earlier default, when their shortcut is still free. + for (const { alongside, rule } of pendingLateDefaults) { + if ( + customConfig.some((entry) => isSameKeybindingRule(entry, alongside)) && + !customConfig.some((entry) => hasSameShortcutContext(entry, rule)) + ) { + missingDefaults.push(rule); + } + } for (const conflict of shortcutConflictWarnings) { yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", { path: keybindingsConfigPath, @@ -506,21 +577,18 @@ const make = Effect.gen(function* () { reason: "shortcut context already used by existing rule", }); } - if (missingDefaults.length === 0) { - yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); - return; - } - - const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) => - customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)) - ? Result.succeed(defaultRule.command) - : Result.failVoid, - ); - if (matchingDefaults.length > 0) { - yield* Effect.logWarning("default keybinding rule already defined in user config", { - path: keybindingsConfigPath, - commands: matchingDefaults, - }); + if (missingDefaults.length > 0) { + const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) => + customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)) + ? Result.succeed(defaultRule.command) + : Result.failVoid, + ); + if (matchingDefaults.length > 0) { + yield* Effect.logWarning("default keybinding rule already defined in user config", { + path: keybindingsConfigPath, + commands: matchingDefaults, + }); + } } // Startup backfill must never evict persisted user rules: append only @@ -535,12 +603,19 @@ const make = Effect.gen(function* () { commands: skippedDefaults.map((rule) => rule.command), }); } - if (defaultsToAppend.length === 0) { - yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); - return; + if (defaultsToAppend.length > 0) { + yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]); + } + // A late default skipped at max entries stays pending for a later start. + const settledLateDefaults = pendingLateDefaults.filter( + (late) => !skippedDefaults.includes(late.rule), + ); + if (settledLateDefaults.length > 0) { + yield* recordAppliedMigrations([ + ...appliedMigrationIds, + ...settledLateDefaults.map((late) => late.id), + ]); } - - yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]); yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 3f927c283ef8..eae4ffa8c0b1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -11,10 +11,12 @@ import { type OrchestrationV2ThreadProjection, type ServerProvider, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts"; import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; @@ -52,7 +54,22 @@ describe("OrchestratorMcpService", () => { } as unknown as OrchestrationV2ThreadProjection; const childProjection = { thread: { id: childThreadId }, - runs: [{ id: childRunId, ordinal: 1, status: "completed" }], + runs: [ + { + id: childRunId, + ordinal: 1, + status: "completed", + startedAt: DateTime.makeUnsafe("2026-10-03T10:00:00Z"), + completedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), + }, + { + id: RunId.make("run:mcp-ack-continuation"), + ordinal: 2, + status: "failed", + startedAt: DateTime.makeUnsafe("2026-10-03T10:02:00Z"), + completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"), + }, + ], contextTransfers: [], messages: [], subagents: [], @@ -126,6 +143,8 @@ describe("OrchestratorMcpService", () => { const result = yield* service.taskStatus(scope, taskId); assert.equal(result.status, "completed"); assert.equal(result.summary, "terminal result"); + assert.equal(result.latestTerminalRunId, childRunId); + assert.equal(result.latestTerminalStatus, "completed"); const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); @@ -133,6 +152,87 @@ describe("OrchestratorMcpService", () => { }), ); + it.effect("reports a restart-cut child as working until its continuation settles", () => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:mcp-restart-parent"); + const childThreadId = ThreadId.make("thread:mcp-restart-child"); + const taskId = NodeId.make("node:mcp-restart-task"); + const dispatched = yield* Ref.make(0); + let awaitsRestart = true; + let readFails = true; + const parentProjection = { + thread: { id: parentThreadId }, + runs: [], + contextTransfers: [], + subagents: [ + { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + driver: "codex", + model: "gpt-5.6-terra", + status: "running", + result: null, + completionDelivery: { state: "pending" }, + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + const childProjection = { + thread: { id: childThreadId }, + runs: [{ id: RunId.make("run:mcp-restart-child"), ordinal: 1, status: "cancelled" }], + contextTransfers: [], + messages: [], + subagents: [], + providerThreads: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection; + const dependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), + delegatedTaskResultPending: () => + readFails + ? Effect.fail(new OrchestratorProjectionError({ threadId: childThreadId })) + : Effect.succeed(awaitsRestart), + dispatch: () => Ref.update(dispatched, (count) => count + 1).pipe(Effect.as({} as never)), + }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:mcp-restart"), + threadId: parentThreadId, + providerSessionId: "provider-session:mcp-restart", + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const failed = yield* service.taskStatus(scope, taskId).pipe(Effect.flip); + assert.equal(failed.code, "orchestration_error"); + assert.equal(yield* Ref.get(dispatched), 0); + readFails = false; + const held = yield* service.taskStatus(scope, taskId); + assert.equal(held.status, "running"); + assert.equal(held.workState, "working"); + assert.isNull(held.summary); + // Acknowledging the cut run would suppress the real result's wake. + assert.equal(yield* Ref.get(dispatched), 0); + awaitsRestart = false; + const settled = yield* service.taskStatus(scope, taskId); + assert.equal(settled.status, "cancelled"); + assert.equal(yield* Ref.get(dispatched), 1); + }).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies)))); + }), + ); + it.effect("does not dispose delivery when a nonterminal task has no active child run", () => Effect.gen(function* () { const parentThreadId = ThreadId.make("thread:mcp-cancel-parent"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5fdc7eb81c80..83a7a4cbfde6 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -52,6 +52,7 @@ import { type ServerProvider, ThreadId, } from "@t3tools/contracts"; +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; @@ -412,7 +413,10 @@ function latestTerminalResultRun( run.status !== "rolled_back" && (run.id === delegatedRun?.id || run.startedAt !== null), ) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + .reduce( + (latest, run) => (latest === undefined || runRanAfter(run, latest) ? run : latest), + undefined, + ); } function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is OrchestrationV2Run { @@ -1055,7 +1059,16 @@ const make = Effect.gen(function* () { messages: [...childControls.messages, ...resultRecords.messages], turnItems: resultRecords.turnItems, }; - const workState = task.result !== null ? "result_available" : progress.state; + // A restart cut the child's run and its continuation has not settled, or + // the child started working again after this read. + const heldForRestart = + task.result === null && + progress.state === "result_available" && + (yield* threadManagement + .delegatedTaskResultPending(task.childThreadId) + .pipe(Effect.mapError(threadManagementFailure))); + const workState = + task.result !== null ? "result_available" : heldForRestart ? "working" : progress.state; const status = task.result !== null ? taskStatusForRun( @@ -1510,6 +1523,8 @@ const make = Effect.gen(function* () { ), ), ); + // Published task results stay terminal. Later child-thread messages do not + // reopen the task, so cancelling it must not interrupt those separate runs. if (isTerminalTaskStatus(current.status)) { yield* disposeCompletionDelivery; return { diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 7d20bf512b10..142e0cc55f12 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -1651,6 +1651,14 @@ describe("orchestrator MCP toolkit", () => { taskId: delegated.taskId, status: "completed", }); + expect( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === delegated.taskId, + ), + ).toMatchObject({ + result: delegatedResult, + completionDelivery: { state: "disposed" }, + }); expect( (yield* orchestrator.getThreadProjection(delegated.childThreadId)).runs.find( (run) => run.id === activeChildFollowup.runId, diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 7a8ed739d734..adf55cad5e91 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { + AuthOrchestrationOperateScope, EnvironmentId, PreviewAutomationClientDisconnectedError, PreviewAutomationInvalidSelectorError, @@ -17,6 +18,7 @@ import { type PreviewAutomationStreamEvent, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; @@ -27,6 +29,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as RpcGroup from "effect/unstable/rpc/RpcGroup"; import * as RpcTest from "effect/unstable/rpc/RpcTest"; +import { rpcScopeAuthorizationLayer } from "../auth/RpcAuthorization.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer)); @@ -1255,9 +1258,12 @@ it.effect("evicts an unanswered host and lets later calls use a healthy runtime" ); const client = yield* RpcTest.makeClient(group).pipe( Effect.provide( - group.toLayer({ - [WS_METHODS.previewAutomationConnect]: (host) => Stream.unwrap(broker.connect(host)), - }), + Layer.merge( + group.toLayer({ + [WS_METHODS.previewAutomationConnect]: (host) => Stream.unwrap(broker.connect(host)), + }), + rpcScopeAuthorizationLayer([AuthOrchestrationOperateScope]), + ), ), ); const events = client[WS_METHODS.previewAutomationConnect](makeHost()); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts index de85b6f72e0c..572cdcbf43e9 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts @@ -4,6 +4,7 @@ import { Tool } from "effect/unstable/ai"; import { CreateThreadsTool, DelegateTaskTool, + OrchestratorToolkit, ScheduleTaskTool, ThreadUpdateTool, } from "./tools.ts"; @@ -17,6 +18,16 @@ describe("orchestrator MCP tool guidance", () => { assert.include(DelegateTaskTool.description ?? "", "waitTimedOut"); assert.include(DelegateTaskTool.description ?? "", "does not cancel the child"); assert.include(DelegateTaskTool.description ?? "", "keep that taskId"); + assert.include(DelegateTaskTool.description ?? "", "call delegate_task again"); + assert.include(DelegateTaskTool.description ?? "", "childThreadId is backing storage"); + assert.include( + OrchestratorToolkit.tools.t3_thread_send.description ?? "", + "Do not use a delegated task's childThreadId to start another review round", + ); + assert.include( + OrchestratorToolkit.tools.task_cancel.description ?? "", + "without interrupting later child-thread runs", + ); }); it("documents wait timeout as a parent budget, not a child failure", () => { diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 833e88bd2ae8..a86f1ce214c5 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -57,7 +57,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { export const DelegateTaskTool = Tool.make("delegate_task", { description: - "Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. The childThreadId is backing storage, not an ordinary top-level thread. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", + "Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", parameters: OrchestratorMcpDelegateTaskInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, @@ -70,7 +70,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", { const TaskStatusTool = Tool.make("task_status", { description: - "Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns; latestTerminal* provides later non-monitor turn results. Reading a terminal result acknowledges its automatic parent delivery.", + "Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task or extend task_cancel to those turns. latestTerminal* provides later non-monitor turn results. Reading a terminal result acknowledges its automatic parent delivery.", parameters: OrchestratorMcpTaskStatusInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, @@ -84,7 +84,7 @@ const TaskStatusTool = Tool.make("task_status", { const TaskCancelTool = Tool.make("task_cancel", { description: - "Request interruption of an active T3-owned delegated task and dispose its automatic parent delivery. Completed task results remain available.", + "Request interruption of an active T3-owned delegated task and dispose its automatic parent delivery. For a terminal task, return its existing status and dispose delivery without interrupting later child-thread runs, even when task_status reports hasPendingChildRuns=true. Published task results remain available. Use t3_thread_interrupt for a later active run.", parameters: OrchestratorMcpTaskCancelInput, success: OrchestratorMcpTaskCancelResult, failure: OrchestratorMcpFailure, @@ -200,7 +200,7 @@ export const ThreadUpdateTool = Tool.make("t3_thread_update", { const ThreadSendTool = Tool.make("t3_thread_send", { description: - "Send a message to a T3 thread in the calling project. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.", + "Send a message to a T3 thread in the calling project. Do not use a delegated task's childThreadId to start another review round here; use delegate_task with the full review context and a new clientRequestId for that round. Thread messages do not create a new delegated task or reopen a completed task. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.", parameters: OrchestratorMcpThreadSendInput, success: OrchestratorMcpThreadSendResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index dab6e7176498..e329ade90d9e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -222,6 +222,58 @@ describe("pull request toolkit handlers", () => { }), ); + it.effect("watching an unlinked pull request links it first", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const result = yield* harness.call("watch_pull_request", { + url: "https://github.com/t3tools/t3code/pull/9", + }); + // The harness thread never changes, so the result reports what it still holds. + expect(result).toMatchObject({ number: 9, watching: false, wasWatching: false }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { + type: "thread.pull-request.watch", + number: 9, + watching: true, + link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" }, + }, + ]); + }), + ); + + it.effect("refuses to watch a merged pull request and stops an existing watch", () => + Effect.gen(function* () { + const watch = { + startedAt: "2026-08-20T00:00:00.000Z", + headSha: null, + failedChecks: [], + passed: false, + remarksThrough: "2026-08-20T00:00:00.000Z", + remarkIds: [], + conflicting: false, + wakes: 0, + }; + const merged = makeLink(1, { headBranch: "done" }); + const harness = yield* makeHarness({ + thread: makeThread([ + { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } }, + makeLink(2, { headBranch: "idle" }), + makeLink(3, { headBranch: "watched", watch }), + ]), + }); + const error = yield* harness + .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 }) + .pipe(Effect.flip); + expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" }); + expect( + yield* harness.call("unwatch_pull_request", { repository: "t3tools/t3code", number: 3 }), + ).toMatchObject({ wasWatching: true }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.watch", number: 3, watching: false }, + ]); + }), + ); + it.effect("links by repository and number, defaulting the host to the project's", () => Effect.gen(function* () { const harness = yield* makeHarness(); @@ -396,6 +448,7 @@ describe("pull request toolkit handlers", () => { number: 3, url: "https://github.com/t3tools/t3code/pull/3", source: "agent", + watching: false, state: "open", title: "PR 3", headBranch: "feat-c", diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 19677e1bd212..97af65e1a7bc 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -34,7 +34,9 @@ import { PullRequestHostRequiredError, PullRequestUnlinkFailedError, PullRequestListFailedError, + PullRequestNotOpenError, type PullRequestTargetInput, + PullRequestWatchFailedError, PullRequestThreadNotFoundError, PullRequestsToolkit, type ThreadPullRequestEntry, @@ -122,6 +124,7 @@ function entryOf( number: link.number, url: link.url, source: link.source, + watching: link.watch !== undefined, state: link.snapshot?.state ?? null, title: link.snapshot?.title ?? null, headBranch: link.snapshot?.headBranch ?? null, @@ -163,7 +166,8 @@ const make = Effect.gen(function* () { Failure: | typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError - | typeof PullRequestListFailedError, + | typeof PullRequestListFailedError + | typeof PullRequestWatchFailedError, ) { const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); const thread = yield* engine @@ -178,7 +182,10 @@ const make = Effect.gen(function* () { const projectOf = ( thread: OrchestrationV2ThreadShell, - Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError, + Failure: + | typeof PullRequestLinkFailedError + | typeof PullRequestUnlinkFailedError + | typeof PullRequestWatchFailedError, ) => projects.getShell(thread.projectId).pipe( Effect.map(Option.getOrUndefined), @@ -186,14 +193,65 @@ const make = Effect.gen(function* () { ); const dispatchFailure = - (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) => + ( + Failure: + | typeof PullRequestLinkFailedError + | typeof PullRequestUnlinkFailedError + | typeof PullRequestWatchFailedError, + ) => ( cause: Cause.Cause, - ): Effect.Effect => + ): Effect.Effect< + never, + PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError + > => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause as Cause.Cause) : Effect.fail(new Failure({ cause })); + /** + * Starts or stops a watch. One command links an unlinked pull request and watches it, and the + * result reports the state the thread holds afterwards. + */ + const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* ( + input: PullRequestTargetInput, + watching: boolean, + ) { + const thread = yield* requireThread(PullRequestWatchFailedError); + const project = yield* projectOf(thread, PullRequestWatchFailedError); + const target = yield* resolveTarget(input, project); + const watchedLink = (shell: OrchestrationV2ThreadShell) => + threadPullRequestsOf(shell).find( + (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target), + ); + const before = watchedLink(thread); + const state = before?.snapshot?.state; + if (watching && state !== undefined && state !== "open") { + return yield* new PullRequestNotOpenError({ state }); + } + yield* engine + .dispatch({ + type: "thread.pull-request.watch", + commandId: yield* commandId("mcp-pr-watch", thread.id), + threadId: thread.id, + host: target.host, + repository: target.repository, + number: target.number, + watching, + ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}), + }) + .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError))); + const after = yield* requireThread(PullRequestWatchFailedError); + return { + host: target.host, + repository: target.repository, + number: target.number, + url: target.url, + watching: watchedLink(after)?.watch !== undefined, + wasWatching: before?.watch !== undefined, + }; + }); + return PullRequestsToolkit.of({ link_pull_request: (input) => Effect.gen(function* () { @@ -260,6 +318,8 @@ const make = Effect.gen(function* () { }), list_thread_pull_requests: () => requireThread(PullRequestListFailedError).pipe(Effect.map(listThreadPullRequests)), + watch_pull_request: (input) => setWatching(input, true), + unwatch_pull_request: (input) => setWatching(input, false), }); }); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 90f22cea2615..52ac473a3d50 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -108,6 +108,24 @@ export class PullRequestUnlinkFailedError extends Schema.TaggedError()( + "PullRequestWatchFailedError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not change whether the pull request is watched."; + } +} + +export class PullRequestNotOpenError extends Schema.TaggedError()( + "PullRequestNotOpenError", + { state: Schema.String }, +) { + override get message(): string { + return `The pull request is ${this.state}, so there is nothing to watch.`; + } +} + export class PullRequestListFailedError extends Schema.TaggedError()( "PullRequestListFailedError", { cause: Schema.Defect() }, @@ -126,6 +144,8 @@ export const PullRequestToolError = Schema.Union([ PullRequestLinkFailedError, PullRequestUnlinkFailedError, PullRequestListFailedError, + PullRequestWatchFailedError, + PullRequestNotOpenError, ]); export type PullRequestToolError = typeof PullRequestToolError.Type; @@ -154,9 +174,21 @@ export const UnlinkPullRequestResult = Schema.Struct({ }); export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type; +export const WatchPullRequestResult = Schema.Struct({ + ...PullRequestIdentity, + watching: Schema.Boolean.annotate({ + description: "Whether T3 Code now watches the pull request for this thread.", + }), + wasWatching: Schema.Boolean.annotate({ + description: "Whether it was already watched before the call.", + }), +}); +export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, + watching: Schema.Boolean, state: Schema.NullOr(PullRequestState), title: Schema.NullOr(Schema.String), headBranch: Schema.NullOr(Schema.String), @@ -224,8 +256,38 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false); +const WatchPullRequestTool = Tool.make("watch_pull_request", { + description: + "Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every minute and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. Watching ends when the pull request merges or closes, when T3 Code cannot read it for 15 minutes, or when you call unwatch_pull_request.", + parameters: PullRequestTargetInput, + success: WatchPullRequestResult, + failure: PullRequestToolError, + dependencies, +}) + .annotate(Tool.Title, "Watch pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false); + +const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", { + description: + "Stop T3 Code from watching a pull request for this thread. The pull request stays linked. Pass the URL, or repository plus number.", + parameters: PullRequestTargetInput, + success: WatchPullRequestResult, + failure: PullRequestToolError, + dependencies, +}) + .annotate(Tool.Title, "Stop watching pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false); + export const PullRequestsToolkit = Toolkit.make( LinkPullRequestTool, UnlinkPullRequestTool, ListThreadPullRequestsTool, + WatchPullRequestTool, + UnwatchPullRequestTool, ); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 146924586763..b6cb0be45acf 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4925,9 +4925,13 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -4950,7 +4954,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, }), }, fileSystem, @@ -4986,28 +4989,13 @@ describe("AcpAdapterV2", () => { makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); // The still-running subagent defers finalize after session/prompt returns. - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId }); let terminalStatus: string | null = null; while (terminalStatus === null) { @@ -5033,10 +5021,14 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -5072,7 +5064,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, }), }, fileSystem, @@ -5107,28 +5098,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let subagentTurnItemId: string | null = null; let firstTerminalStatus: string | null = null; @@ -5193,10 +5169,14 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -5230,7 +5210,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, }), }, fileSystem, @@ -5272,28 +5251,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -5352,7 +5316,6 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const secondPromptWireReturned = yield* Deferred.make(); const releaseSecondPromptCompletion = yield* Deferred.make(); const instanceId = ProviderInstanceId.make("acp-test"); @@ -5361,7 +5324,12 @@ describe("AcpAdapterV2", () => { let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -5395,7 +5363,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -5456,28 +5423,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -5601,7 +5553,6 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const baseClock = yield* Clock.Clock; const finalizationClockRead = yield* Deferred.make(); const releaseFinalizationClockRead = yield* Deferred.make(); @@ -5629,7 +5580,12 @@ describe("AcpAdapterV2", () => { let sessionUpdateHandler: | Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -5668,7 +5624,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -5719,18 +5674,7 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); yield* TestClock.adjust("1 second"); assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); @@ -6451,14 +6395,18 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH"; const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -6492,7 +6440,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -6548,28 +6495,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -6752,14 +6684,18 @@ describe("AcpAdapterV2", () => { new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); const continuationRequests: Array = []; - const protocolEvents = yield* Queue.bounded(256); const promptWireReturned = yield* Deferred.make(); const releasePromptCompletion = yield* Deferred.make(); const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -6795,7 +6731,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -6875,18 +6810,13 @@ describe("AcpAdapterV2", () => { }, }); yield* Deferred.succeed(releasePromptCompletion, undefined); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -7223,7 +7153,6 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; const instanceId = ProviderInstanceId.make("acp-test"); const childSessionId = "mock-child-session-pending-continuation"; @@ -7231,7 +7160,12 @@ describe("AcpAdapterV2", () => { let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -7265,7 +7199,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -7321,28 +7254,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -7506,14 +7424,18 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; const instanceId = ProviderInstanceId.make("acp-test"); const childSessionId = "mock-child-session-root-then-child"; let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -7547,7 +7469,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => @@ -7603,28 +7524,13 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { @@ -7760,12 +7666,16 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; let cancelCalled = false; let runtimeOrdinalSeen = 0; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -7812,7 +7722,6 @@ describe("AcpAdapterV2", () => { runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; }, - protocolEvents, wrapCancel: (cancel) => Effect.sync(() => { cancelCalled = true; @@ -7853,28 +7762,13 @@ describe("AcpAdapterV2", () => { ); // The still-running subagent defers finalize after session/prompt returns, // so the interrupt below hits a settled turn held open for background work. - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); assert.isFalse( cancelCalled, "settled soft steer must not send session/cancel (the real Grok CLI kills background subagents on cancel)", @@ -13725,10 +13619,14 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; + const promptSettled = yield* Deferred.make(); const adapter = makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, crypto: yield* Crypto.Crypto, instanceId, flavor: { @@ -13762,7 +13660,6 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, }), }, fileSystem, @@ -13799,32 +13696,17 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + yield* Deferred.await(promptSettled); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: firstProviderTurnId, + requestRuntimeRestart: true, + }); let subagentStatus: string | null = null; let firstTerminalStatus: string | null = null; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e5839c824219..b837575c1faf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -947,6 +947,7 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => { messages: Stream.never, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -1097,6 +1098,7 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio messages: Stream.never, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -1187,6 +1189,7 @@ describe("ClaudeAdapterV2 resume compaction", () => { messages: Stream.never, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -1406,6 +1409,7 @@ describe("ClaudeAdapterV2 attachments", () => { offeredMessages.push(message); }), setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }), @@ -1544,6 +1548,7 @@ describe("ClaudeAdapterV2 attachments", () => { messages: Stream.never, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -1632,6 +1637,7 @@ describe("ClaudeAdapterV2 native fork", () => { messages: Stream.empty, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -1803,6 +1809,7 @@ describe("ClaudeAdapterV2 native session identity", () => { messages: Stream.empty, offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Effect.void, }; @@ -2058,6 +2065,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* Deferred.await(processed); }); const offeredMessages: Array = []; + const permissionModeChanges: Array = []; const continuationRequests: Array = []; const terminalReceipts = yield* Queue.unbounded>(); @@ -2106,6 +2114,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { offeredMessages.push(message); }), setModel: () => Effect.void, + setPermissionMode: (mode) => + Effect.sync(() => { + permissionModeChanges.push(mode); + }), interrupt: options?.interrupt ?? Effect.void, close: options?.close?.(sdkMessages) ?? Effect.void, }; @@ -2158,6 +2170,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { sdkMessages, offerAndWait, offeredMessages, + permissionModeChanges, continuationRequests, events, terminalReceipts, @@ -2985,6 +2998,18 @@ describe("ClaudeAdapterV2 background wake turns", () => { harness.sdkMessages, toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]), ); + // Claude entered plan mode on its own (EnterPlanMode). + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "plan", + uuid: "00000000-0000-4000-8000-000000000508", + session_id: WAKE_NATIVE_SESSION, + }), + ); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -3095,6 +3120,9 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan"); assert.equal(proposedPlan?.status, "active"); + // The second prompt reuses the live process, which is still in the + // plan mode Claude entered, so it is put back in the thread's mode. + assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))), ), ); @@ -3615,6 +3643,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, // The first CLI process keeps streaming until the test ends // it, so Stop stays parked waiting for it to exit. @@ -3864,6 +3893,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(queue), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(queue), }; @@ -6655,6 +6685,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, // End this process stream so openQuery can replace it. close: Queue.shutdown(sdkMessages), @@ -6837,6 +6868,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), }; @@ -7071,6 +7103,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), }; @@ -7257,6 +7290,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), }; @@ -7433,6 +7467,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), }; @@ -7564,6 +7599,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messages: Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, + setPermissionMode: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), }; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index ca133173a9eb..39b0d44ba9ed 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -184,6 +184,11 @@ interface ClaudeQuerySetModelFrame { readonly model: string; } +interface ClaudeQuerySetPermissionModeFrame { + readonly type: "query.set_permission_mode"; + readonly mode: string; +} + interface ClaudeQueryInterruptFrame { readonly type: "query.interrupt"; } @@ -239,6 +244,7 @@ type ClaudeOutboundFrame = | ClaudeQueryOpenFrame | ClaudePromptOfferFrame | ClaudeQuerySetModelFrame + | ClaudeQuerySetPermissionModeFrame | ClaudeQueryInterruptFrame | ClaudePermissionResponseFrame | ClaudeSessionForkFrame @@ -811,6 +817,13 @@ function makeReplayQueryRunner( model, }); }), + setPermissionMode: (mode) => + replayEffect(() => { + assertNextOutboundFrame({ + type: "query.set_permission_mode", + mode, + }); + }), interrupt: replayEffect(() => { assertNextOutboundFrame({ type: "query.interrupt" }); }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1aa14ae6fdd6..0aca36abe77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -327,6 +327,9 @@ export interface ClaudeAgentSdkQuerySession { readonly messages: Stream.Stream; readonly offer: (message: SDKUserMessage) => Effect.Effect; readonly setModel: (model: string) => Effect.Effect; + readonly setPermissionMode: ( + mode: PermissionMode, + ) => Effect.Effect; readonly interrupt: Effect.Effect; readonly close: Effect.Effect; } @@ -466,6 +469,14 @@ export type ClaudeAgentSdkProtocolLogEvent = readonly model: string; }; } + | { + readonly direction: "outgoing"; + readonly stage: "decoded"; + readonly payload: { + readonly type: "query.set_permission_mode"; + readonly mode: PermissionMode; + }; + } | { readonly direction: "outgoing"; readonly stage: "decoded"; @@ -670,6 +681,22 @@ export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer< }), ), ), + setPermissionMode: (mode) => + Effect.tryPromise({ + try: () => queryRuntime.setPermissionMode(mode), + catch: (cause) => queryRunnerError(cause, "setPermissionMode"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.set_permission_mode", + mode, + }, + }), + ), + ), interrupt: Effect.tryPromise({ try: () => queryRuntime.interrupt(), catch: (cause) => queryRunnerError(cause, "interrupt"), @@ -2688,6 +2715,11 @@ interface ClaudeLiveQueryContext { // uuid before any echo, so it echoes, but a resume's own turns can still // run ahead of that prompt. promptEchoMode: "unknown" | "acknowledged" | "early" | "result_only"; + // The mode this process was opened in, and the mode the CLI last reported + // (init and status frames). Claude changes the latter itself through + // EnterPlanMode. + readonly openedPermissionMode: PermissionMode; + permissionMode: PermissionMode; // Stop, rollback or fork is closing this process; its work is ending. stopping: boolean; // Registry entries still running when this process opened. Their process @@ -3673,7 +3705,7 @@ export function makeClaudeAdapterV2( readonly output: ClaudeNativeToolOutput; readonly status: Extract< OrchestrationV2TurnItem["status"], - "running" | "completed" | "failed" + "running" | "completed" | "failed" | "interrupted" | "cancelled" >; readonly startedAt: DateTime.Utc; readonly updatedAt: DateTime.Utc; @@ -4740,7 +4772,9 @@ export function makeClaudeAdapterV2( parentNodeId: toolCall.parentNodeId, ordinal: toolCall.ordinal, output: NO_CLAUDE_NATIVE_TOOL_OUTPUT, - status: "failed", + // A stopped turn cuts its open tools short; only a turn that + // ended on its own leaves them failed. + status: input.status === "completed" ? "failed" : input.status, startedAt: toolCall.startedAt, updatedAt: input.completedAt, presentation: toolCall.presentation, @@ -6841,10 +6875,23 @@ export function makeClaudeAdapterV2( if ( existing !== null && existing.nativeThreadId === nativeThreadId && - (isClaudeProviderContinuationTurn(turnInput) || - (existing.queryPolicyKey === queryPolicyKey && - existing.selectionKey === compiledSelection.queryIdentity)) + isClaudeProviderContinuationTurn(turnInput) + ) { + return existing; + } + if ( + existing !== null && + existing.nativeThreadId === nativeThreadId && + existing.queryPolicyKey === queryPolicyKey && + existing.selectionKey === compiledSelection.queryIdentity ) { + // Claude can switch its own mode mid-session (EnterPlanMode), and + // a denied ExitPlanMode leaves it there. Put the live process back + // in the thread's mode before the next prompt. + if (existing.permissionMode !== existing.openedPermissionMode) { + yield* existing.query.setPermissionMode(existing.openedPermissionMode); + existing.permissionMode = existing.openedPermissionMode; + } return existing; } @@ -6887,31 +6934,32 @@ export function makeClaudeAdapterV2( const hasPersistedProviderTurn = turnInput.providerTurnOrdinal > 1; const shouldResume = resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn; + const queryOptions = makeClaudeQueryOptions({ + modelSelection: turnInput.modelSelection, + nativeThreadId, + resume: shouldResume, + ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), + cwd: turnInput.runtimePolicy.cwd, + attachmentsDir, + settings: adapterOptions.settings, + environment: adapterOptions.environment, + tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS, + ...mcpOverrides, + permissionMode: queryPolicy.permissionMode, + ...(queryPolicy.allowDangerouslySkipPermissions === undefined + ? {} + : { + allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions, + }), + canUseTool, + onUserDialog, + supportedDialogKinds: ["resume_return"], + }); const querySession = yield* queryRunner .open({ threadId: turnInput.threadId, providerSessionId: input.providerSessionId, - options: makeClaudeQueryOptions({ - modelSelection: turnInput.modelSelection, - nativeThreadId, - resume: shouldResume, - ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), - cwd: turnInput.runtimePolicy.cwd, - attachmentsDir, - settings: adapterOptions.settings, - environment: adapterOptions.environment, - tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS, - ...mcpOverrides, - permissionMode: queryPolicy.permissionMode, - ...(queryPolicy.allowDangerouslySkipPermissions === undefined - ? {} - : { - allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions, - }), - canUseTool, - onUserDialog, - supportedDialogKinds: ["resume_return"], - }), + options: queryOptions, }) .pipe( Effect.tapError(() => @@ -6958,6 +7006,8 @@ export function makeClaudeAdapterV2( selectionKey: compiledSelection.queryIdentity, closed, promptEchoMode: "unknown", + openedPermissionMode: queryOptions.permissionMode, + permissionMode: queryOptions.permissionMode, stopping: false, subagentsFromEarlierProcesses: new Set( [...(yield* Ref.get(sessionSubagentsByTaskId)).values()].filter( @@ -6967,7 +7017,16 @@ export function makeClaudeAdapterV2( }; yield* Ref.set(queryContext, context); yield* querySession.messages.pipe( - Stream.runForEach((message) => handleSdkMessage({ query: querySession, message })), + Stream.runForEach((message) => { + if ( + message.type === "system" && + (message.subtype === "init" || message.subtype === "status") && + message.permissionMode !== undefined + ) { + context.permissionMode = message.permissionMode; + } + return handleSdkMessage({ query: querySession, message }); + }), Effect.exit, Effect.flatMap( Effect.fnUntraced(function* (exit: ClaudeQueryStreamExit) { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3145e33dabd1..85748fa056e7 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2597,6 +2597,161 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each( + ( + [ + ["recovers archived-session errors", "session saved-thread is archived", 0, ""], + [ + "recovers unarchive hints", + "Run `codex unarchive saved-thread` to unarchive it first.", + 0, + "", + ], + ["preserves missing-thread errors", "thread not found", 3, "thread not found"], + ["preserves missing-rollout errors", "no rollout found", 3, "no rollout found"], + ["preserves authentication errors", "authentication failed", 3, "authentication failed"], + [ + "preserves archived-workspace errors", + "workspace is archived", + 3, + "workspace is archived", + ], + [ + "preserves unrelated archive-path errors", + "permission denied reading archived_sessions/saved-thread", + 3, + "permission denied reading archived_sessions/saved-thread", + ], + [ + "propagates unarchive missing-thread errors", + "session saved-thread is archived", + 4, + "thread not found", + ], + [ + "propagates unarchive archived errors", + "session saved-thread is archived", + 4, + "session saved-thread is archived", + ], + [ + "propagates retry missing-thread errors", + "session saved-thread is archived", + 5, + "thread not found", + ], + [ + "does not retry archived errors twice", + "session saved-thread is archived", + 5, + "session saved-thread is archived", + ], + ] as const + ).map(([name, resumeError, failAt, finalError]) => ({ name, resumeError, failAt, finalError })), + )("$name", ({ name, resumeError, failAt, finalError }) => + Effect.scoped( + Effect.gen(function* () { + const nativeThreadId = "saved-thread"; + const params = { + threadId: nativeThreadId, + excludeTurns: true, + cwd: CODEX_TEST_RUNTIME_POLICY.cwd, + model: CODEX_TEST_MODEL_SELECTION.model, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }; + const entries: Array = [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5), + { + type: "expect_outbound", + label: "resume archived thread", + frame: { id: 3, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "resume error", + frame: { id: 3, error: { code: -32600, message: resumeError } }, + }, + ]; + if (failAt !== 3) { + entries.push( + { + type: "expect_outbound", + label: "unarchive same thread", + frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } }, + }, + { + type: "emit_inbound", + label: "unarchive result", + frame: + failAt === 4 + ? { id: 4, error: { code: -32600, message: finalError } } + : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } }, + }, + ); + } + if (failAt === 0 || failAt === 5) { + entries.push( + { + type: "expect_outbound", + label: "retry identical resume", + frame: { id: 5, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "retry result", + frame: + failAt === 5 + ? { id: 5, error: { code: -32600, message: finalError } } + : { + id: 5, + result: { + thread: { + id: nativeThreadId, + updatedAt: 1782622450, + turns: [{ type: "unknown-history-item" }], + }, + }, + }, + }, + ); + } + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ scenario: name, entries }), + ); + const resume = harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + if (failAt !== 0) { + const error = yield* Effect.flip(resume); + assert.equal(error._tag, "ProviderAdapterResumeThreadError"); + assert.nestedPropertyVal(error, "cause.errorMessage", finalError); + assert.nestedPropertyVal( + error, + "cause.method", + failAt === 4 ? "thread/unarchive" : "thread/resume", + ); + assert.nestedPropertyVal(error, "cause.requestId", String(failAt)); + return; + } + const resumed = yield* resume; + assert.equal(resumed.id, harness.providerThread.id); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.deepEqual( + resumed.nativeConversationHeadRef, + harness.providerThread.nativeConversationHeadRef, + ); + assert.equal(resumed.status, "idle"); + assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); + }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))), + ), + ); + it.effect("continues an interrupted native thread with empty input and reasoning summaries", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 58ec16508841..3727b419fe1d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -5429,23 +5429,39 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi resumeThread: (threadInput) => Effect.gen(function* () { const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); - + // excludeTurns is not in the generated request schema yet. + const resume = client.raw.request("thread/resume", { + threadId: nativeThreadId, + excludeTurns: true, + ...codexThreadRuntimeParams({ + threadId: threadInput.threadId ?? threadInput.providerThread.appThreadId, + ...(threadInput.modelSelection === undefined + ? {} + : { modelSelection: threadInput.modelSelection }), + ...(threadInput.runtimePolicy === undefined + ? {} + : { runtimePolicy: threadInput.runtimePolicy }), + }), + }); const response = yield* ensureInitialized.pipe( Effect.andThen( - // excludeTurns is not in the generated request schema yet. - client.raw.request("thread/resume", { - threadId: nativeThreadId, - excludeTurns: true, - ...codexThreadRuntimeParams({ - threadId: threadInput.threadId ?? threadInput.providerThread.appThreadId, - ...(threadInput.modelSelection === undefined - ? {} - : { modelSelection: threadInput.modelSelection }), - ...(threadInput.runtimePolicy === undefined - ? {} - : { runtimePolicy: threadInput.runtimePolicy }), + resume.pipe( + Effect.catchTags({ + CodexAppServerRequestError: (cause) => { + if ( + !/\bsession \S+ is archived\b|\bcodex unarchive\b/i.test( + cause.errorMessage, + ) + ) { + return Effect.fail(cause); + } + // Keep the session's history without decoding the unarchive response. + return client.raw + .request("thread/unarchive", { threadId: nativeThreadId }) + .pipe(Effect.andThen(resume)); + }, }), - }), + ), ), Effect.flatMap(decodeCodexResumeMetadata), ); diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts new file mode 100644 index 000000000000..2b1c529ba177 --- /dev/null +++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts @@ -0,0 +1,446 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + NodeId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectWorker from "./EffectWorker.ts"; +import * as EventSink from "./EventSink.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import type { + ProviderAdapterV2Event, + ProviderAdapterV2InterruptInput, + ProviderAdapterV2Shape, + ProviderAdapterV2TurnInput, +} from "./ProviderAdapter.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts"; +import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts"; + +const driver = ProviderDriverKind.make("codex"); +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "test-model" }; + +// Codex turns leave commands running, then the thread moves to another +// provider thread (a provider switch). Stop on the newer, settled run must +// reach both provider threads and end all of the Codex work. +it.effect("Stop reaches background work an earlier provider thread still runs", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("background-work-stop"); + const events = yield* Queue.unbounded(); + const started: ProviderAdapterV2TurnInput[] = []; + const interrupts: ProviderAdapterV2InterruptInput[] = []; + const adapter: ProviderAdapterV2Shape = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (input) => + Effect.gen(function* () { + const now = yield* DateTime.now; + return { + instanceId, + driver, + providerSessionId: input.providerSessionId, + providerSession: { + id: input.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:codex:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: input.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + started.push(turn); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: { + driver, + nativeId: `native:${turn.attemptId}`, + strength: "strong", + }, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: (interrupt) => + Effect.sync(() => { + interrupts.push(interrupt); + }), + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("thread:background-work-stop"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:background-work-stop"), + title: "Background work stop", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-dev-server"), + threadId, + messageId: MessageId.make("message:start-dev-server"), + text: "Start the dev server", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + const first = started[0]!; + const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + const devServerId = TurnItemId.make("turn-item:dev-server"); + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make("dev-server"), + type: "turn-item.updated", + threadId, + runId: first.runId, + occurredAt: now, + payload: { + id: devServerId, + threadId, + runId: first.runId, + nodeId: first.rootNodeId, + providerThreadId: codexTurn.providerThreadId, + providerTurnId: codexTurn.id, + nativeItemRef: null, + parentItemId: null, + ordinal: 100, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "command_execution", + input: "vp run dev --share", + }, + }, + ], + }); + const settled = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...codexTurn, status: "completed", completedAt: now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: codexTurn.providerThreadId, + providerTurnId: codexTurn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + + const codexProviderThread = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + // A settled run with its root node, attempt, provider turn and, + // optionally, a command or native subagent it left running. + const settledRun = (input: { + readonly ordinal: number; + readonly providerThreadId: ProviderThreadId; + readonly runningItem?: { readonly id: TurnItemId; readonly kind: "command" | "subagent" }; + }) => { + const runId = RunId.make(`run:${input.ordinal}`); + const attemptId = RunAttemptId.make(`attempt:${input.ordinal}`); + const nodeId = NodeId.make(`node:${input.ordinal}`); + const providerTurnId = ProviderTurnId.make(`provider-turn:${input.ordinal}`); + const events: Array = [ + { + id: EventId.make(`run:${input.ordinal}`), + type: "run.created", + threadId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: input.ordinal, + providerInstanceId: instanceId, + modelSelection, + providerThreadId: input.providerThreadId, + userMessageId: MessageId.make(`message:${input.ordinal}`), + rootNodeId: nodeId, + activeAttemptId: attemptId, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, + }, + { + id: EventId.make(`node:${input.ordinal}`), + type: "node.updated", + threadId, + runId, + occurredAt: now, + payload: { + id: nodeId, + threadId, + runId, + parentNodeId: null, + rootNodeId: nodeId, + kind: "root_turn", + status: "completed", + countsForRun: true, + providerThreadId: input.providerThreadId, + providerTurnId, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: now, + }, + }, + { + id: EventId.make(`attempt:${input.ordinal}`), + type: "run-attempt.created", + threadId, + occurredAt: now, + payload: { + id: attemptId, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId: instanceId, + providerThreadId: input.providerThreadId, + providerTurnId, + reason: "initial", + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + { + id: EventId.make(`provider-turn:${input.ordinal}`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: providerTurnId, + providerThreadId: input.providerThreadId, + nodeId, + runAttemptId: attemptId, + nativeTurnRef: null, + ordinal: input.ordinal, + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + ]; + const item = input.runningItem; + if (item !== undefined) { + const base = { + id: item.id, + threadId, + runId, + nodeId, + providerThreadId: input.providerThreadId, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: input.ordinal * 100, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + } as const; + events.push({ + id: EventId.make(`item:${input.ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: now, + payload: + item.kind === "command" + ? { ...base, type: "command_execution", input: "vp run test --watch" } + : { + ...base, + // A native subagent item names its own provider thread + // but its parent's provider turn. + providerThreadId: ProviderThreadId.make("provider-thread:codex-subagent"), + type: "subagent", + subagentId: NodeId.make(`subagent:${input.ordinal}`), + origin: "provider_native", + driver, + providerInstanceId: instanceId, + childThreadId: null, + prompt: "Review the change", + result: null, + }, + }); + } + return { runId, providerTurnId, events }; + }; + + // Later Codex runs leave a second command and a native subagent. Then + // the thread moves on to another provider thread, which also has a + // live session. + const watcherId = TurnItemId.make("turn-item:watcher"); + const watcherRun = settledRun({ + ordinal: 2, + providerThreadId: codexProviderThread.id, + runningItem: { id: watcherId, kind: "command" }, + }); + const reviewerId = TurnItemId.make("turn-item:reviewer"); + const reviewerRun = settledRun({ + ordinal: 3, + providerThreadId: codexProviderThread.id, + runningItem: { id: reviewerId, kind: "subagent" }, + }); + const otherProviderThreadId = ProviderThreadId.make("provider-thread:other"); + const latestRun = settledRun({ ordinal: 4, providerThreadId: otherProviderThreadId }); + yield* sink.write({ + events: [ + ...watcherRun.events, + ...reviewerRun.events, + { + id: EventId.make("provider-thread:other"), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + ...codexProviderThread, + id: otherProviderThreadId, + firstRunOrdinal: 4, + lastRunOrdinal: 4, + }, + }, + ...latestRun.events, + ], + }); + + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop-background-work"), + threadId, + runId: latestRun.runId, + }); + yield* worker.drain(); + + // Stop reaches both provider threads. The Codex one is interrupted at + // its latest pending work, the subagent's parent turn, so its settle + // covers all three Codex runs. + assert.sameDeepMembers( + interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]), + [ + [otherProviderThreadId, latestRun.providerTurnId], + [codexProviderThread.id, reviewerRun.providerTurnId], + ], + ); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + [devServerId, watcherId, reviewerId].map( + (id) => after.turnItems.find((item) => item.id === id)?.status, + ), + ["interrupted", "interrupted", "interrupted"], + ); + }).pipe( + Effect.provide( + makeOrchestratorV2ReplayLayerWithRegistry( + { name: "background-work-stop" }, + ProviderAdapterRegistry.makeSingleLayer(adapter), + { runEffectWorker: false }, + ), + ), + ); + }), + ), +); diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index a64dc21cec91..e11338775462 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -7,6 +7,7 @@ import { MessageId, type ModelSelection, NodeId, + type OrchestrationV2Run, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -35,6 +36,7 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; +import { continueRestartedRun } from "./RestartContinuation.ts"; import { OrchestrationV2EventSinkLayerLive, OrchestrationV2LayerLive, @@ -384,6 +386,98 @@ it.layer(TestLayer)("delegated completion delivery repairs", (it) => { }), ); + it.effect("acceptance batches a settled_only sibling once its spawning run ended", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("mailbox-mixed"); + const runId = RunId.make("mailbox-mixed-parent"); + const taskId = NodeId.make("mailbox-mixed-always"); + const siblingId = NodeId.make("mailbox-mixed-settled-only"); + const messageId = MessageId.make(`message:delegated-delivery:${threadId}`); + yield* seedParentWithTerminalTask({ + threadId, + runId, + projectId: ProjectId.make("mailbox-mixed-project"), + rootNodeId: NodeId.make("mailbox-mixed-root"), + taskId, + deliveryState: "claimed", + completionWake: "always", + deliveryTaskIds: [taskId], + now, + }); + const projection = yield* orchestrator.getThreadProjection(threadId); + const task = projection.subagents[0]!; + const spawningRun = projection.runs.find((row) => row.id === runId)!; + // A restart cut the spawning run; its continuation is the live run now. + yield* sink.write({ + events: [ + { + ...runEvent({ threadId, runId, ordinal: 1, status: "cancelled", now }), + payload: { ...spawningRun, status: "cancelled" as const, completedAt: now }, + }, + runEvent({ + threadId, + runId: RunId.make("mailbox-mixed-continuation"), + ordinal: 2, + status: "running", + now, + }), + { + id: EventId.make("mailbox-mixed-message"), + type: "message.updated", + threadId, + runId, + occurredAt: now, + payload: { + id: messageId, + threadId, + runId, + nodeId: task.parentNodeId, + role: "user", + text: "Background task finished", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] }, + }, + }, + { + id: EventId.make(`event:${siblingId}`), + type: "subagent.updated" as const, + threadId, + runId, + nodeId: siblingId, + occurredAt: now, + payload: { + ...task, + id: siblingId, + completionWake: "settled_only" as const, + completionDelivery: { state: "pending" as const, observedByRunId: null }, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "notification.delivery.accept", + commandId: CommandId.make("accept-mixed"), + threadId, + messageId, + }); + const accepted = yield* orchestrator.getThreadProjection(threadId); + const cohort = accepted.runs.find((row) => row.id === runId)?.delegatedCompletion; + assert.deepEqual(cohort?.delivery?.taskIds, [siblingId]); + assert.equal( + accepted.subagents.find((row) => row.id === siblingId)?.completionDelivery?.state, + "claimed", + ); + }), + ); + it.effect("builds completion text and metadata from the same live cohort", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -652,3 +746,533 @@ it.layer(TestLayer)("delegated completion delivery repairs", (it) => { }), ); }); + +// Runtime reconciliation writes restart cancellations under this command +// prefix, which the live terminal-run listener skips. +const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`); + +const parentProviderThreadId = (threadId: ThreadId) => + ProviderThreadId.make(`provider-thread:${String(threadId).replace("thread:", "")}`); + +const runEvent = (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly ordinal: number; + readonly status: OrchestrationV2Run["status"]; + readonly now: DateTime.Utc; + readonly providerThreadId?: ProviderThreadId; + readonly userMessageId?: MessageId; + readonly delegatedCompletion?: OrchestrationV2Run["delegatedCompletion"]; +}) => ({ + id: EventId.make(`event:${input.runId}:${input.status}`), + type: "run.updated" as const, + threadId: input.threadId, + runId: input.runId, + providerInstanceId: modelSelection.instanceId, + occurredAt: input.now, + payload: { + id: input.runId, + threadId: input.threadId, + ordinal: input.ordinal, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: input.providerThreadId ?? null, + userMessageId: input.userMessageId ?? MessageId.make(`message:${input.runId}`), + rootNodeId: null, + activeAttemptId: null, + status: input.status, + requestedAt: input.now, + startedAt: input.now, + completedAt: input.status === "running" ? null : input.now, + checkpointId: null, + contextHandoffId: null, + ...(input.delegatedCompletion === undefined + ? {} + : { delegatedCompletion: input.delegatedCompletion }), + }, +}); + +/** A running app-owned task whose child thread's first run the restart cancelled. */ +const seedRestartCancelledChild = (input: { + readonly parentThreadId: ThreadId; + readonly projectId: ProjectId; + readonly parentRunId: RunId; + readonly rootNodeId: NodeId; + readonly name: string; + readonly completionWake: "always" | "settled_only"; + readonly continuationPending: boolean; + /** "completed" seeds a settled turn whose background work the restart cancelled. */ + readonly runStatus?: "cancelled" | "completed"; + readonly now: DateTime.Utc; +}) => + Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const taskId = NodeId.make(`node:${input.name}`); + const childThreadId = ThreadId.make(`thread:${input.name}`); + const childRunId = RunId.make(`run:${input.name}:1`); + yield* eventSink.write({ + commandId: CommandId.make(`command:seed-child:${input.name}`), + events: [ + { + id: EventId.make(`event:${input.name}:thread`), + type: "thread.created", + threadId: childThreadId, + occurredAt: input.now, + payload: { + createdBy: "agent", + creationSource: "server", + id: childThreadId, + projectId: input.projectId, + title: input.name, + providerInstanceId: modelSelection.instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: input.parentThreadId, + relationshipToParent: "subagent", + rootThreadId: input.parentThreadId, + }, + forkedFrom: { type: "node", nodeId: taskId }, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }, + { + id: EventId.make(`event:${input.name}:task`), + type: "subagent.updated", + threadId: input.parentThreadId, + runId: input.parentRunId, + nodeId: taskId, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: input.now, + payload: { + id: taskId, + threadId: input.parentThreadId, + runId: input.parentRunId, + parentNodeId: input.rootNodeId, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId: modelSelection.instanceId, + providerThreadId: null, + childThreadId, + nativeTaskRef: null, + prompt: `Run ${input.name}.`, + title: null, + model: null, + completionWake: input.completionWake, + status: "running", + result: null, + startedAt: input.now, + completedAt: null, + updatedAt: input.now, + }, + }, + ], + }); + yield* eventSink.writeWithEffects({ + commandId: reconcileCommandId(input.name), + events: [ + runEvent({ + threadId: childThreadId, + runId: childRunId, + ordinal: 1, + status: input.runStatus ?? "cancelled", + now: input.now, + }), + ], + effects: input.continuationPending + ? [ + { + id: `effect:restart-continuation:${childRunId}`, + commandId: reconcileCommandId(input.name), + threadId: childThreadId, + request: { type: "provider-runtime.continue", sourceRunId: childRunId }, + }, + ] + : [], + }); + return { taskId, childThreadId, childRunId }; + }); + +it.layer(TestLayer)("delegated tasks across a server restart", (it) => { + it.effect("holds a restart-cancelled child for its continuation's result", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:restart-parent"); + const projectId = ProjectId.make("project:restart-parent"); + const runId = RunId.make("run:restart-parent"); + const rootNodeId = NodeId.make("node:restart-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:restart-parent-settled"), + deliveryState: "delivered", + now, + }); + const child = ( + name: string, + continuationPending: boolean, + runStatus?: "cancelled" | "completed", + ) => + seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name, + completionWake: "always", + continuationPending, + ...(runStatus === undefined ? {} : { runStatus }), + now, + }); + const resumed = yield* child("restart-resumed-child", true); + const stopped = yield* child("restart-stopped-child", false); + // Settled with only background work left: its interim reply is not the result. + const backgrounded = yield* child("restart-backgrounded-child", true, "completed"); + // A second restart cut the first continuation before it started. + const recut = yield* child("restart-recut-child", false); + const recutContinuationId = RunId.make("run:restart-recut-child:2"); + const recutCommandId = CommandId.make("command:restart-recut-child:reconcile"); + const recutRun = runEvent({ + threadId: recut.childThreadId, + runId: recutContinuationId, + ordinal: 2, + status: "cancelled", + now, + }); + yield* eventSink.writeWithEffects({ + commandId: recutCommandId, + events: [ + { + ...recutRun, + payload: { + ...recutRun.payload, + startedAt: null, + restartContinuationOfRunId: recut.childRunId, + }, + }, + ], + effects: [ + { + id: `effect:restart-continuation:${recutContinuationId}`, + commandId: recutCommandId, + threadId: recut.childThreadId, + request: { type: "provider-runtime.continue", sourceRunId: recutContinuationId }, + }, + ], + }); + + yield* orchestrator.recoverDelegatedTasks; + + const recovered = yield* orchestrator.getThreadProjection(threadId); + const task = (id: NodeId) => recovered.subagents.find((row) => row.id === id); + assert.equal(task(stopped.taskId)?.status, "cancelled"); + assert.equal(task(stopped.taskId)?.completionDelivery?.state, "claimed"); + assert.equal(task(resumed.taskId)?.status, "running"); + assert.isNull(task(resumed.taskId)?.result ?? null); + assert.equal(task(backgrounded.taskId)?.status, "running"); + assert.isNull(task(backgrounded.taskId)?.result ?? null); + assert.equal(task(recut.taskId)?.status, "running"); + assert.isTrue(yield* orchestrator.delegatedTaskResultPending(recut.childThreadId)); + assert.isTrue(yield* orchestrator.delegatedTaskResultPending(resumed.childThreadId)); + assert.isFalse(yield* orchestrator.delegatedTaskResultPending(stopped.childThreadId)); + // A replayed first continuation settling must not release the second one's hold. + yield* orchestrator.recoverDelegatedTask(recut.childThreadId, recut.childRunId); + const replayed = yield* orchestrator.getThreadProjection(threadId); + assert.equal(replayed.subagents.find((row) => row.id === recut.taskId)?.status, "running"); + // A caller that read the cancelled run before the child resumed sees it as pending. + yield* eventSink.write({ + commandId: CommandId.make("command:restart-stopped-child:resumed"), + events: [ + runEvent({ + threadId: stopped.childThreadId, + runId: RunId.make("run:restart-stopped-child:2"), + ordinal: 2, + status: "running", + now, + }), + ], + }); + assert.isTrue(yield* orchestrator.delegatedTaskResultPending(stopped.childThreadId)); + assert.isFalse( + recovered.contextTransfers.some( + (transfer) => transfer.sourceThreadId === resumed.childThreadId, + ), + ); + + // The continuation's own run finishing settles the task with its result. + const afterSequence = yield* eventSink.latestSequence(); + const continuationRunId = RunId.make("run:restart-resumed-child:2"); + yield* eventSink.write({ + commandId: CommandId.make("command:restart-resumed-child:completed"), + events: [ + { + id: EventId.make("event:restart-resumed-child:result"), + type: "message.updated", + threadId: resumed.childThreadId, + runId: continuationRunId, + occurredAt: now, + payload: { + id: MessageId.make("message:restart-resumed-child:result"), + threadId: resumed.childThreadId, + runId: continuationRunId, + nodeId: null, + role: "assistant", + text: "Finished after the restart.", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + }, + }, + runEvent({ + threadId: resumed.childThreadId, + runId: continuationRunId, + ordinal: 2, + status: "completed", + now, + }), + ], + }); + const settled = yield* eventSink + .stream({ afterSequence, eventType: "subagent.updated" }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === resumed.taskId, + ), + Stream.take(1), + Stream.runHead, + ); + assert.isTrue(settled._tag === "Some"); + const finished = yield* orchestrator.getThreadProjection(threadId); + const finishedTask = finished.subagents.find((row) => row.id === resumed.taskId); + assert.equal(finishedTask?.status, "completed"); + assert.equal(finishedTask?.result, "Finished after the restart."); + }), + ); + + it.effect("settles a restart-cancelled child whose continuation declines to start", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:restart-declined-parent"); + const projectId = ProjectId.make("project:restart-declined-parent"); + const runId = RunId.make("run:restart-declined-parent"); + const rootNodeId = NodeId.make("node:restart-declined-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:restart-declined-parent-settled"), + deliveryState: "delivered", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: "restart-declined-child", + completionWake: "always", + continuationPending: true, + now, + }); + yield* orchestrator.recoverDelegatedTasks; + const held = yield* orchestrator.getThreadProjection(threadId); + assert.equal(held.subagents.find((row) => row.id === child.taskId)?.status, "running"); + + yield* continueRestartedRun({ + threadId: child.childThreadId, + sourceRunId: child.childRunId, + }).pipe( + Effect.provide(ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false })), + ); + + const settled = yield* orchestrator.getThreadProjection(threadId); + const task = settled.subagents.find((row) => row.id === child.taskId); + assert.equal(task?.status, "cancelled"); + assert.equal(task?.completionDelivery?.state, "claimed"); + }), + ); + + // A running provider turn does not prove the provider consumed the delivery + // (Claude marks the turn running before it reads the prompt), so a cut + // delivery is offered again even when a continuation resumes that turn. + it.effect("re-offers a cut delivery even when a continuation resumes its turn", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const seed = (name: string, continuationPending: boolean) => + Effect.gen(function* () { + const threadId = ThreadId.make(`thread:${name}`); + const runId = RunId.make(`run:${name}`); + const taskId = NodeId.make(`node:${name}-task`); + const messageId = MessageId.make(`message:delegated-delivery:${threadId}`); + const deliveryRunId = RunId.make(`run:${name}:delivery`); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make(`project:${name}`), + runId, + rootNodeId: NodeId.make(`node:${name}-root`), + taskId, + deliveryState: "claimed", + completionWake: "always", + deliveryTaskIds: [taskId], + now, + }); + yield* eventSink.writeWithEffects({ + commandId: reconcileCommandId(name), + events: [ + { + id: EventId.make(`event:${name}:delivery-message`), + type: "message.updated", + threadId, + runId: deliveryRunId, + occurredAt: now, + payload: { + id: messageId, + threadId, + runId: deliveryRunId, + nodeId: null, + role: "user", + text: `Delegated task ${taskId} reached a terminal state.`, + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] }, + }, + }, + runEvent({ + threadId, + runId: deliveryRunId, + ordinal: 2, + status: "cancelled", + now, + providerThreadId: parentProviderThreadId(threadId), + userMessageId: messageId, + }), + ], + effects: continuationPending + ? [ + { + id: `effect:restart-continuation:${deliveryRunId}`, + commandId: reconcileCommandId(name), + threadId, + request: { type: "provider-runtime.continue", sourceRunId: deliveryRunId }, + }, + ] + : [], + }); + return { threadId, runId, taskId }; + }); + const cut = yield* seed("delivery-cut", false); + const resumed = yield* seed("delivery-resumed", true); + + yield* orchestrator.recoverDelegatedTasks; + + for (const seeded of [cut, resumed]) { + const projection = yield* orchestrator.getThreadProjection(seeded.threadId); + assert.deepEqual( + projection.subagents.find((row) => row.id === seeded.taskId)?.completionDelivery?.state, + "claimed", + ); + const delivery = projection.runs.find((row) => row.id === seeded.runId)?.delegatedCompletion + ?.delivery; + assert.equal(delivery?.generation, 2); + assert.deepEqual(delivery?.taskIds, [seeded.taskId]); + } + }), + ); + + it.effect("wakes the parent for a settled_only task once its spawning turn ended", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:settled-only-restart"); + const projectId = ProjectId.make("project:settled-only-restart"); + const runId = RunId.make("run:settled-only-restart"); + const rootNodeId = NodeId.make("node:settled-only-restart-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:settled-only-restart-settled"), + deliveryState: "delivered", + now, + }); + // The restart cut the turn blocked in delegate_task(wait); its + // continuation is a new, live run. + yield* eventSink.write({ + commandId: reconcileCommandId("settled-only-restart"), + events: [ + runEvent({ + threadId, + runId, + ordinal: 1, + status: "cancelled", + now, + providerThreadId: parentProviderThreadId(threadId), + userMessageId: MessageId.make(`message:seed-user:${threadId}`), + delegatedCompletion: { disposition: "open", nextGeneration: 2, delivery: null }, + }), + runEvent({ + threadId, + runId: RunId.make("run:settled-only-restart:continuation"), + ordinal: 2, + status: "running", + now, + providerThreadId: parentProviderThreadId(threadId), + }), + ], + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: "settled-only-restart-child", + completionWake: "settled_only", + continuationPending: false, + now, + }); + + yield* orchestrator.recoverDelegatedTasks; + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + projection.subagents.find((row) => row.id === child.taskId)?.completionDelivery?.state, + "claimed", + ); + assert.deepEqual( + projection.runs.find((row) => row.id === runId)?.delegatedCompletion?.delivery?.taskIds, + [child.taskId], + ); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 4841a5762480..9f63d8c568b6 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -278,9 +278,16 @@ export const layer: Layer.Layer = La available, Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined), ).pipe(Effect.asVoid); + // Each thread runs its effects one at a time, in enqueue (rowid) order. An earlier + // effect waiting out a retry backoff still blocks later ones, so a turn + // cannot start while a failed rollback is about to restore files. A claim + // that skips restart continuations is not blocked by them either. // Title generation is correlated metadata work, so it has its own // per-thread lane and cannot delay provider lifecycle effects. - const claimableCandidatePredicate = (availableBefore?: string) => + const claimableCandidatePredicate = ( + availableBefore?: string, + excludeRestartContinuations = false, + ) => sql` ${ availableBefore === undefined @@ -292,7 +299,18 @@ export const layer: Layer.Layer = La SELECT 1 FROM orchestration_v2_effect_outbox AS active WHERE active.thread_id = candidate.thread_id - AND active.status = 'running' + AND ( + active.status = 'running' + OR ( + active.status = 'pending' + AND active.rowid < candidate.rowid + AND ${ + excludeRestartContinuations + ? sql`active.effect_type != 'provider-runtime.continue'` + : sql`1 = 1` + } + ) + ) AND ( ( candidate.effect_type = 'thread-title.generate' @@ -492,7 +510,7 @@ export const layer: Layer.Layer = La WHERE effect_id = ( SELECT candidate.effect_id FROM orchestration_v2_effect_outbox AS candidate - WHERE ${claimableCandidatePredicate(nowIso)} + WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)} AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`} ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC LIMIT 1 diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index af2667a8cf8e..5f7db32b1194 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -79,6 +79,8 @@ function restartEffect( function makeExecutorLayer(input: { readonly events: Ref.Ref>; readonly failFirstStart?: Ref.Ref; + readonly threads?: Partial; + readonly continueAfterRestart?: boolean; }) { const record = (event: string) => Ref.update(input.events, (events) => [...events, event]); const dependencies = Layer.mergeAll( @@ -148,8 +150,10 @@ function makeExecutorLayer(input: { Layer.provide( Layer.mergeAll( dependencies, - Layer.mock(ThreadManagementService.ThreadManagementService)({}), - ServerSettings.layerTest(), + Layer.mock(ThreadManagementService.ThreadManagementService)(input.threads ?? {}), + ServerSettings.layerTest( + input.continueAfterRestart === true ? { continueThreadsAfterServerUpdate: true } : {}, + ), ), ), ); @@ -753,3 +757,46 @@ it.effect("safely retries after replacement cleanup succeeds and start fails", ( ]); }), ); + +it.effect("settles a delegated child once its restart continuation fails for good", () => + Effect.gen(function* () { + const timestamp = DateTime.formatIso(yield* DateTime.now); + const events = yield* Ref.make>([]); + const recovered = yield* Ref.make>([]); + const layer = makeExecutorLayer({ + events, + continueAfterRestart: true, + threads: { + getThreadRecords: () => Effect.fail(new Error("provider instance removed") as never), + recoverDelegatedTask: (childThreadId) => + Ref.update(recovered, (ids) => [...ids, childThreadId]), + }, + }); + const effect: EffectOutbox.OrchestrationEffectV2 = { + id: `effect:restart-continuation:${runId}`, + commandId: CommandId.make("command:restart-continuation-failure"), + threadId, + request: { type: "provider-runtime.continue", sourceRunId: runId }, + status: "running", + attemptCount: 1, + availableAt: timestamp, + leaseOwner: "test-worker", + leaseExpiresAt: timestamp, + createdAt: timestamp, + updatedAt: timestamp, + completedAt: null, + lastError: null, + }; + yield* Effect.gen(function* () { + const executor = yield* EffectWorker.OrchestrationEffectExecutorV2; + assert.isTrue( + Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: true }))), + ); + assert.deepEqual(yield* Ref.get(recovered), []); + assert.isTrue( + Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: false }))), + ); + assert.deepEqual(yield* Ref.get(recovered), [threadId]); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 1abf070b87ec..149494739182 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -108,13 +108,17 @@ export const executorLayer: Layer.Layer< execute: (effect, options) => { const willRetry = options?.willRetry ?? false; switch (effect.request.type) { - case "provider-runtime.continue": - return continueRestartedRun({ - threadId: effect.threadId, - sourceRunId: effect.request.sourceRunId, - }).pipe( + case "provider-runtime.continue": { + const sourceRunId = effect.request.sourceRunId; + return continueRestartedRun({ threadId: effect.threadId, sourceRunId }).pipe( Effect.provideService(ThreadManagementService.ThreadManagementService, threads), Effect.provideService(ServerSettings.ServerSettingsService, settings), + // A continuation that will never run still owes a delegated parent a result. + Effect.tapError(() => + willRetry + ? Effect.void + : threads.recoverDelegatedTask(effect.threadId, sourceRunId), + ), Effect.mapError( (cause) => new OrchestrationEffectExecutionError({ @@ -124,6 +128,7 @@ export const executorLayer: Layer.Layer< }), ), ); + } case "provider-session.detach": return providerSessions .detach({ @@ -169,10 +174,12 @@ export const executorLayer: Layer.Layer< // The provider has stopped what it still ran and reported it. // Whatever the thread still shows on that provider thread is // work no process will report on, so the Stop ends it too. + // One Stop can interrupt several provider threads, so the + // settle is keyed by effect, not by the Stop command. Effect.andThen( threads.dispatch({ type: "thread.background-work.settle", - commandId: CommandId.make(`${effect.commandId}:background-work-settled`), + commandId: CommandId.make(`${effect.id}:background-work-settled`), threadId: effect.threadId, providerThreadId: effect.request.providerThreadId, providerTurnId: effect.request.providerTurnId, diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index c61ce6ba8b7b..71b6f0ea994f 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -17,6 +17,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; +import * as Semaphore from "effect/Semaphore"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -224,6 +225,40 @@ const baseLayer: Layer.Layer< ); } }); + const publishStoredEvents = (events: ReadonlyArray) => + eventStore.publishCommitted(events).pipe(Effect.andThen(publishLiveEvents(events))); + + // Transactions commit one at a time, but each writer publishes after its + // commit. If a writer is descheduled in between, a later commit reaches + // subscribers first, and clients drop any event at or below the newest + // sequence they have applied. So a writer takes this lane as the last step + // of its transaction and holds it until it has published. Publishing never + // waits, so a writer that holds the transaction while it waits for the + // lane is not blocked for long. + const publishLane = yield* Semaphore.make(1); + const commitThenPublish = ( + transaction: Effect.Effect, + publish: (committed: A) => Effect.Effect, + ) => + Effect.suspend(() => { + let holdsLane = false; + const takeLane = publishLane.take(1).pipe( + Effect.andThen( + Effect.sync(() => { + holdsLane = true; + }), + ), + Effect.uninterruptible, + ); + return sql + .withTransaction(Effect.tap(transaction, () => takeLane)) + .pipe( + Effect.tap(publish), + Effect.ensuring( + Effect.suspend(() => (holdsLane ? publishLane.release(1) : Effect.void)), + ), + ); + }); // A user can answer after terminal normalization reads the pending request. // Recheck inside the write transaction so stale cleanup cannot erase answers. @@ -332,7 +367,7 @@ const baseLayer: Layer.Layer< "orchestration_v2.thread_id": input.events[0]?.threadId ?? null, }); - const storedEvents = yield* sql.withTransaction( + return yield* commitThenPublish( Effect.gen(function* () { const normalized = yield* normalizeEvents( input.guardPendingUserInputCancellations === true @@ -347,13 +382,14 @@ const baseLayer: Layer.Layer< yield* effectOutbox.enqueue(input.effects); return committed; }), + (storedEvents) => + Effect.gen(function* () { + if (input.effects.length > 0) { + yield* effectOutbox.notifyAvailable(input.effects.length); + } + yield* publishStoredEvents(storedEvents); + }), ); - if (input.effects.length > 0) { - yield* effectOutbox.notifyAvailable(input.effects.length); - } - yield* eventStore.publishCommitted(storedEvents); - yield* publishLiveEvents(storedEvents); - return storedEvents; }); const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")( @@ -365,7 +401,7 @@ const baseLayer: Layer.Layer< "orchestration_v2.thread_id": input.threadId, }); - const result = yield* sql.withTransaction( + return yield* commitThenPublish( Effect.gen(function* () { const rows = yield* sql<{ readonly status: string; @@ -403,12 +439,8 @@ const baseLayer: Layer.Layer< yield* applyStoredEvents(storedEvents); return { committed: true as const, storedEvents }; }), + (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void), ); - if (result.committed) { - yield* eventStore.publishCommitted(result.storedEvents); - yield* publishLiveEvents(result.storedEvents); - } - return result; }, ); @@ -424,7 +456,7 @@ const baseLayer: Layer.Layer< "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal, }); - const result = yield* sql.withTransaction( + return yield* commitThenPublish( Effect.gen(function* () { const rows = yield* sql<{ readonly active_attempt_id: string | null; @@ -464,12 +496,8 @@ const baseLayer: Layer.Layer< yield* applyStoredEvents(storedEvents); return { committed: true as const, storedEvents }; }), + (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void), ); - if (result.committed) { - yield* eventStore.publishCommitted(result.storedEvents); - yield* publishLiveEvents(result.storedEvents); - } - return result; }); const existingCommandResult = (commandId: CommandId) => @@ -490,7 +518,7 @@ const baseLayer: Layer.Layer< const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* ( input: Parameters[0], ) { - const result = yield* sql.withTransaction( + const result = yield* commitThenPublish( Effect.gen(function* () { const reserved = yield* commandReceipts.insertIfAbsent({ commandId: input.commandId, @@ -538,15 +566,15 @@ const baseLayer: Layer.Layer< }); return { receipt, storedEvents, committed: true as const, cancelledEffectIds }; }), + (result) => + Effect.gen(function* () { + yield* effectOutbox.signalCancellations(result.cancelledEffectIds); + if (result.committed && input.effects.length > 0) { + yield* effectOutbox.notifyAvailable(input.effects.length); + } + if (result.committed) yield* publishStoredEvents(result.storedEvents); + }), ); - yield* effectOutbox.signalCancellations(result.cancelledEffectIds); - if (result.committed && input.effects.length > 0) { - yield* effectOutbox.notifyAvailable(input.effects.length); - } - if (result.committed) { - yield* eventStore.publishCommitted(result.storedEvents); - yield* publishLiveEvents(result.storedEvents); - } return { receipt: result.receipt, storedEvents: result.storedEvents, @@ -593,7 +621,7 @@ const baseLayer: Layer.Layer< const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")( function* (input: Parameters[0]) { - const result = yield* sql.withTransaction( + const result = yield* commitThenPublish( Effect.gen(function* () { const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = { commandId: input.commandId, @@ -613,10 +641,9 @@ const baseLayer: Layer.Layer< yield* commandReceipts.upsert(receipt); return { receipt, event }; }), + (result) => + result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]), ); - if (result.event !== undefined) { - yield* eventStore.publishCommitted([result.event]); - } return { receipt: result.receipt, committed: result.event !== undefined }; }, ); diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 22b93178711c..dc7eacc59ba5 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -51,7 +51,9 @@ import * as EventStore from "./EventStore.ts"; import * as IdAllocator from "./IdAllocator.ts"; import * as ProjectionMaintenance from "./ProjectionMaintenance.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProjectStore from "./ProjectStore.ts"; import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; +import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; const isLiveStreamBufferError = Schema.is(LiveStreamBufferError); const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -2303,6 +2305,76 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }).pipe(Effect.provide(Layer.fresh(effectOutboxProvided))), ); + it.effect("keeps later thread effects behind an earlier effect waiting to retry", () => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const workerId = "retry-order-worker"; + const commandId = CommandId.make("command:foundation-retry-order"); + const threadId = ThreadId.make("thread:foundation-retry-order"); + yield* outbox.enqueue([ + { + id: "effect:foundation-retry-order:z-rollback", + commandId, + threadId, + request: { + type: "provider-thread.rollback", + providerThreadId: ProviderThreadId.make("provider-thread:foundation-retry-order"), + checkpointId: CheckpointId.make("checkpoint:foundation-retry-order"), + scopeId: CheckpointScopeId.make("scope:foundation-retry-order"), + }, + }, + ]); + const rollback = yield* outbox.claimNext({ workerId, leaseDurationMs: 30_000 }); + assert.isTrue(Option.isSome(rollback)); + if (Option.isNone(rollback)) return; + yield* outbox.retry({ + effectId: rollback.value.id, + workerId, + error: "rollback failed once", + delayMs: 60_000, + }); + + // A turn the user starts during the rollback's backoff must not run first, + // even when its timestamp ties and its id sorts first. + yield* outbox.enqueue([ + { + id: "effect:foundation-retry-order:a-start", + commandId: CommandId.make("command:foundation-retry-order:start"), + threadId, + request: { type: "provider-turn.start", runId: RunId.make("run:foundation-retry-order") }, + }, + { + id: "effect:foundation-retry-order:b-title", + commandId: CommandId.make("command:foundation-retry-order:title"), + threadId, + request: { type: "thread-title.generate", kind: { type: "regenerate" } }, + }, + ]); + const title = yield* outbox.claimNext({ workerId, leaseDurationMs: 30_000 }); + assert.equal(Option.getOrUndefined(title)?.id, "effect:foundation-retry-order:b-title"); + const blocked = yield* outbox.claimNext({ workerId, leaseDurationMs: 30_000 }); + assert.isTrue(Option.isNone(blocked)); + const nextClaimable = yield* outbox.nextClaimableAt; + assert.isTrue(Option.isSome(nextClaimable)); + if (Option.isSome(nextClaimable)) { + assert.equal( + DateTime.formatIso(nextClaimable.value), + (yield* outbox.get(rollback.value.id)).pipe(Option.getOrThrow).availableAt, + ); + } + + yield* outbox.cancelUnsettled({ + threadId, + effectTypes: ["provider-thread.rollback"], + reason: "Test cleanup.", + }); + const unblocked = yield* outbox.claimNext({ workerId, leaseDurationMs: 30_000 }); + assert.equal(Option.getOrUndefined(unblocked)?.id, "effect:foundation-retry-order:a-start"); + yield* outbox.succeed({ effectId: "effect:foundation-retry-order:a-start", workerId }); + yield* outbox.succeed({ effectId: "effect:foundation-retry-order:b-title", workerId }); + }).pipe(Effect.provide(Layer.fresh(effectOutboxProvided))), + ); + it.effect("executes a retry at its durable deadline instead of the liveness interval", () => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; @@ -3222,3 +3294,90 @@ it.live("keeps claiming new work after repeated idle periods", () => }).pipe(Effect.provide(workerLayer), Effect.scoped); }).pipe(Effect.provide(TestLayer)), ); + +it.effect("publishes live events in commit order across concurrent writers", () => + Effect.gen(function* () { + const firstCommitted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + // The first writer's post-commit wakeup stands in for any scheduler yield + // between its commit and its publish. + const pausingOutbox = Layer.effect( + EffectOutbox.EffectOutboxV2, + Effect.gen(function* () { + const delegate = yield* EffectOutbox.EffectOutboxV2; + return EffectOutbox.EffectOutboxV2.of({ + ...delegate, + notifyAvailable: (count) => + Deferred.succeed(firstCommitted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFirst)), + Effect.andThen(delegate.notifyAvailable(count)), + ), + }); + }), + ).pipe(Layer.provide(effectOutboxProvided)); + const eventSinkLayer = EventSink.layerFromStores.pipe( + Layer.provide( + Layer.mergeAll( + storesProvided, + pausingOutbox, + commandReceiptStoreProvided, + ProjectStore.layer.pipe(Layer.provide(databaseLayer)), + TurnItemPositionStore.layer.pipe(Layer.provide(databaseLayer)), + ), + ), + ); + + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const first = makeThread(ThreadId.make("thread:foundation-publish-order:first"), now); + const second = makeThread(ThreadId.make("thread:foundation-publish-order:second"), now); + const published = yield* eventSink + .stream({ afterSequence: yield* eventSink.latestSequence() }) + .pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true })); + + const firstWrite = yield* eventSink + .writeWithEffects({ + events: [ + threadCreatedEvent({ id: "event:foundation-publish-order:first", thread: first, now }), + ], + effects: [ + { + id: "effect:foundation-publish-order:first", + commandId: CommandId.make("command:foundation-publish-order:first"), + threadId: first.id, + request: { type: "terminal.cleanup" }, + }, + ], + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(firstCommitted); + // The second writer commits after the first. It may run as far as it can + // before the first writer resumes. + const secondWrite = yield* eventSink + .write({ + events: [ + threadCreatedEvent({ + id: "event:foundation-publish-order:second", + thread: second, + now, + }), + ], + }) + .pipe( + Effect.provideService(Scheduler.MaxOpsBeforeYield, Number.POSITIVE_INFINITY), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + yield* Deferred.succeed(releaseFirst, undefined); + yield* Fiber.join(firstWrite); + yield* Fiber.join(secondWrite); + + const sequences = Array.from(yield* Fiber.join(published), (stored) => stored.sequence); + assert.deepEqual( + sequences, + [...sequences].sort((left, right) => left - right), + ); + }).pipe(Effect.provide(eventSinkLayer)); + }).pipe(Effect.provide(databaseLayer)), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 28296f9d7b78..112735188d1b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1,6 +1,7 @@ import { latestExecutedRun, latestRootProviderFailure, + runRanAfter, usageLimitBlockedRun, } from "@t3tools/shared/orchestrationV2ThreadError"; import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests"; @@ -19,6 +20,8 @@ import { OrchestrationV2Command, type OrchestrationV2InternalCommand, type OrchestrationV2ServerCommand, + type ThreadPullRequestLink, + type ThreadPullRequestWatch, type OrchestrationV2AppThread, type OrchestrationV2ContextHandoff, type OrchestrationV2ContextSourcePoint, @@ -75,6 +78,7 @@ import { notificationTurnItem } from "./Notification.ts"; import { isRestartNoteSource } from "./RestartBackgroundNote.ts"; import { isUndeliveredMailboxSteer } from "./NotificationMailbox.ts"; import { EventSinkV2 } from "./EventSink.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { @@ -240,6 +244,17 @@ export interface OrchestratorV2DispatchResult { export interface OrchestratorV2Shape { readonly resumeQueuedRuns: Effect.Effect; + /** Startup pass that settles delegated-task results and deliveries runs left behind. */ + readonly recoverDelegatedTasks: Effect.Effect; + /** Settles a delegated child whose restart continuation of `sourceRunId` declined or failed. */ + readonly recoverDelegatedTask: (threadId: ThreadId, sourceRunId: RunId) => Effect.Effect; + /** + * Whether a delegated child's apparent result is not final yet: a restart + * continuation is pending, or the child is working again. + */ + readonly delegatedTaskResultPending: ( + childThreadId: ThreadId, + ) => Effect.Effect; readonly dispatch: ( command: OrchestrationV2ServerCommand, ) => Effect.Effect; @@ -336,7 +351,8 @@ function wakeWorkStartedAt( return previous === undefined ? {} : { workStartedAt: orchestrationV2RunWorkStartedAt(previous) }; } -function isNativeMaintenanceCommand(message: { +/** A native /compact or /logout turn: provider maintenance, not agent work. */ +export function isNativeMaintenanceCommand(message: { readonly text: string; readonly attachments: ReadonlyArray; readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined; @@ -371,6 +387,8 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": + case "thread.pull-request.watch": + case "thread.pull-request-watch.sync": case "thread.pull-request.sync": case "thread.title.regeneration.complete": case "thread.runtime-mode.set": @@ -444,6 +462,35 @@ function hasLiveRun(projection: Pick): ); } +/** The link with its watch replaced, or removed when `watch` is undefined. */ +function withPullRequestWatch( + link: ThreadPullRequestLink, + watch: ThreadPullRequestWatch | undefined, +): ThreadPullRequestLink { + const { watch: _previous, ...rest } = link; + return watch === undefined ? rest : { ...rest, watch }; +} + +/** A legacy single-PR link as a link entry. Re-linking a pull request keeps its watch. */ +function legacyPullRequestLink( + thread: OrchestrationV2AppThread, + linked: ThreadLinkedPullRequest, + now: DateTime.Utc, +): ThreadPullRequestLink { + const key = legacyThreadPullRequestKey(linked); + return withPullRequestWatch( + { + ...key, + url: linked.url, + source: "manual", + linkedAt: DateTime.formatIso(now), + snapshot: null, + stack: null, + }, + threadPullRequestsOf(thread).find((link) => threadPullRequestKeysEqual(link, key))?.watch, + ); +} + function delegatedCompletionWakeDetail(taskIds: ReadonlyArray): string { const taskList = taskIds.join(", "); return taskIds.length === 1 @@ -685,6 +732,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const idAllocator = yield* IdAllocatorV2; const projects = yield* ProjectStore.ProjectStoreV2; const projectionStore = yield* ProjectionStoreV2; + const effectOutbox = yield* EffectOutbox.EffectOutboxV2; const nextTurnItemOrdinal = ( projection: Pick & Partial>, @@ -2188,9 +2236,66 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + // Checked under the thread lock: the watch or the thread can change while the host is read. + // The watch is recorded first so the wake's own thread events carry it. + const dispatchPullRequestWatchSync = Effect.fn("orchestrationV2.dispatch.pullRequestWatchSync")( + function* ( + command: Extract< + OrchestrationV2ServerCommand, + { readonly type: "thread.pull-request-watch.sync" } + >, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const thread = yield* projectionStore + .getThread(command.threadId) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + const key = normalizeThreadPullRequestKey(command); + const link = threadPullRequestsOf(thread).find( + (candidate) => + candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key), + ); + // Same rule as a direct message.dispatch: a provider-native subagent takes no messages. + const inactive = + thread.archivedAt !== null || + thread.settledOverride === "settled" || + thread.settledAt !== null || + isProviderNativeSubagentThread(thread); + if (link?.watch?.startedAt !== command.startedAt || (command.wake && inactive)) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The pull request watch ended or its thread settled while it was read.", + }); + } + yield* dispatchThreadMutation(command, events, effects); + if (command.wake === undefined) return; + yield* dispatchMessage( + { + type: "message.dispatch", + commandId: command.commandId, + threadId: command.threadId, + messageId: command.wake.messageId, + text: command.wake.text, + notification: command.wake.notification, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }, + events, + effects, + ); + }, + ); + const dispatchThreadMutation = Effect.fn("orchestrationV2.dispatch.threadMutation")(function* ( command: Extract< - OrchestrationV2Command, + OrchestrationV2ServerCommand, { readonly type: | "thread.archive" @@ -2209,6 +2314,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.pull-request.link" | "thread.pull-request.unlink" | "thread.pull-request-link.sync" + | "thread.pull-request.watch" + | "thread.pull-request-watch.sync" | "thread.pull-request.sync" | "thread.title.regeneration.complete" | "thread.runtime-mode.set" @@ -2236,6 +2343,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is deleted.`, }); } + if ( + command.type === "thread.pull-request.watch" && + command.watching && + isProviderNativeSubagentThread(thread) + ) { + return yield* new OrchestratorSubagentThreadReadOnlyError({ + commandId: command.commandId, + threadId: command.threadId, + }); + } if ( command.type === "thread.metadata.update" && command.expectedWorktreePath !== undefined && @@ -2719,16 +2836,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ), ...(command.linkedPullRequest - ? [ - { - ...legacyThreadPullRequestKey(command.linkedPullRequest), - url: command.linkedPullRequest.url, - source: "manual" as const, - linkedAt: DateTime.formatIso(now), - snapshot: null, - stack: null, - }, - ] + ? [legacyPullRequestLink(thread, command.linkedPullRequest, now)] : []), ], }), @@ -2801,7 +2909,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); pullRequests = belongsToStack ? links.map((link) => - link === existing ? { ...link, source: "stack-dismissed" as const } : link, + link === existing + ? { + ...withPullRequestWatch(link, undefined), + source: "stack-dismissed" as const, + } + : link, ) : links.filter((link) => link !== existing); } else { @@ -2830,6 +2943,61 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: command.type === "thread.pull-request-link.sync" ? thread.updatedAt : now, }; } + case "thread.pull-request.watch": + case "thread.pull-request-watch.sync": { + const key = normalizeThreadPullRequestKey(command); + const startedAt = DateTime.formatIso(now); + const linked = threadPullRequestsOf(thread); + const visible = (link: ThreadPullRequestLink) => + link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, key); + // A watch started on an unlinked (or dismissed) pull request links it in the same step. + const links = + command.type === "thread.pull-request.watch" && + command.watching && + command.link !== undefined && + !linked.some(visible) + ? [ + ...linked.filter((link) => !threadPullRequestKeysEqual(link, key)), + { + ...key, + url: command.link.url, + source: command.link.source, + linkedAt: startedAt, + snapshot: null, + stack: null, + }, + ] + : linked; + const existing = links.find(visible); + if (existing === undefined) return thread; + const watch = + command.type === "thread.pull-request-watch.sync" + ? // Progress read before a stop or restart must not bring the old watch back. + existing.watch?.startedAt === command.startedAt + ? (command.watch ?? undefined) + : existing.watch + : !command.watching + ? undefined + : (existing.watch ?? { + startedAt, + headSha: null, + failedChecks: [], + passed: false, + remarksThrough: startedAt, + remarkIds: [], + conflicting: false, + wakes: 0, + }); + if (watch === existing.watch && links === linked) return thread; + return { + ...thread, + pullRequests: links.map((link) => + link === existing ? withPullRequestWatch(link, watch) : link, + ), + // A user or agent starting or stopping a watch is activity; recorded progress is not. + updatedAt: command.type === "thread.pull-request.watch" ? now : thread.updatedAt, + }; + } case "thread.pull-request.sync": return { ...thread, @@ -2857,16 +3025,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ), ...(command.linkedPullRequest - ? [ - { - ...legacyThreadPullRequestKey(command.linkedPullRequest), - url: command.linkedPullRequest.url, - source: "manual" as const, - linkedAt: DateTime.formatIso(now), - snapshot: null, - stack: null, - }, - ] + ? [legacyPullRequestLink(thread, command.linkedPullRequest, now)] : []), ], }), @@ -2927,6 +3086,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": + case "thread.pull-request.watch": + case "thread.pull-request-watch.sync": case "thread.pull-request.sync": return "thread.pull-request-synced" as const; case "thread.runtime-mode.set": @@ -4211,7 +4372,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection.thread.archivedAt !== null || projection.thread.deletedAt !== null || projection.thread.providerInstanceId !== source.providerInstanceId || - projection.runs.some((run) => run.ordinal > source.ordinal) + // Held queued runs never started; they wait behind the continuation. + projection.runs.some( + (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source), + ) ) { // Preserve the current row so stale automatic deliveries receive an // accepted receipt without changing work or repeatedly retrying. @@ -6448,12 +6612,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // policy when the child terminalizes. Both writers hold this parent lock, // so a terminal task means finalize already committed the terminal row and // already made its offer decision under the pre-upgrade policy: under - // settled_only it offered iff the parent had no live run. Plan a delivery - // only when the parent has a live run now, which is precisely the case + // settled_only it offered iff the spawning run was not live. Plan a + // delivery only when that run is live now, which is precisely the case // where finalize skipped. The mailbox steers a capable active session or - // queues behind that run. When the parent is not live, finalize already - // offered and a second - // offer would wake the parent twice. (If the parent settled in between, + // queues behind that run. When that run is not live, finalize already + // offered and a second offer would wake the parent twice. (If the parent settled in between, // this skips a wake that finalize also skipped; a missed wake is cheaper // than a duplicate one, and the result is already in the projection.) const parentRun = @@ -6463,7 +6626,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const completionPlan = command.completionWake === "always" && isTerminalDelegatedTaskStatus(task.status) && - hasLiveRun(parentProjection) + parentRun !== undefined && + hasLiveRun({ runs: [parentRun] }) ? yield* planDelegatedCompletionDelivery({ parentProjection, parentRun, @@ -7962,6 +8126,63 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Run ${command.runId} is not interruptible.`, }); } + // Background work can outlive a provider switch, such as a Codex dev + // server left running when the thread moved to Claude. Stop also reaches + // each other live provider thread that owns pending work; that + // interrupt's settle follow-up ends what its provider leaves behind. + // Work on a dead session is settled with this run's below. + const otherProviderInterrupts: Array = []; + if (hasBackgroundWork) { + const runOrdinals = new Map( + projection.runs.map((candidate) => [candidate.id, candidate.ordinal]), + ); + const runOrdinalOf = (item: (typeof projection.turnItems)[number]) => + item.runId === null ? -1 : (runOrdinals.get(item.runId) ?? -1); + // Each provider thread is interrupted at its latest pending work: that + // turn's run bounds the settle follow-up, which must cover all of the + // thread's work. The target comes from the item's provider turn, since + // a native subagent item names its own provider thread but its + // parent's turn; interrupting the parent's turn reaches the subagent. + const latestTurnByProviderThread = new Map< + OrchestrationV2ProviderThread["id"], + { readonly turn: (typeof projection.providerTurns)[number]; readonly runOrdinal: number } + >(); + for (const item of pendingBackgroundTurnItems({ + turnItems: projection.turnItems, + runs: projection.runs, + })) { + const turn = projection.providerTurns.find( + (candidate) => candidate.id === item.providerTurnId, + ); + if (turn === undefined || turn.providerThreadId === providerThread.id) continue; + const runOrdinal = runOrdinalOf(item); + const latest = latestTurnByProviderThread.get(turn.providerThreadId); + if (latest === undefined || runOrdinal > latest.runOrdinal) { + latestTurnByProviderThread.set(turn.providerThreadId, { turn, runOrdinal }); + } + } + for (const { turn } of latestTurnByProviderThread.values()) { + const owner = projection.providerThreads.find( + (candidate) => candidate.id === turn.providerThreadId, + ); + if (owner === undefined || owner.providerSessionId === null) continue; + const ownerSession = yield* providerSessions + .get(owner.providerSessionId) + .pipe(Effect.orElseSucceed(() => Option.none())); + if (Option.isNone(ownerSession)) continue; + otherProviderInterrupts.push({ + id: `effect:${command.commandId}:provider-turn.interrupt:${turn.id}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-turn.interrupt", + providerSessionId: owner.providerSessionId, + providerThreadId: owner.id, + providerTurnId: turn.id, + }, + }); + } + } // Stop on a settled thread's background work. Its process may be gone // (released, restarted) and only the projection still shows the work; // the settle follow-up ends whatever no provider reports ending. @@ -7993,6 +8214,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio throughRunOrdinal: run.ordinal, now, }); + yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]); return undefined; } if (providerThread.providerSessionId === null) { @@ -8054,6 +8276,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: providerTurn.id, }, } satisfies PendingOrchestrationEffectV2, + ...otherProviderInterrupts, ]); return undefined; }); @@ -8289,6 +8512,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : undefined; }); + /** + * A run with a pending restart continuation has no outcome yet: restart + * reconciliation cancelled it mid-turn, or cancelled the background work a + * settled turn was waiting on. The continuation's own run settles it, or + * RestartContinuation recovers the thread when it declines to continue. + */ + const awaitsRestartContinuation = (run: OrchestrationV2Run) => + effectOutbox + .get(`effect:restart-continuation:${run.id}`) + .pipe( + Effect.map( + Option.exists((effect) => effect.status === "pending" || effect.status === "running"), + ), + ); + + /** + * A delegated child's result is held while its result run, or a run after it + * that a second restart cut before it started, still has a continuation pending. + */ + const childAwaitsRestartContinuation = ( + runs: ReadonlyArray, + resultRun: OrchestrationV2Run, + settledContinuationOf?: RunId, + ) => + Effect.forEach( + runs.filter( + (run) => + run.id !== settledContinuationOf && + (run.id === resultRun.id || runRanAfter(run, resultRun)), + ), + awaitsRestartContinuation, + ).pipe(Effect.map((pending) => pending.includes(true))); + const planDelegatedCompletionDelivery = Effect.fn( "orchestrationV2.planDelegatedCompletionDelivery", )(function* (input: { @@ -8336,9 +8592,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio offer: false, }; } + // settled_only defers to a blocking delegate_task wait, which lives only as + // long as the turn that spawned the task. Once that turn is over (a restart + // continues it as a new run), nothing else delivers the result. if ( (input.task.completionWake ?? "settled_only") === "settled_only" && - hasLiveRun(input.parentProjection) + hasLiveRun({ runs: [input.parentRun] }) ) { return { task: input.updatedTask, @@ -8489,9 +8748,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio * delegated_task.wake-policy handler rewrites the same subagent row under * that lock with a full-row payload, and unserialized writers clobber each * other (stale policy on the terminal row, or a terminal row regressed to - * running). + * running). `settledContinuationOf` names the restart continuation that just + * declined or failed, so its own still-running effect does not hold the child. */ - const finalizeAppOwnedSubagent = (childThreadId: ThreadId) => + const finalizeAppOwnedSubagent = ( + childThreadId: ThreadId, + options?: { readonly settledContinuationOf?: RunId }, + ) => Effect.gen(function* () { const childControls = yield* projectionStore.getThreadRecords( childThreadId, @@ -8514,6 +8777,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (terminalStatus === null) { return; } + if ( + yield* childAwaitsRestartContinuation( + childControls.runs, + childRun, + options?.settledContinuationOf, + ) + ) { + return; + } const childResult = yield* projectionStore.getThreadRecords( childThreadId, @@ -8942,7 +9214,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); return; } - const parentIsLive = hasLiveRun(projection); + // settled_only tasks defer only to a blocking wait in their spawning run. + const parentIsLive = hasLiveRun({ runs: [parentRun] }); const pendingTaskIds = projection.thread.archivedAt === null && projection.thread.deletedAt === null ? projection.subagents @@ -9130,6 +9403,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": + case "thread.pull-request.watch": case "thread.pull-request.sync": case "thread.title.regeneration.complete": case "thread.runtime-mode.set": @@ -9138,6 +9412,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "provider.switch": yield* dispatchThreadMutation(command, events, effects); break; + case "thread.pull-request-watch.sync": + yield* dispatchPullRequestWatchSync(command, events, effects); + break; case "provider-session.detach": yield* dispatchProviderSessionDetach(command, events, effects); break; @@ -9540,97 +9817,140 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.forkDetach, ); - // Recover child results from projections. Queue recovery instead holds - // unstarted runs until an explicit queue.resume command arrives. - yield* projectionStore.getRecoveryThreadIds("subagent-results").pipe( - Effect.flatMap((threadIds) => - Effect.forEach( - threadIds, - (threadId) => - Effect.gen(function* () { - const thread = yield* projectionStore.getThreadShell(threadId); - const parentThreadId = thread?.lineage.parentThreadId; - if (parentThreadId === undefined || parentThreadId === null) return; - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId)); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to recover terminal app-owned subagent", { - childThreadId: threadId, - cause, - }), - ), - ), - { concurrency: 8, discard: true }, - ), - ), - Effect.catchCause((cause) => - Effect.logWarning("Failed to inspect app-owned subagents during recovery", { - cause, - }), - ), - ); - yield* projectionStore.getRecoveryThreadIds("delegated-completions").pipe( - Effect.flatMap((threadIds) => - Effect.forEach( - threadIds, - (threadId) => - threadDispatch - .withLock( - threadId, - Effect.gen(function* () { - const projection = yield* projectionStore.getThreadRecords(threadId, [ - "runs", - "messages", - ]); - const terminalDeliveryRunIds = projection.runs - .filter((run) => delegatedTaskTerminalStatus(run.status) !== null) - .filter((run) => - projection.messages.some( - (message) => - message.id === run.userMessageId && - message.delegatedCompletion !== undefined, - ), - ) - .map((run) => run.id); - for (const runId of terminalDeliveryRunIds) { - yield* finalizeDelegatedCompletionDelivery(threadId, runId); - } - const refreshed = - terminalDeliveryRunIds.length === 0 - ? projection - : yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], { - messageRoles: ["user"], - }); - for (const run of refreshed.runs) { - if ( - run.delegatedCompletion?.delivery !== null && - run.delegatedCompletion !== undefined - ) { - yield* offerDelegatedCompletionDelivery(threadId, run.id); - } - } - }), - ) - .pipe( + // Settles child results and completion deliveries whose runs ended without + // the listener above: before this boot, or in runtime reconciliation, which + // it skips. Startup runs this after reconciliation and before the effect + // worker. Queue recovery instead holds unstarted runs until an explicit + // queue.resume command arrives. + const recoverDelegatedTasks = Effect.gen(function* () { + yield* projectionStore.getRecoveryThreadIds("subagent-results").pipe( + Effect.flatMap((threadIds) => + Effect.forEach( + threadIds, + (threadId) => + Effect.gen(function* () { + const thread = yield* projectionStore.getThreadShell(threadId); + const parentThreadId = thread?.lineage.parentThreadId; + if (parentThreadId === undefined || parentThreadId === null) return; + yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId)); + }).pipe( Effect.catchCause((cause) => - Effect.logWarning("Failed to recover delegated completion delivery", { - threadId, + Effect.logWarning("Failed to recover terminal app-owned subagent", { + childThreadId: threadId, cause, }), ), ), - { concurrency: 8, discard: true }, + { concurrency: 8, discard: true }, + ), ), - ), - Effect.catchCause((cause) => - Effect.logWarning("Failed to inspect delegated completion delivery during recovery", { - cause, - }), - ), - ); + Effect.catchCause((cause) => + Effect.logWarning("Failed to inspect app-owned subagents during recovery", { + cause, + }), + ), + ); + yield* projectionStore.getRecoveryThreadIds("delegated-completions").pipe( + Effect.flatMap((threadIds) => + Effect.forEach( + threadIds, + (threadId) => + threadDispatch + .withLock( + threadId, + Effect.gen(function* () { + const projection = yield* projectionStore.getThreadRecords(threadId, [ + "runs", + "messages", + ]); + const terminalDeliveryRunIds = projection.runs + .filter((run) => delegatedTaskTerminalStatus(run.status) !== null) + .filter((run) => + projection.messages.some( + (message) => + message.id === run.userMessageId && + message.delegatedCompletion !== undefined, + ), + ) + .map((run) => run.id); + for (const runId of terminalDeliveryRunIds) { + yield* finalizeDelegatedCompletionDelivery(threadId, runId); + } + const refreshed = + terminalDeliveryRunIds.length === 0 + ? projection + : yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], { + messageRoles: ["user"], + }); + for (const run of refreshed.runs) { + if ( + run.delegatedCompletion?.delivery !== null && + run.delegatedCompletion !== undefined + ) { + yield* offerDelegatedCompletionDelivery(threadId, run.id); + } + } + }), + ) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to recover delegated completion delivery", { + threadId, + cause, + }), + ), + ), + { concurrency: 8, discard: true }, + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Failed to inspect delegated completion delivery during recovery", { + cause, + }), + ), + ); + }); + + const delegatedTaskResultPending = (childThreadId: ThreadId) => + Effect.gen(function* () { + const child = yield* projectionStore.getThreadRecords( + childThreadId, + ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"], + { messageRoles: ["user"] }, + ); + const progress = delegatedTaskProgress(child); + // A caller's older read saw a result; newer work since then means it is not final. + if (progress.state !== "result_available") return true; + if (progress.resultRun === undefined) return false; + return yield* childAwaitsRestartContinuation(child.runs, progress.resultRun); + }).pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }), + ), + ); + + const recoverDelegatedTask = (threadId: ThreadId, sourceRunId: RunId) => + Effect.gen(function* () { + const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); + if (parentThreadId === undefined) return; + yield* threadDispatch.withLock( + parentThreadId, + finalizeAppOwnedSubagent(threadId, { settledContinuationOf: sourceRunId }), + ); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to recover delegated task after restart", { + childThreadId: threadId, + cause, + }), + ), + ); return OrchestratorV2.of({ resumeQueuedRuns, + recoverDelegatedTasks, + recoverDelegatedTask, + delegatedTaskResultPending, dispatch: dispatchWithReceipt, getTimelinePage: (threadId, options) => projectionStore @@ -9724,6 +10044,7 @@ export const layer: Layer.Layer< | CommandPolicyV2 | CommandReceiptStoreV2 | ContextHandoffServiceV2 + | EffectOutbox.EffectOutboxV2 | EventSinkV2 | IdAllocatorV2 | ProjectStore.ProjectStoreV2 @@ -9747,6 +10068,9 @@ const layerUnavailable: Layer.Layer = Layer.succeed( cause: "Orchestration V2 live runtime is not configured.", }), ), + recoverDelegatedTasks: Effect.void, + recoverDelegatedTask: () => Effect.void, + delegatedTaskResultPending: () => Effect.succeed(false), dispatch: (command) => Effect.fail( new OrchestratorDispatchError({ diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 8db18a0d5f08..617655e38fb1 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -420,6 +420,73 @@ it.effect("includes shared sessions and provider-owned background rosters in rec }).pipe(Effect.provide(TestLayer)), ); +it.effect("reads the run that owns a background roster, not a queued or resumed one", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const withRoster = Effect.fn(function* (threadId: ThreadId) { + yield* projections.apply({ + id: EventId.make(`event:${threadId}:roster`), + type: "provider-thread.updated", + threadId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: ProviderThreadId.make(`provider-thread:${threadId}`), + appThreadId: threadId, + ownerNodeId: null, + driver, + providerInstanceId, + providerSessionId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: [ + { taskId: "background", description: "Still running", kind: "command" }, + ], + }, + }); + }); + const runIds = (threadId: ThreadId) => + projections + .getRuntimeRecoveryProjection(threadId) + .pipe(Effect.map((state) => state.runs.map((run) => run.id))); + // Settled with background work left, then a queued follow-up. + const settled = yield* createThread("roster-before-queue"); + const settledRun = yield* createRun(settled, "completed", { + providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`), + }); + const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null }); + yield* withRoster(settled); + assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]); + // A resumed queued run (ordinal 1) ended after a continuation (ordinal 2). + const resumed = yield* createThread("roster-after-resume"); + const resumedRun = yield* createRun(resumed, "completed", { + providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`), + completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"), + }); + const continuationRun = yield* createRun(resumed, "completed", { + providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`), + ordinal: 2, + completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"), + }); + yield* withRoster(resumed); + assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]); + // Without a roster, settled history is not read. + const quiet = yield* createThread("no-roster-before-queue"); + yield* createRun(quiet, "completed"); + const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null }); + assert.deepEqual(yield* runIds(quiet), [quietQueued]); + }).pipe(Effect.provide(TestLayer)), +); + it.effect("marks fork descendants unreadable when their source is missing or corrupt", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 60149fe8a292..1e8297c362c2 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -247,7 +247,7 @@ it.effect.each([ forkedFrom: null, createdAt: old, updatedAt: old, - pendingBackgroundTasks: [{ taskId: "running-task", kind: "command" }], + pendingBackgroundTasks: [{ taskId: "running-task", kind: "subagent" }], }, }); const candidates = yield* store.getSettlementCandidates(); @@ -278,7 +278,13 @@ it.effect.each([ }; assert.deepEqual( resolveAutoSettlementAt({ ...settings, thread: candidate }), - resolveAutoSettlementAt({ ...settings, thread: expected }), + resolveAutoSettlementAt({ + ...settings, + thread: { + ...expected, + latestUserAuthoredMessageAt: candidate.latestUserAuthoredMessageAt, + }, + }), ); } assert.equal( @@ -292,6 +298,54 @@ it.effect.each([ }).pipe(Effect.provide(testLayer)), ); +it.effect.each([ + ["sql", SqlLayer], + ["memory", ProjectionStore.layerMemory], +] as const)("%s: the user-authored message time ignores agent notifications", ([, testLayer]) => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* createThread("agent-woken"); + yield* createRun(threadId); + const message = ( + id: string, + createdBy: "user" | "agent", + creationSource: "web" | "provider", + at: DateTime.Utc, + ) => + store.apply({ + id: EventId.make(`event:settlement:${id}`), + type: "message.updated", + threadId, + occurredAt: at, + payload: { + createdBy, + creationSource, + id: MessageId.make(`message:settlement:${id}`), + threadId, + runId: null, + nodeId: null, + role: "user", + text: id, + attachments: [], + streaming: false, + createdAt: at, + updatedAt: at, + }, + }); + const written = DateTime.subtract(now, { hours: 2 }); + yield* message("written", "user", "web", written); + yield* message("notification", "agent", "provider", now); + + const [candidate] = yield* store.getSettlementCandidates(threadId); + assert.isDefined(candidate); + assert.equal(DateTime.formatIso(candidate.latestUserMessageAt!), DateTime.formatIso(now)); + assert.equal( + DateTime.formatIso(candidate.latestUserAuthoredMessageAt!), + DateTime.formatIso(written), + ); + }).pipe(Effect.provide(testLayer)), +); + const pullRequestLink = (number: number) => ({ host: "github.com", repository: "owner/repository", diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index c64fece9db07..3e979544c87b 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1377,6 +1377,36 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { (row) => row.sourceItemId === interruptResultId, ), ); + + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET payload_json = json_set(payload_json, '$.createdBy', 'agent') + WHERE thread_id = ${threadId} AND type = 'user_message' + `; + const agentPromptId = TurnItemId.make("turn-item:bounded-sql-history:interrupt-filler:1281"); + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET type = 'user_message', + payload_json = json_set(payload_json, + '$.type', 'user_message', '$.inputIntent', 'turn_start', + '$.createdBy', 'agent', '$.creationSource', 'provider', + '$.messageId', 'message:bounded-sql-history:agent-prompt', + '$.text', 'Continue the child task', '$.attachments', json('[]')) + WHERE turn_item_id = ${agentPromptId} + `; + const agentWindow = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns, + }); + assert.lengthOf( + agentWindow.projection.visibleTurnItems.filter( + (row) => row.item.type !== "run_interrupt_request", + ), + sqlPageLimit, + ); + assert.isTrue( + agentWindow.projection.visibleTurnItems.some((row) => row.sourceItemId === agentPromptId), + ); }), ); @@ -2276,8 +2306,33 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { }, }); yield* assertSummary("Plan limit reached.", "usage_limit"); + // A restart continuation ran ahead of the held queue and ended before the + // resumed failed run: the failure is still the latest executed run. + const aheadRunId = RunId.make("run:limit-shell:ran-ahead"); + yield* store.apply({ + id: EventId.make("event:limit-shell:ran-ahead"), + type: "run.created", + threadId, + runId: aheadRunId, + nodeId: NodeId.make("node:limit-shell:ran-ahead"), + driver, + providerInstanceId, + occurredAt: now, + payload: { + ...original, + id: aheadRunId, + ordinal: original.ordinal + 3, + rootNodeId: NodeId.make("node:limit-shell:ran-ahead"), + userMessageId: MessageId.make("message:limit-shell:ran-ahead"), + status: "completed", + startedAt: DateTime.subtract(now, { minutes: 10 }), + completedAt: DateTime.subtract(now, { minutes: 5 }), + }, + }); + yield* assertSummary("Plan limit reached.", "usage_limit"); const sql = yield* SqlClient.SqlClient; // The rest of this case treats the failed run as the latest run. + yield* sql`DELETE FROM orchestration_v2_projection_runs WHERE run_id = ${aheadRunId}`; yield* sql`DELETE FROM orchestration_v2_projection_runs WHERE run_id = ${queuedRunId}`; yield* assertSummary("Plan limit reached.", "usage_limit"); yield* sql`DELETE FROM orchestration_v2_projection_runs WHERE run_id = ${cancelledRunId}`; @@ -4372,6 +4427,36 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { released && projectThreadAwarenessV2({ environmentId, project, thread: released }); assert.equal(state?.phase, "completed"); assert.equal(state?.updatedAt, DateTime.formatIso(releasedAt)); + + // A later provider must not hide this owner's roster from restart recovery. + yield* store.apply({ + id: EventId.make("event:held-completion:monitor-restarted"), + type: "provider-thread.updated", + threadId, + occurredAt: releasedAt, + payload: { ...providerThread, updatedAt: releasedAt }, + }); + const newerRunId = RunId.make("run:held-completion:new-provider"); + yield* store.apply({ + id: EventId.make("event:held-completion:new-provider"), + type: "run.created", + threadId, + runId: newerRunId, + occurredAt: releasedAt, + payload: { + ...(yield* store.getThreadProjection(threadId)).runs[0]!, + id: newerRunId, + ordinal: 2, + providerThreadId: ProviderThreadId.make("provider-thread:held-completion:new-provider"), + requestedAt: releasedAt, + startedAt: releasedAt, + completedAt: releasedAt, + }, + }); + assert.deepEqual( + (yield* store.getRuntimeRecoveryProjection(threadId)).runs.map((run) => run.id), + [runId, newerRunId], + ); }), ); }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ac0624b05806..a1b2e0f061f1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -159,7 +159,13 @@ export type ProjectionThreadPullRequests = Pick< "id" | "projectId" | "settledOverride" | "settledAt" | "pullRequests" >; -/** Thread activity needed by settlement, without transcript or fork history. */ +/** + * Thread activity needed by settlement, without transcript or fork history. + * `latestUserAuthoredMessageAt` is the last message the user wrote. Agent, + * provider, and server notifications also use the user role, so + * `latestUserMessageAt` moves when background work or a PR watch wakes the + * agent. + */ export type ProjectionSettlementCandidate = Pick< OrchestrationV2ThreadShell, | "id" @@ -187,7 +193,7 @@ export type ProjectionSettlementCandidate = Pick< | "activityRunStatus" | "pendingRuntimeRequest" | "pendingBackgroundTasks" ->; +> & { readonly latestUserAuthoredMessageAt: DateTime.Utc | null }; const ProjectionCheckpointContext = Schema.Struct({ runs: Schema.Array( @@ -516,8 +522,10 @@ function needsRecovery( } case "runtime": return ( - projection.runs.some((run) => - ["queued", "preparing", "starting", "running", "waiting"].includes(run.status), + projection.runs.some( + (run) => + ["preparing", "starting", "running", "waiting"].includes(run.status) || + (run.status === "queued" && run.queueHeld !== true), ) || projection.runtimeRequests.some((request) => request.status === "pending") || projection.providerSessions.some( @@ -930,7 +938,7 @@ type SettlementThreadRow = Pick< | "latest_run_started_at" | "latest_run_completed_at" | "latest_user_message_at" ->; +> & { readonly latest_user_authored_message_at: string | null }; type ShellRunItemCountRow = { readonly thread_id: string; @@ -2668,7 +2676,7 @@ export const layer: Layer.Layer = WHEN (SELECT COUNT(*) FROM turn_anchors) >= ${THREAD_HISTORY_MAX_RAW_TURNS + 2} THEN (SELECT MIN(ordinal) FROM turn_anchors) ELSE 0 - END AS ordinal, (SELECT COUNT(*) FROM turn_anchors) AS anchors + END AS ordinal FROM user_anchors ), selected AS ( SELECT payload_json, ordinal, turn_item_id, run_id, type @@ -2677,7 +2685,7 @@ export const layer: Layer.Layer = ORDER BY ordinal DESC, turn_item_id DESC LIMIT CASE WHEN ${window.rowLimit} = 0 THEN 0 - WHEN (SELECT anchors FROM boundary) > 0 THEN -1 + WHEN (SELECT COUNT(*) FROM user_anchors) > 0 THEN -1 ELSE ${window.rowLimit} END ), retained AS ( @@ -3157,7 +3165,7 @@ export const layer: Layer.Layer = localWindow !== undefined && localWindow.rowLimit > 0 && projection.turnItems.length >= localWindow.rowLimit && - !projection.turnItems.some(isThreadHistoryTurnStart) + !projection.turnItems.some(isThreadHistoryUserTurn) ) { return withLocalVisibleTurnItems(projection); } @@ -3301,7 +3309,10 @@ export const layer: Layer.Layer = latest.status = 'cancelled' AND json_extract(latest.payload_json, '$.startedAt') IS NULL ) - ORDER BY latest.ordinal DESC, latest.run_id DESC LIMIT 1 + -- latestExecutedRun: the run that ended last (runRanAfter). + ORDER BY latest.completed_at IS NULL DESC, latest.completed_at DESC, + latest.ordinal DESC, latest.run_id DESC + LIMIT 1 ) AND r.status = 'failed' INNER JOIN orchestration_v2_projection_turn_items item ON item.turn_item_id = ( SELECT error.turn_item_id FROM orchestration_v2_projection_turn_items error @@ -3427,7 +3438,15 @@ export const layer: Layer.Layer = ELSE 0 END ) SELECT thread_id FROM orchestration_v2_projection_runs - WHERE status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + WHERE status IN ('preparing', 'starting', 'running', 'waiting') + UNION + -- A held queue already went through recovery; rereading it on + -- every boot costs a projection read per held thread. + SELECT thread_id FROM orchestration_v2_projection_runs + WHERE status = 'queued' + AND CASE WHEN json_valid(payload_json) + THEN json_extract(payload_json, '$.queueHeld') IS NOT 1 + ELSE 1 END UNION SELECT thread_id FROM orchestration_v2_projection_runtime_requests WHERE status = 'pending' @@ -3799,6 +3818,24 @@ export const layer: Layer.Layer = WHERE latest.thread_id = ${threadId} ORDER BY latest.ordinal DESC LIMIT 1 ) + -- Retain the latest run for each provider thread with lost + -- background work, including owners used before a handoff. + OR run.run_id IN ( + SELECT ( + SELECT ended.run_id FROM orchestration_v2_projection_runs AS ended + WHERE ended.thread_id = ${threadId} + AND ended.provider_thread_id = roster.provider_thread_id + AND ended.status NOT IN ('queued', 'rolled_back') + ORDER BY ended.completed_at IS NULL DESC, ended.completed_at DESC, + ended.ordinal DESC + LIMIT 1 + ) + FROM orchestration_v2_projection_provider_threads AS roster + WHERE roster.thread_id = ${threadId} + AND CASE WHEN json_valid(roster.payload_json) + THEN json_array_length(roster.payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END + ) OR run.run_id IN ( SELECT item.run_id FROM orchestration_v2_projection_turn_items AS item WHERE item.thread_id = ${threadId} @@ -4893,7 +4930,10 @@ export const layer: Layer.Layer = candidate.status = 'cancelled' AND json_extract(candidate.payload_json, '$.startedAt') IS NULL ) - ORDER BY candidate.ordinal DESC, candidate.run_id DESC LIMIT 1 + -- latestExecutedRun: the run that ended last (runRanAfter). + ORDER BY candidate.completed_at IS NULL DESC, candidate.completed_at DESC, + candidate.ordinal DESC, candidate.run_id DESC + LIMIT 1 ) AND blocked.status = 'failed' WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`}${ location === "active" @@ -5051,7 +5091,15 @@ export const layer: Layer.Layer = WHERE message.thread_id = t.thread_id AND message.role = 'user' ORDER BY message.updated_at DESC, message.message_id DESC LIMIT 1 - ) AS latest_user_message_at + ) AS latest_user_message_at, + ( + SELECT message.updated_at + FROM orchestration_v2_projection_messages message + WHERE message.thread_id = t.thread_id AND message.role = 'user' + AND json_extract(message.payload_json, '$.createdBy') = 'user' + ORDER BY message.updated_at DESC, message.message_id DESC + LIMIT 1 + ) AS latest_user_authored_message_at FROM orchestration_v2_projection_threads t LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = ( SELECT latest.run_id FROM orchestration_v2_projection_runs latest @@ -5113,6 +5161,10 @@ export const layer: Layer.Layer = row.latest_user_message_at === null ? null : DateTime.makeUnsafe(row.latest_user_message_at), + latestUserAuthoredMessageAt: + row.latest_user_authored_message_at === null + ? null + : DateTime.makeUnsafe(row.latest_user_authored_message_at), activityRunStatus: null, activityRunStartedAt: null, pendingRuntimeRequest: null, @@ -5578,7 +5630,16 @@ export const layerMemory: Layer.Layer = Layer.effect( !runs.some(isActivityRunForShell) && !runtimeRequests.some((request) => request.status === "pending"), ) - .map(threadShellFromProjection) + .map((projection) => ({ + ...threadShellFromProjection(projection), + latestUserAuthoredMessageAt: + projection.messages + .filter((message) => message.role === "user" && message.createdBy === "user") + .map((message) => message.updatedAt) + .toSorted( + (left, right) => DateTime.toEpochMillis(right) - DateTime.toEpochMillis(left), + )[0] ?? null, + })) .toSorted( (left, right) => DateTime.toEpochMillis(left.updatedAt) - DateTime.toEpochMillis(right.updatedAt) || @@ -6058,7 +6119,7 @@ export const layerMemory: Layer.Layer = Layer.effect( ); const anchorLimit = (options.userTurnLimit ?? 0) + 2; const start = - turnAnchors.length > 0 + anchors.length > 0 ? anchors.length < anchorLimit ? rawStart : anchors.at(-anchorLimit)! diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryPerformance.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryPerformance.test.ts new file mode 100644 index 000000000000..b000351508aa --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryPerformance.test.ts @@ -0,0 +1,510 @@ +import { assert, it } from "@effect/vitest"; +import { + CheckpointScopeId, + CommandId, + EventId, + MessageId, + NodeId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as EventSink from "./EventSink.ts"; +import * as EventStore from "./EventStore.ts"; +import * as IdAllocator from "./IdAllocator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; + +// Startup recovery cost for restart continuation. The default case is small +// enough for CI and asserts correctness; T3_BENCH_RECOVERY=1 adds the matrix. +// `it.live` keeps a real clock: each reconcile gets a fresh command id, so the +// second recover cannot hide behind command receipt dedup. + +const stores = Layer.mergeAll( + EventStore.layer, + ProjectionStore.layer, + EffectOutbox.layer, + IdAllocator.layer, +).pipe(Layer.provideMerge(SqlitePersistenceMemory)); +const TestLayer = ProviderRuntimeRecovery.layer.pipe( + Layer.provideMerge(EventSink.layer.pipe(Layer.provideMerge(stores))), + Layer.provideMerge(ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true })), +); + +const providerInstanceId = ProviderInstanceId.make("codex"); +const driver = ProviderDriverKind.make("codex"); +const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" }; +const projectId = ProjectId.make("project:recovery-bench"); +const ITEMS_PER_SETTLED_THREAD = 10; +const OPEN_ITEMS_PER_ACTIVE_THREAD = 3; +const WAITING_THREADS = 3; +const SEED_BATCH = 500; + +type UnstampedEvent = OrchestrationV2DomainEvent extends infer Event + ? Event extends OrchestrationV2DomainEvent + ? Omit + : never + : never; + +interface Scenario { + readonly settled: number; + readonly active: number; +} + +interface Seeded { + readonly unheldQueuedThreads: number; + readonly waitingThreads: number; +} + +const seedScenario = Effect.fn(function* (scenario: Scenario) { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + let eventIndex = 0; + const apply = (event: UnstampedEvent) => + projections.apply({ + ...event, + id: EventId.make(`event:bench:${eventIndex++}`), + occurredAt: now, + } as OrchestrationV2DomainEvent); + + const thread = (id: ThreadId, overrides: Partial = {}) => + apply({ + type: "thread.created", + threadId: id, + payload: { + createdBy: "user", + creationSource: "web", + id, + projectId, + title: id, + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + ...overrides, + }, + }); + + const run = ( + threadId: ThreadId, + ordinal: number, + status: OrchestrationV2Run["status"], + overrides: Partial = {}, + ) => { + const runId = RunId.make(`run:${threadId}:${ordinal}`); + return apply({ + type: "run.created", + threadId, + runId, + payload: { + id: runId, + threadId, + ordinal, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make(`message:${runId}`), + rootNodeId: null, + activeAttemptId: null, + status, + requestedAt: now, + startedAt: status === "queued" ? null : now, + completedAt: status === "completed" ? now : null, + checkpointId: null, + contextHandoffId: null, + ...overrides, + }, + }).pipe(Effect.as(runId)); + }; + + const commandItem = (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly ordinal: number; + readonly status: "running" | "completed"; + readonly nodeId?: NodeId; + readonly providerThreadId?: ProviderThreadId; + readonly providerTurnId?: ProviderTurnId; + }) => + apply({ + type: "turn-item.updated", + threadId: input.threadId, + runId: input.runId, + payload: { + id: TurnItemId.make(`item:${input.runId}:${input.ordinal}`), + threadId: input.threadId, + runId: input.runId, + nodeId: input.nodeId ?? null, + providerThreadId: input.providerThreadId ?? null, + providerTurnId: input.providerTurnId ?? null, + nativeItemRef: null, + parentItemId: null, + ordinal: input.ordinal, + type: "command_execution", + status: input.status, + title: `Command ${input.ordinal}`, + input: `echo ${input.ordinal}`, + output: input.status === "completed" ? `${input.ordinal}\n` : "", + ...(input.status === "completed" ? { exitCode: 0 } : {}), + startedAt: now, + completedAt: input.status === "completed" ? now : null, + updatedAt: now, + }, + }); + + const settledThread = Effect.fn(function* (index: number) { + const threadId = ThreadId.make(`thread:bench:settled:${index}`); + yield* thread(threadId); + const runId = yield* run(threadId, 1, "completed"); + for (let ordinal = 1; ordinal <= ITEMS_PER_SETTLED_THREAD; ordinal += 1) { + yield* commandItem({ threadId, runId, ordinal, status: "completed" }); + } + // ~5% of threads carry a queued follow-up; half are already held, and an + // earlier recovery already handled those, so only unheld ones are candidates. + if (index % 20 === 0) { + const queueHeld = index % 40 === 0; + yield* run(threadId, 2, "queued", { queueHeld }); + return !queueHeld; + } + return false; + }); + + const activeThread = Effect.fn(function* (index: number) { + const threadId = ThreadId.make(`thread:bench:active:${index}`); + const providerSessionId = ProviderSessionId.make(`session:bench:${index}`); + const providerThreadId = ProviderThreadId.make(`provider-thread:bench:${index}`); + const runId = RunId.make(`run:${threadId}:1`); + const attemptId = RunAttemptId.make(`attempt:bench:${index}`); + const nodeId = NodeId.make(`node:bench:${index}`); + const providerTurnId = ProviderTurnId.make(`provider-turn:bench:${index}`); + yield* thread(threadId, { activeProviderThreadId: providerThreadId }); + yield* apply({ + type: "provider-session.attached", + threadId, + driver, + providerInstanceId, + payload: { + id: providerSessionId, + driver, + providerInstanceId, + status: "ready", + cwd: "/workspace", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }); + yield* apply({ + type: "provider-thread.updated", + threadId, + driver, + providerInstanceId, + payload: { + id: providerThreadId, + appThreadId: threadId, + ownerNodeId: null, + driver, + providerInstanceId, + providerSessionId, + nativeThreadRef: { driver, nativeId: `native:bench:${index}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "active", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: [], + }, + }); + yield* run(threadId, 1, "running", { + providerThreadId, + rootNodeId: nodeId, + activeAttemptId: attemptId, + }); + yield* apply({ + type: "run-attempt.created", + threadId, + runId, + payload: { + id: attemptId, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId, + providerTurnId, + reason: "initial", + status: "running", + startedAt: now, + completedAt: null, + }, + }); + yield* apply({ + type: "node.updated", + threadId, + runId, + nodeId, + providerInstanceId, + payload: { + id: nodeId, + threadId, + runId, + parentNodeId: null, + rootNodeId: nodeId, + kind: "root_turn", + status: "running", + countsForRun: true, + providerThreadId, + providerTurnId, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + }); + yield* apply({ + type: "provider-turn.updated", + threadId, + runId, + nodeId, + providerInstanceId, + payload: { + id: providerTurnId, + providerThreadId, + nodeId, + runAttemptId: attemptId, + nativeTurnRef: { driver, nativeId: `native-turn:bench:${index}`, strength: "strong" }, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + for (let ordinal = 1; ordinal <= OPEN_ITEMS_PER_ACTIVE_THREAD; ordinal += 1) { + yield* commandItem({ + threadId, + runId, + ordinal, + status: "running", + nodeId, + providerThreadId, + providerTurnId, + }); + } + }); + + const waitingThread = Effect.fn(function* (index: number) { + const threadId = ThreadId.make(`thread:bench:waiting:${index}`); + yield* thread(threadId); + yield* run(threadId, 1, "completed"); + const runId = yield* run(threadId, 2, "waiting"); + yield* outbox.enqueue([ + { + id: `effect:bench:checkpoint:${runId}`, + commandId: CommandId.make(`command:effect:checkpoint.capture:${runId}`), + threadId, + request: { + type: "checkpoint.capture", + runId, + scopeId: CheckpointScopeId.make(`scope:bench:${index}`), + }, + }, + ]); + }); + + let unheldQueuedThreads = 0; + for (let start = 0; start < scenario.settled; start += SEED_BATCH) { + const end = Math.min(scenario.settled, start + SEED_BATCH); + yield* sql.withTransaction( + Effect.gen(function* () { + for (let index = start; index < end; index += 1) { + if (yield* settledThread(index)) unheldQueuedThreads += 1; + } + }), + ); + } + yield* sql.withTransaction( + Effect.gen(function* () { + for (let index = 0; index < scenario.active; index += 1) yield* activeThread(index); + for (let index = 0; index < WAITING_THREADS; index += 1) yield* waitingThread(index); + }), + ); + return { unheldQueuedThreads, waitingThreads: WAITING_THREADS } satisfies Seeded; +}); + +const timed = (effect: Effect.Effect) => + Effect.gen(function* () { + const start = performance.now(); + const value = yield* effect; + return [value, performance.now() - start] as const; + }); + +const continuationEffectCount = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE 'effect:restart-continuation:%' AND status = 'pending' + `; + return Number(rows[0]?.count ?? 0); +}); + +interface Measurement { + readonly settled: number; + readonly active: number; + readonly seedMs: number; + readonly candidates: number; + readonly selectMs: number; + readonly prepareMs: number; + readonly shutdownMs: number; + readonly startupAfterShutdownMs: number; + readonly crashRecoverMs: number; + readonly secondRecoverMs: number; +} + +/** A graceful restart: prepare intent, reconcile on shutdown, recover on boot. */ +const measureGraceful = Effect.fn(function* (scenario: Scenario) { + const [seeded, seedMs] = yield* timed(seedScenario(scenario)); + const projections = yield* ProjectionStore.ProjectionStoreV2; + const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const [candidates, selectMs] = yield* timed(projections.getRecoveryThreadIds("runtime")); + assert.equal( + candidates.length, + scenario.active + seeded.unheldQueuedThreads + seeded.waitingThreads, + "runtime recovery candidates", + ); + const [, prepareMs] = yield* timed(recovery.prepareForShutdown); + assert.equal(yield* continuationEffectCount, scenario.active, "prepared continuations"); + const [, shutdownMs] = yield* timed(recovery.reconcile("shutdown")); + const [, startupAfterShutdownMs] = yield* timed(recovery.recover); + assert.equal(yield* continuationEffectCount, scenario.active, "continuations after boot"); + return { + seedMs, + candidates: candidates.length, + selectMs, + prepareMs, + shutdownMs, + startupAfterShutdownMs, + }; +}); + +/** A crash: no shutdown hook ran, so boot recovery records the continuations. */ +const measureCrash = Effect.fn(function* (scenario: Scenario) { + yield* seedScenario(scenario); + const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const [summary, crashRecoverMs] = yield* timed(recovery.recover); + assert.equal(summary.terminalizedRuns, scenario.active, "terminalized active runs"); + assert.equal(summary.stoppedSessions, scenario.active, "stopped active sessions"); + assert.equal(yield* continuationEffectCount, scenario.active, "recorded continuations"); + const [, secondRecoverMs] = yield* timed(recovery.recover); + assert.equal(yield* continuationEffectCount, scenario.active, "second recover is idempotent"); + return { crashRecoverMs, secondRecoverMs }; +}); + +const measure = Effect.fn(function* (scenario: Scenario) { + const graceful = yield* measureGraceful(scenario).pipe(Effect.provide(Layer.fresh(TestLayer))); + const crash = yield* measureCrash(scenario).pipe(Effect.provide(Layer.fresh(TestLayer))); + return { ...scenario, ...graceful, ...crash } satisfies Measurement; +}); + +const formatTable = (rows: ReadonlyArray) => { + const ms = (value: number) => value.toFixed(1); + const perActive = (value: number, active: number) => (value / Math.max(active, 1)).toFixed(2); + const header = [ + "N", + "A", + "seed", + "cand", + "select", + "prepare", + "prep/A", + "shutdown", + "boot-after", + "crash-recover", + "recover/A", + "recover-2", + ]; + const lines = rows.map((row) => [ + String(row.settled), + String(row.active), + ms(row.seedMs), + String(row.candidates), + ms(row.selectMs), + ms(row.prepareMs), + perActive(row.prepareMs, row.active), + ms(row.shutdownMs), + ms(row.startupAfterShutdownMs), + ms(row.crashRecoverMs), + perActive(row.crashRecoverMs, row.active), + ms(row.secondRecoverMs), + ]); + const widths = header.map((cell, column) => + Math.max(cell.length, ...lines.map((line) => line[column]!.length)), + ); + return [header, ...lines] + .map((line) => line.map((cell, column) => cell.padStart(widths[column]!)).join(" ")) + .join("\n"); +}; + +it.live( + "restart recovery records one continuation per active thread and is idempotent", + () => + Effect.gen(function* () { + const row = yield* measure({ settled: 500, active: 20 }); + yield* Console.log(`provider runtime recovery (ms)\n${formatTable([row])}`); + }), + 60_000, +); + +it.live.skipIf(process.env.T3_BENCH_RECOVERY !== "1")( + "restart recovery scales with active threads, not settled history", + () => + Effect.gen(function* () { + const rows: Array = []; + for (const settled of [5_000, 50_000]) { + for (const active of [10, 100, 1_000]) { + rows.push(yield* measure({ settled, active })); + yield* Console.log(`provider runtime recovery (ms)\n${formatTable(rows)}`); + } + } + }), + 3_600_000, +); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index 8df85818a761..b36239de290d 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -1272,3 +1272,151 @@ it.effect( }).pipe(Effect.provide(layer)); }, ); + +it.effect("leaves delegated tasks to their own child threads after process loss", () => { + const threadId = ThreadId.make("thread_recovery_delegation"); + const settledRunId = RunId.make("run_recovery_delegation_settled"); + const runningRunId = RunId.make("run_recovery_delegation_running"); + const providerThreadId = ProviderThreadId.make("provider_thread_recovery_delegation"); + const claudeInstanceId = ProviderInstanceId.make("claude"); + const driver = ProviderDriverKind.make("claude"); + const settledTaskId = NodeId.make("node_recovery_delegation_settled"); + const runningTaskId = NodeId.make("node_recovery_delegation_running"); + const nativeSubagentId = NodeId.make("node_recovery_native_subagent"); + const delegatedTask = (id: NodeId, runId: RunId) => ({ + id, + runId, + origin: "app_owned", + childThreadId: ThreadId.make(`thread:delegated-task:${id}`), + driver, + providerInstanceId: claudeInstanceId, + status: "running", + }); + const subagentItem = (subagentId: NodeId, runId: RunId, origin: string) => ({ + id: TurnItemId.make(`turn_item:${subagentId}`), + runId, + nodeId: subagentId, + providerThreadId, + type: "subagent", + status: "running", + subagentId, + origin, + childThreadId: + origin === "app_owned" ? ThreadId.make(`thread:delegated-task:${subagentId}`) : null, + providerInstanceId: claudeInstanceId, + title: `subagent ${subagentId}`, + }); + let committedInput: Parameters[0] | null = + null; + const projection = { + thread: { id: threadId, providerInstanceId: claudeInstanceId }, + runtimeRequests: [], + providerSessions: [], + providerThreads: [ + { + id: providerThreadId, + driver, + providerInstanceId: claudeInstanceId, + ownerNodeId: null, + status: "idle", + pendingBackgroundTasks: [], + }, + ], + providerTurns: [], + runs: [ + { + id: settledRunId, + ordinal: 1, + status: "completed", + providerThreadId, + providerInstanceId: claudeInstanceId, + }, + { + id: runningRunId, + ordinal: 2, + status: "running", + providerThreadId, + providerInstanceId: claudeInstanceId, + }, + ], + attempts: [], + nodes: [ + { id: settledTaskId, runId: settledRunId, status: "running", kind: "subagent" }, + { id: runningTaskId, runId: runningRunId, status: "running", kind: "subagent" }, + { id: nativeSubagentId, runId: settledRunId, status: "running", kind: "subagent" }, + ], + subagents: [ + delegatedTask(settledTaskId, settledRunId), + delegatedTask(runningTaskId, runningRunId), + { + ...delegatedTask(nativeSubagentId, settledRunId), + origin: "provider_native", + childThreadId: null, + }, + ], + messages: [], + turnItems: [ + subagentItem(settledTaskId, settledRunId, "app_owned"), + subagentItem(runningTaskId, runningRunId, "app_owned"), + subagentItem(nativeSubagentId, settledRunId, "provider_native"), + ], + } as unknown as OrchestrationV2ThreadProjection; + const layer = ProviderRuntimeRecovery.layer.pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mergeAll( + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getRecoveryThreadIds: () => Effect.succeed([threadId]), + getRuntimeRecoveryProjection: () => Effect.succeed(projection), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => { + committedInput = input; + return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never); + }, + }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ + runRecoveryOnce: Effect.succeed(false), + }), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + listByCommandId: () => Effect.succeed([]), + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), + }), + ), + ), + ); + + return Effect.gen(function* () { + yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup"); + const events = committedInput?.events ?? []; + const touched = events.flatMap((event) => + event.type === "turn-item.updated" + ? event.payload.type === "subagent" + ? [event.payload.subagentId] + : [] + : event.type === "subagent.updated" || event.type === "node.updated" + ? [event.payload.id] + : [], + ); + // The cut run itself is cancelled; only the provider-native subagent dies with it. + assert.isTrue( + events.some( + (event) => + event.type === "run.updated" && + event.payload.id === runningRunId && + event.payload.status === "cancelled", + ), + ); + assert.notInclude(touched, settledTaskId); + assert.notInclude(touched, runningTaskId); + assert.include(touched, nativeSubagentId); + // The note lists only provider-native work: delegated tasks report back on their own. + const noted = events.flatMap((event) => + event.type === "run.background-work-cancelled" + ? event.payload.restartCancelledBackgroundWork.map((work) => work.label) + : [], + ); + assert.deepEqual(noted, [`subagent ${nativeSubagentId}`]); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 67ae22f1883b..98287944dee1 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -1,12 +1,15 @@ +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, type OrchestrationV2DomainEvent, type ProviderThreadId, type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, ThreadId, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -93,6 +96,23 @@ function isNonterminalNodeStatus(status: string): boolean { return status === "pending" || status === "running" || status === "waiting"; } +/** + * A delegate_task child. Its own thread is reconciled and continued on its own + * and reports back through the app, so it is not provider background work. + */ +function isAppOwnedDelegation(task: { + readonly origin: OrchestrationV2Subagent["origin"]; + readonly childThreadId: ThreadId | null; +}): boolean { + return task.origin === "app_owned" && task.childThreadId !== null; +} + +function isAppOwnedDelegationItem( + item: OrchestrationV2ThreadProjection["turnItems"][number], +): boolean { + return item.type === "subagent" && isAppOwnedDelegation(item); +} + function providerThreadHasPendingBackgroundTasks( providerThread: OrchestrationV2ThreadProjection["providerThreads"][number], ): boolean { @@ -138,7 +158,11 @@ function providerThreadsWithOpenBackgroundWork( ): ReadonlySet { const ids = new Set(); for (const item of projection.turnItems ?? []) { - if (!isBackgroundCapableTurnItemType(item.type) || !isNonterminalTurnItemStatus(item.status)) + if ( + !isBackgroundCapableTurnItemType(item.type) || + !isNonterminalTurnItemStatus(item.status) || + isAppOwnedDelegationItem(item) + ) continue; const providerThreadId = item.providerThreadId ?? @@ -166,7 +190,7 @@ function latestStartedRun( run.providerThreadId === providerThreadId && run.status !== "queued" && run.status !== "rolled_back" && - (latest === undefined || run.ordinal > latest.ordinal) + (latest === undefined || runRanAfter(run, latest)) ? run : latest, undefined, @@ -222,6 +246,13 @@ export const make = Effect.gen(function* () { const requests = projection.runtimeRequests.filter( (request) => request.status === "pending" && request.responseCapability.type !== "message", ); + // Delegated task rows, items and nodes stay open: the child settles them. + const delegatedTaskNodeIds = new Set([ + ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id), + ...(projection.turnItems ?? []).flatMap((item) => + item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [], + ), + ]); const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`; const commandId = CommandId.make( `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`, @@ -333,6 +364,7 @@ export const make = Effect.gen(function* () { (candidate) => candidate.runId === run.id && !messageRequestNodeIds.has(candidate.id) && + !delegatedTaskNodeIds.has(candidate.id) && (candidate.status === "pending" || candidate.status === "running" || candidate.status === "waiting"), @@ -351,6 +383,7 @@ export const make = Effect.gen(function* () { for (const subagent of projection.subagents.filter( (candidate) => candidate.runId === run.id && + !isAppOwnedDelegation(candidate) && (candidate.status === "pending" || candidate.status === "running" || candidate.status === "waiting"), @@ -404,6 +437,7 @@ export const make = Effect.gen(function* () { (candidate) => candidate.runId === run.id && (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) && + !isAppOwnedDelegationItem(candidate) && (candidate.status === "pending" || candidate.status === "running" || candidate.status === "waiting"), @@ -436,7 +470,7 @@ export const make = Effect.gen(function* () { if (!isBackgroundCapableTurnItemType(item.type)) { continue; } - if (!isNonterminalTurnItemStatus(item.status)) { + if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) { continue; } const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection); @@ -763,32 +797,41 @@ export const make = Effect.gen(function* () { if (!enabled) return; const threadIds = yield* projections.getRecoveryThreadIds("runtime"); for (const threadId of threadIds) { - const projection = yield* projections.getRuntimeRecoveryProjection(threadId); - if ( - !resolveProjectSettings(enabled, projection.thread.projectId).settings - .continueThreadsAfterServerUpdate - ) - continue; - // Shutdown reconciliation cancels the background work below, so a - // settled thread's continuation must be captured while it is still open. - const run = restartContinuationRun( - projection, - providerThreadsWithOpenBackgroundWork(projection), + yield* Effect.gen(function* () { + const projection = yield* projections.getRuntimeRecoveryProjection(threadId); + if ( + !resolveProjectSettings(enabled, projection.thread.projectId).settings + .continueThreadsAfterServerUpdate + ) + return; + // Shutdown reconciliation cancels the background work below, so a + // settled thread's continuation must be captured while it is still open. + const run = restartContinuationRun( + projection, + providerThreadsWithOpenBackgroundWork(projection), + ); + if (!run) return; + const commandId = CommandId.make(`command:restart-prepare:${run.id}`); + yield* eventSink.writeWithEffects({ + commandId, + events: [], + effects: [ + { + id: `effect:restart-continuation:${run.id}`, + commandId, + threadId, + request: { type: "provider-runtime.continue", sourceRunId: run.id }, + }, + ], + }); + }).pipe( + // One failing thread must not cost the threads after it their continuation. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }), + ), ); - if (!run) continue; - const commandId = CommandId.make(`command:restart-prepare:${run.id}`); - yield* eventSink.writeWithEffects({ - commandId, - events: [], - effects: [ - { - id: `effect:restart-continuation:${run.id}`, - commandId, - threadId, - request: { type: "provider-runtime.continue", sourceRunId: run.id }, - }, - ], - }); } }).pipe( Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index a567a4ab4841..696a40d8d176 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -20,6 +20,7 @@ import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -80,6 +81,52 @@ const FailingReleaseEventSinkLayer = Layer.effect( }), ).pipe(Layer.provide(TestEventSinkLayer)); +interface FlakyReleaseWrites { + /** Which release writes fail right now. */ + readonly failing: Ref.Ref<"none" | "session" | "session-and-requests">; + /** Receives one item per failed write. */ + readonly failures: Queue.Queue; + /** Holds runtime request writes: completes `paused`, then waits for `resume`. */ + readonly pauseRequestWrites?: { + readonly paused: Deferred.Deferred; + readonly resume: Deferred.Deferred; + }; +} + +// Fails release writes with a defect, the way a failed SQL commit surfaces. +const makeFlakyReleaseEventSinkLayer = (flaky: FlakyReleaseWrites) => + Layer.effect( + EventSink.EventSinkV2, + Effect.gen(function* () { + const delegate = yield* EventSink.EventSinkV2; + return EventSink.EventSinkV2.of({ + ...delegate, + write: (input) => + Effect.gen(function* () { + const failing = yield* Ref.get(flaky.failing); + const fails = input.events.some( + (event) => + (failing !== "none" && + event.type === "provider-session.updated" && + (event.payload.status === "stopped" || event.payload.status === "error")) || + (failing === "session-and-requests" && event.type === "runtime-request.updated"), + ); + const pause = flaky.pauseRequestWrites; + if ( + pause !== undefined && + input.events.some((event) => event.type === "runtime-request.updated") + ) { + yield* Deferred.succeed(pause.paused, undefined); + yield* Deferred.await(pause.resume); + } + if (!fails) return yield* delegate.write(input); + yield* Queue.offer(flaky.failures, undefined); + return yield* Effect.die(new Error("simulated commit failure")); + }), + }); + }), + ).pipe(Layer.provide(TestEventSinkLayer)); + const CodexCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2; const ExclusiveCapabilities: OrchestrationV2ProviderCapabilities = { ...CodexCapabilities, @@ -359,15 +406,19 @@ function makeTestLayer(input: { readonly initialProviderItemIdentityVersion?: 2; }) => Effect.Effect; readonly failReleaseEventWrites?: boolean; + readonly flakyReleaseWrites?: FlakyReleaseWrites; readonly hasPendingBackgroundWork?: Effect.Effect; readonly hangSessionScopeClose?: boolean; readonly beforeUnload?: Effect.Effect; readonly serverSettingsLayer?: ReturnType; readonly projectServiceLayer?: Layer.Layer; }) { - const configuredEventSinkLayer = input.failReleaseEventWrites - ? FailingReleaseEventSinkLayer - : TestEventSinkLayer; + const configuredEventSinkLayer = + input.flakyReleaseWrites !== undefined + ? makeFlakyReleaseEventSinkLayer(input.flakyReleaseWrites) + : input.failReleaseEventWrites + ? FailingReleaseEventSinkLayer + : TestEventSinkLayer; const registryLayer = ProviderAdapterRegistry.makeSingleLayer( makeProviderAdapter(input.state, { failEventStream: input.failEventStream ?? false, @@ -2299,6 +2350,299 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r yield* effect.pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 1000 }))); }), ); +it.effect("ProviderSessionManagerV2 retries release records that failed to persist", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const flaky: FlakyReleaseWrites = { + failing: yield* Ref.make<"none" | "session" | "session-and-requests">("session"), + failures: yield* Queue.unbounded(), + }; + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-release-retry"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const providerThread = makeProviderThread({ idAllocator, threadId, providerSessionId, now }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const pendingRequest = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId, + providerSessionId, + providerThread, + now, + }); + yield* eventSink.write({ events: pendingRequest.events }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + + assert.isTrue(Exit.isFailure(yield* Effect.exit(manager.close(providerSessionId)))); + yield* Queue.take(flaky.failures); + // The failed session write does not keep the approval answerable. + const afterClose = yield* projectionStore.getThreadProjection(threadId); + assert.equal(afterClose.runtimeRequests.at(-1)?.responseCapability.type, "not_resumable"); + assert.equal(afterClose.providerSessions.at(-1)?.status, "ready"); + + // The first retry fails as well, and the retries continue. + yield* TestClock.adjust("1 second"); + yield* Queue.take(flaky.failures); + yield* Ref.set(flaky.failing, "none"); + const stopped = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + eventType: "provider-session.updated", + }) + .pipe(Stream.runHead, Effect.forkScoped); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(stopped); + + const afterRetry = yield* projectionStore.getThreadProjection(threadId); + assert.equal(afterRetry.providerSessions.at(-1)?.status, "stopped"); + }); + + yield* effect.pipe( + Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000, flakyReleaseWrites: flaky })), + ); + }), +); + +it.effect("ProviderSessionManagerV2 release retries leave a replacement session alone", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const flaky: FlakyReleaseWrites = { + failing: yield* Ref.make<"none" | "session" | "session-and-requests">("none"), + failures: yield* Queue.unbounded(), + }; + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread-provider-session-manager-release-replacement"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const writePendingRequest = Effect.gen(function* () { + const now = yield* DateTime.now; + const request = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId, + providerSessionId, + providerThread: makeProviderThread({ idAllocator, threadId, providerSessionId, now }), + now, + }); + yield* eventSink.write({ events: request.events }); + return request.requestId; + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + const oldRequestId = yield* writePendingRequest; + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* Ref.set(flaky.failing, "session-and-requests"); + assert.isTrue(Exit.isFailure(yield* Effect.exit(manager.close(providerSessionId)))); + yield* Queue.take(flaky.failures); + yield* Queue.take(flaky.failures); + yield* Ref.set(flaky.failing, "none"); + + // A replacement opens with the same id before the retry runs. + yield* TestClock.adjust("500 millis"); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + const newRequestId = yield* writePendingRequest; + const replacementStatus = (yield* projectionStore.getThreadProjection( + threadId, + )).providerSessions.at(-1)?.status; + const settled = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + eventType: "runtime-request.updated", + }) + .pipe(Stream.runHead, Effect.forkScoped); + yield* TestClock.adjust("500 millis"); + yield* Fiber.join(settled); + + const projection = yield* projectionStore.getThreadProjection(threadId); + const request = (id: typeof oldRequestId) => + projection.runtimeRequests.find((candidate) => candidate.id === id); + assert.equal(request(oldRequestId)?.responseCapability.type, "not_resumable"); + assert.equal(request(newRequestId)?.responseCapability.type, "live"); + assert.equal(projection.providerSessions.at(-1)?.status, replacementStatus); + }); + + yield* effect.pipe( + Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000, flakyReleaseWrites: flaky })), + ); + }), +); + +it.effect("ProviderSessionManagerV2 keeps each failed release's cleanup", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const flaky: FlakyReleaseWrites = { + failing: yield* Ref.make<"none" | "session" | "session-and-requests">("none"), + failures: yield* Queue.unbounded(), + }; + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const firstThreadId = ThreadId.make("thread-provider-session-manager-release-each-a"); + const secondThreadId = ThreadId.make("thread-provider-session-manager-release-each-b"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: firstThreadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: firstThreadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: secondThreadId, now }), + ], + }); + const secondThreadRequest = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId: secondThreadId, + providerSessionId, + providerThread: makeProviderThread({ + idAllocator, + threadId: secondThreadId, + providerSessionId, + now, + }), + now, + }); + yield* eventSink.write({ events: secondThreadRequest.events }); + const failRelease = (failedWrites: number) => + Effect.gen(function* () { + yield* Ref.set(flaky.failing, "session-and-requests"); + assert.isTrue(Exit.isFailure(yield* Effect.exit(manager.close(providerSessionId)))); + yield* Effect.repeat(Queue.take(flaky.failures), { times: failedWrites - 1 }); + yield* Ref.set(flaky.failing, "none"); + }); + + // The first session serves both threads. Its replacement serves one. + yield* manager.open({ + threadId: firstThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: secondThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + // Both the session write and the second thread's request write fail. + yield* failRelease(2); + yield* TestClock.adjust("500 millis"); + yield* manager.open({ + threadId: firstThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + // Only the session write fails: the first thread has no requests. + yield* failRelease(1); + + const settled = yield* eventSink + .stream({ + threadId: secondThreadId, + afterSequence: yield* eventSink.latestSequence({ threadId: secondThreadId }), + eventType: "runtime-request.updated", + }) + .pipe(Stream.runHead, Effect.forkScoped); + yield* TestClock.adjust("500 millis"); + yield* Fiber.join(settled); + + const projection = yield* projectionStore.getThreadProjection(secondThreadId); + assert.equal(projection.runtimeRequests.at(-1)?.responseCapability.type, "not_resumable"); + }); + + yield* effect.pipe( + Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000, flakyReleaseWrites: flaky })), + ); + }), +); + +it.effect("ProviderSessionManagerV2 settles a request the event pump persists during release", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const flaky: FlakyReleaseWrites = { + failing: yield* Ref.make<"none" | "session" | "session-and-requests">("none"), + failures: yield* Queue.unbounded(), + pauseRequestWrites: { + paused: yield* Deferred.make(), + resume: yield* Deferred.make(), + }, + }; + const pause = flaky.pauseRequestWrites!; + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-release-pump"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + // The runtime creates the request a moment after the release starts. + const createdAt = DateTime.add(now, { seconds: 1 }); + const pendingRequest = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId, + providerSessionId, + providerThread: makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now: createdAt, + }), + now: createdAt, + }); + const adapterEvents = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(adapterEvents); + yield* Queue.offerAll(adapterEvents!, pendingRequest.providerEvents); + // The event pump holds the request permit while it persists the request. + yield* Deferred.await(pause.paused); + const closed = yield* manager + .close(providerSessionId) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("1 second"); + yield* Deferred.succeed(pause.resume, undefined); + yield* Fiber.join(closed); + + const projection = yield* projectionStore.getThreadProjection(threadId); + const request = projection.runtimeRequests.find( + (candidate) => candidate.id === pendingRequest.requestId, + ); + assert.equal(request?.responseCapability.type, "not_resumable"); + }); + + yield* effect.pipe( + Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000, flakyReleaseWrites: flaky })), + ); + }), +); + it.effect("ProviderSessionManagerV2 terminalizes a pending input transcript item on release", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 786eb5a6bf0a..20e240e79c58 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -17,11 +17,13 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; @@ -360,7 +362,29 @@ export const layerWithOptions = ( }, ); const layerScope = yield* Effect.scope; + // Ctrl+C, or a stop that signals the whole process group, reaches the + // provider CLIs with the server. They report their own background work + // stopped before shutdown captures restart continuations, so provider + // events after the signal are dropped; restart recovery owns that state. + const shutdownSignal = { received: false }; + const onShutdownSignal = () => { + shutdownSignal.received = true; + }; + yield* Effect.acquireRelease( + Effect.sync(() => { + process.on("SIGINT", onShutdownSignal); + process.on("SIGTERM", onShutdownSignal); + }), + () => + Effect.sync(() => { + process.off("SIGINT", onShutdownSignal); + process.off("SIGTERM", onShutdownSignal); + }), + ); const sessions = yield* Ref.make(new Map()); + // One retry per released entry, so a later release with the same id + // cannot drop cleanup for threads only the earlier session served. + const releaseRecordRetries = yield* FiberSet.make(); const nextSubscriberId = yield* Ref.make(0); const sessionOpen = yield* makeKeyedSerialExecutor(); // Orders a thread's attach against a detach unloading it on the same session. @@ -608,6 +632,8 @@ export const layerWithOptions = ( const writeReleasedRuntimeRequestEvents = (input: { readonly entry: LiveSessionEntry; readonly reason: ProviderSessionReleaseReason; + /** Requests created later belong to a replacement session with the same id. */ + readonly releasedAt: DateTime.Utc; }) => Effect.gen(function* () { const providerSessionId = input.entry.runtime.providerSessionId; @@ -629,7 +655,8 @@ export const layerWithOptions = ( (request) => request.status === "pending" && request.responseCapability.type === "live" && - request.responseCapability.providerSessionId === providerSessionId, + request.responseCapability.providerSessionId === providerSessionId && + DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt), ); for (const request of releasedRequests) { @@ -708,6 +735,125 @@ export const layerWithOptions = ( } }); + // Records a released session as stopped and resolves the live runtime + // requests it left. Each write runs even if the other fails. Once a + // replacement session opens with the same id, it owns the session status, + // so only the requests are settled. + const writeReleaseRecords = (input: { + readonly entry: LiveSessionEntry; + readonly reason: ProviderSessionReleaseReason; + readonly detail?: string; + readonly releasedAt: DateTime.Utc; + readonly replaced: boolean; + }) => + Effect.all( + [ + input.replaced + ? Effect.succeed(Exit.void) + : Effect.exit(writeReleasedSessionEvents(input)), + Effect.exit( + writeReleasedRuntimeRequestEvents(input).pipe( + input.entry.requestEventPermit.withPermits(1), + ), + ), + ], + { concurrency: 1 }, + ).pipe(Effect.flatMap(Exit.asVoidAll)); + + // The session already left the live map, so a later release finds + // nothing to do. Without a retry the UI would keep a ready session and + // answerable approvals until a server restart. Each attempt holds the + // session's open lock, so it sees a replacement that opened meanwhile. + const retryReleaseRecords = ( + input: Omit[0], "replaced">, + ) => { + const providerSessionId = input.entry.runtime.providerSessionId; + const attempt = Effect.gen(function* () { + const exit = yield* Effect.exit( + sessionOpen.withLock( + providerSessionId, + Effect.gen(function* () { + const replaced = (yield* Ref.get(sessions)).has(sessionKey(providerSessionId)); + yield* writeReleaseRecords({ ...input, replaced }); + }), + ), + ); + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return yield* exit; + yield* Effect.logWarning("orchestration-v2.provider-session-release-records-failed", { + providerSessionId, + cause: exit.cause, + }); + // A failed SQL commit is a defect, so every failure but interruption + // is retried. + return yield* Effect.fail(exit.cause); + }); + return attempt.pipe( + Effect.retry({ + schedule: Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), + ), + }), + Effect.delay("1 second"), + FiberSet.run(releaseRecordRetries), + ); + }; + + const logReleaseFailure = + (providerSessionId: ProviderSessionId) => + (release: Effect.Effect) => + release.pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.provider-session-release-failed", { + providerSessionId, + cause, + }), + ), + ); + + // Removes the live entry and reads the request cleanup cutoff while + // holding the entry's request permit. A request the event pump is + // persisting for this runtime lands before the cutoff, and once the + // entry is gone the pump persists no more for it. A replacement's + // requests come after its own open. + const removeLiveEntry = (input: { + readonly providerSessionId: ProviderSessionId; + readonly onlyIfIdleGeneration?: number; + }): Effect.Effect, DateTime.Utc]> => + Effect.gen(function* () { + const key = sessionKey(input.providerSessionId); + const candidate = (yield* Ref.get(sessions)).get(key); + if (candidate === undefined) { + return [Option.none(), yield* DateTime.now] as const; + } + const removed = yield* Effect.zip( + Ref.modify(sessions, (current) => { + const existing = current.get(key); + if (existing !== candidate) { + return [existing === undefined ? "gone" : "changed", current] as const; + } + if ( + input.onlyIfIdleGeneration !== undefined && + (existing.busyCount > 0 || existing.idleGeneration !== input.onlyIfIdleGeneration) + ) { + return ["kept", current] as const; + } + const updated = new Map(current); + updated.delete(key); + return ["removed", updated] as const; + }), + DateTime.now, + ).pipe(candidate.requestEventPermit.withPermits(1)); + const [outcome, releasedAt] = removed; + // Another entry took this id while the permit was held; release it instead. + if (outcome === "changed") return yield* removeLiveEntry(input); + return [ + outcome === "removed" ? Option.some(candidate) : Option.none(), + releasedAt, + ] as const; + }); + const releaseEntry = (input: { readonly providerSessionId: ProviderSessionId; readonly reason: ProviderSessionReleaseReason; @@ -717,23 +863,8 @@ export const layerWithOptions = ( readonly gracefulSubscribers?: boolean; }) => Effect.acquireUseRelease( - Ref.modify(sessions, (current) => { - const key = sessionKey(input.providerSessionId); - const existing = current.get(key); - if (existing === undefined) { - return [Option.none(), current] as const; - } - if ( - input.onlyIfIdleGeneration !== undefined && - (existing.busyCount > 0 || existing.idleGeneration !== input.onlyIfIdleGeneration) - ) { - return [Option.none(), current] as const; - } - const updated = new Map(current); - updated.delete(key); - return [Option.some(existing), updated] as const; - }), - (entry) => + removeLiveEntry(input), + ([entry, releasedAt]) => Option.match(entry, { onNone: () => Effect.void, onSome: (entry) => @@ -794,21 +925,25 @@ export const layerWithOptions = ( Effect.forkDetach, ); } - yield* writeReleasedSessionEvents({ + const records = { entry, reason: input.reason, ...(input.detail === undefined ? {} : { detail: input.detail }), - }); - yield* writeReleasedRuntimeRequestEvents({ - entry, - reason: input.reason, - }).pipe(entry.requestEventPermit.withPermits(1)); + releasedAt, + }; + const recorded = yield* Effect.exit( + writeReleaseRecords({ ...records, replaced: false }), + ); + if (Exit.isFailure(recorded)) { + yield* retryReleaseRecords(records); + return yield* recorded; + } if (Option.isSome(closeExit) && Exit.isFailure(closeExit.value)) { return yield* Effect.failCause(closeExit.value.cause); } }), }), - (entry) => + ([entry]) => Option.match(entry, { onNone: () => Effect.void, onSome: (entry) => @@ -1426,6 +1561,7 @@ export const layerWithOptions = ( let stoppedByProvider = false; return entry.runtime.events.pipe( Stream.runForEach((event) => { + if (shutdownSignal.received) return Effect.void; if ( event.type === "provider_session.updated" && event.providerSession.status === "stopped" @@ -1484,6 +1620,8 @@ export const layerWithOptions = ( Effect.exit, Effect.flatMap((exit) => Effect.gen(function* () { + // A provider that exits on the shutdown signal is released by shutdown. + if (shutdownSignal.received) return; const current = (yield* Ref.get(sessions)).get( sessionKey(entry.runtime.providerSessionId), ); @@ -1495,7 +1633,7 @@ export const layerWithOptions = ( providerSessionId: entry.runtime.providerSessionId, reason: "manual_shutdown", gracefulSubscribers: true, - }).pipe(Effect.ignore); + }).pipe(logReleaseFailure(entry.runtime.providerSessionId)); return; } const cause = Exit.isFailure(exit) @@ -1516,7 +1654,7 @@ export const layerWithOptions = ( providerSessionId: entry.runtime.providerSessionId, reason: "runtime_error", detail: Cause.pretty(cause), - }).pipe(Effect.ignore); + }).pipe(logReleaseFailure(entry.runtime.providerSessionId)); }), ), Effect.forkIn(layerScope), @@ -1705,7 +1843,7 @@ export const layerWithOptions = ( providerSessionId: input.providerSessionId, reason: "runtime_error", detail: "Failed to persist the provider-session attachment.", - }).pipe(Effect.ignore), + }).pipe(logReleaseFailure(input.providerSessionId)), ), ); yield* startEventPump(entry); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 746fbe235d99..fdb45f193179 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -30,6 +30,7 @@ import * as ProviderAuthService from "../provider/Services/ProviderAuthService.t import * as ContextHandoffService from "./ContextHandoffService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "./IdAllocator.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import { ProviderAdapterEventStreamError } from "./ProviderAdapter.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -168,6 +169,8 @@ function makeLocalCommandHarness(input: { readonly interruptOpen?: boolean; readonly interruptRunBeforeOpenFailure?: boolean; readonly writeFailure?: unknown; + /** Loads the thread and starts the run, then fails every later state read. */ + readonly failReadsAfterRunning?: boolean; }) { const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z"); const threadId = ThreadId.make("thread-native-account-command"); @@ -411,9 +414,40 @@ function makeLocalCommandHarness(input: { ), ), ) - : Effect.die("A local command must not open a native session."), + : input.failReadsAfterRunning === true + ? Effect.succeed({ + driver: providerThread.driver, + providerSession: { + id: providerSessionId, + driver: providerThread.driver, + providerInstanceId: newInstanceId, + status: "ready", + cwd: "/tmp/native-account-command", + model: null, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + ensureThread: () => Effect.succeed(providerThread), + } as never) + : Effect.die("A local command must not open a native session."), + ); + const startRootRun = vi.fn< + (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect + >(() => + input.failReadsAfterRunning === true + ? Effect.void + : Effect.die("A local command must not start a native turn."), + ); + const failReadIfRunning = Effect.suspend(() => + input.failReadsAfterRunning === true && + projection.runs.find((candidate) => candidate.id === runId)?.status === "running" + ? Effect.fail( + new ProjectionStore.ProjectionStoreReadError({ threadId, cause: "database unavailable" }), + ) + : Effect.void, ); - const startRootRun = vi.fn(() => Effect.die("A local command must not start a native turn.")); const tryHandlePromptCommand = vi.fn(() => input.logoutFailure === undefined ? Effect.succeed(true) @@ -471,7 +505,7 @@ function makeLocalCommandHarness(input: { ), }), getRuntimeRecoveryProjection: () => - Effect.succeed({ + Effect.as(failReadIfRunning, { ...projection, hasConversation: projection.messages.some( (m) => @@ -703,6 +737,25 @@ effectIt.effect( }), ); +effectIt.effect("does not mistake a failed state read for a superseded run", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true }); + + yield* harness.start; + + expect(harness.projection().runs.at(-1)?.status).toBe("running"); + const controls = harness.startRootRun.mock.calls[0]?.[0]; + expect(controls).toBeDefined(); + if (controls === undefined) return; + // "false" would skip the provider turn or the terminal write and leave the + // run active. A read failure must reach the caller instead. + const startCheck = yield* Effect.flip(controls.shouldStartProviderTurn!()); + const finalizeCheck = yield* Effect.flip(controls.shouldFinalizeRun!()); + expect(startCheck._tag).toBe("ProjectionStoreReadError"); + expect(finalizeCheck._tag).toBe("ProjectionStoreReadError"); + }), +); + effectIt.effect("does not overwrite a run interrupted while its thread loads", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 781491ac7fd6..a3e3b122ca45 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -124,13 +124,14 @@ export const layer: Layer.Layer< }) => { // Guards and background routing need live execution state, not a fresh // allocation of every completed message and tool output in the thread. + // `false` means the run moved on or is gone. A failed read is an error, + // so the caller fails the start or the run instead of skipping it. const isCurrentAttemptInStatus = (expectedStatus: OrchestrationV2Run["status"]) => projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe( Effect.map((current) => { const run = current.runs.find((candidate) => candidate.id === input.runId); return run?.activeAttemptId === input.attemptId && run.status === expectedStatus; }), - Effect.catchCause(() => Effect.succeed(false)), ); return { isCurrentAttemptInStatus, @@ -157,7 +158,6 @@ export const layer: Layer.Layer< (run.status === "starting" || run.status === "running") ); }), - Effect.catchCause(() => Effect.succeed(false)), ), hasUnpairedRunInterruptRequest: () => projectionStore @@ -953,6 +953,7 @@ export const layer: Layer.Layer< run, projection.runs, projection.providerTurns, + projection.attempts, ); const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, @@ -967,9 +968,7 @@ export const layer: Layer.Layer< .map((candidate) => candidate.id), ), run, - runAttemptIds: projection.attempts - .filter((candidate) => candidate.runId === run.id) - .map((candidate) => candidate.id), + attempts: projection.attempts, }); const restartNote = restartCancelledWork.length === 0 diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts new file mode 100644 index 000000000000..4eb6ec80ce17 --- /dev/null +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -0,0 +1,219 @@ +import { + CommandId, + MessageId, + type OrchestrationV2Notification, + type ThreadPullRequestLink, + type ThreadPullRequestWatch, +} from "@t3tools/contracts"; +import { + normalizeThreadPullRequestKey, + threadPullRequestKeyOf, + visibleThreadPullRequests, +} from "@t3tools/shared/threadPullRequests"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; +import type * as Scope from "effect/Scope"; + +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import { evaluatePullRequestWatch, pullRequestWatchMessage } from "./pullRequestWatch.ts"; + +/** Passes in a row that could not read a pull request before its watch ends (one a minute). */ +const READ_FAILURE_LIMIT = 15; + +const logFailure = + (message: string, fields: Record) => + (cause: Cause.Cause): Effect.Effect => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.logWarning(message, { ...fields, cause }); + +interface WatchTarget { + readonly thread: ProjectionStore.ProjectionThreadPullRequests; + readonly link: ThreadPullRequestLink; + readonly watch: ThreadPullRequestWatch; +} + +const failureKey = ({ thread, link, watch }: WatchTarget) => + `${thread.id} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`; + +function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean { + return ( + left.startedAt === right.startedAt && + left.headSha === right.headSha && + left.failedChecks.join("\n") === right.failedChecks.join("\n") && + left.passed === right.passed && + left.remarksThrough === right.remarksThrough && + left.remarkIds.join("\n") === right.remarkIds.join("\n") && + left.conflicting === right.conflicting && + left.wakes === right.wakes + ); +} + +/** + * Wakes a thread's agent when a pull request it watches (`watch_pull_request`) needs a look: + * checks finished on the head commit, someone else commented, or the branch started to + * conflict. One pass a minute reads each watched pull request; settled threads wait until + * they are active again, and a merged or closed pull request ends its watch. + */ +export class PullRequestWatchReactor extends Context.Service< + PullRequestWatchReactor, + { + readonly start: () => Effect.Effect; + /** One pass over every watched pull request. */ + readonly sweep: Effect.Effect; + } +>()("t3/orchestration-v2/PullRequestWatchReactor") {} + +/** @public Service construction is part of the canonical Effect module API. */ +export const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const pullRequests = yield* PullRequestService.PullRequestService; + const crypto = yield* Crypto.Crypto; + + // Passes in a row that failed, per watch. Kept in memory: a restart only delays the stop. + const readFailures = new Map(); + + // Host-level identity, with the repository as linked, the way pull request sync reads it. + const identityOf = (link: ThreadPullRequestLink) => ({ + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, + }); + + /** + * Records what a pass saw, and wakes the agent with it. The orchestrator applies this only + * while the same watch is on, so a stop or restart that lands during the host read wins. + */ + const record = ( + target: WatchTarget, + next: ThreadPullRequestWatch | null, + wake?: { readonly text: string; readonly notification: OrchestrationV2Notification }, + ) => + Effect.gen(function* () { + const uuid = yield* crypto.randomUUIDv4; + yield* engine.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`), + threadId: target.thread.id, + ...identityOf(target.link), + startedAt: target.watch.startedAt, + watch: next, + ...(wake === undefined + ? {} + : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }), + }); + }); + + // A watch that cannot read its pull request ends with a wake saying so, rather than showing + // "Watching" while it learns nothing. + const giveUp = (target: WatchTarget) => + record(target, null, { + text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because it could not read it from the host for ${READ_FAILURE_LIMIT} minutes. Check it yourself, and call watch_pull_request to watch it again.`, + notification: { + source: { kind: "monitor" }, + outcome: "failed", + summary: `#${target.link.number}: stopped watching, could not read it`, + }, + }).pipe(Effect.catch(() => record(target, null))); + + const check = Effect.fn("PullRequestWatchReactor.check")(function* (target: WatchTarget) { + const { thread, link, watch } = target; + const pullRequest = identityOf(link); + // A merged pull request cannot reopen, so its watch ends without a host read, even on a + // settled thread. A closed one can, so the host decides below. + if (link.snapshot?.state === "merged") return yield* record(target, null); + if (thread.settledOverride === "settled" || thread.settledAt !== null) return; + + const reference = { projectId: thread.projectId, ...pullRequest }; + const read = yield* Effect.exit( + Effect.all( + [ + pullRequests.detail({ ...reference, allowStale: false }), + pullRequests.activity(reference), + ], + { concurrency: 2 }, + ), + ); + // Only host reads count towards giving up; a refused wake is not the host's fault. + const key = failureKey(target); + if (Exit.isFailure(read)) { + if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause); + const failures = (readFailures.get(key) ?? 0) + 1; + readFailures.set(key, failures); + // The count stays until the stop lands, so a failed stop is tried again next pass. + if (failures >= READ_FAILURE_LIMIT) { + yield* giveUp(target); + readFailures.delete(key); + } + return yield* Effect.failCause(read.cause); + } + readFailures.delete(key); + const [detail, activity] = read.value; + if (detail.state !== "open") return yield* record(target, null); + + // A degraded read (GitHub's review thread query failed) is truncated with no long thread to + // explain it, and would skip review comments, so remarks wait for a later pass. Replies past + // the first ten of a long review thread are not read. + const degraded = + activity.commentsTruncated && + !activity.reviewThreads.some((reviewThread) => reviewThread.nextCommentsCursor !== undefined); + const report = evaluatePullRequestWatch(watch, detail, degraded ? null : activity.comments); + if (report.changes.length > 0) { + return yield* record( + target, + report.exhausted ? null : report.next, + pullRequestWatchMessage({ + number: link.number, + url: link.url, + baseBranch: detail.baseBranch, + headSha: report.next.headSha, + report, + }), + ); + } + if (!watchesEqual(report.next, watch)) yield* record(target, report.next); + }); + + const sweep = Effect.gen(function* () { + const threads = yield* projections.getThreadsWithPullRequests(); + const targets = threads.flatMap((thread) => + visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) => + link.watch === undefined ? [] : [{ thread, link, watch: link.watch }], + ), + ); + const keys = new Set(targets.map(failureKey)); + for (const key of readFailures.keys()) if (!keys.has(key)) readFailures.delete(key); + yield* Effect.forEach( + targets, + (target) => + check(target).pipe( + Effect.catchCause( + logFailure("pull request watch check failed", { + threadId: target.thread.id, + pullRequest: threadPullRequestKeyOf(target.link), + }), + ), + ), + { concurrency: 4, discard: true }, + ); + }).pipe( + Effect.catchCause(logFailure("pull request watch sweep failed", {})), + Effect.withSpan("PullRequestWatchReactor.sweep"), + ); + + const start: PullRequestWatchReactor["Service"]["start"] = () => + forkParked(sweep.pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid)); + + return { start, sweep } satisfies PullRequestWatchReactor["Service"]; +}); + +export const layer = Layer.effect(PullRequestWatchReactor, make); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index f5215c1f3b6b..2f22ed583a91 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -6,12 +6,15 @@ import { RunId, type OrchestrationV2Run, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import { cancelledRosterTaskWork, cancelledTurnItemWork, + isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, restartCancelledBackgroundWorkNote, + restartContinuationNote, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; @@ -51,7 +54,7 @@ it("keeps the note for the provider thread that lost the work across a provider providerTurns: runs.filter((source) => source.id !== target.id).map(turnFor), compactionMessageIds: new Set(), run: target, - runAttemptIds: target.activeAttemptId === null ? [] : [target.activeAttemptId], + attempts: [{ id: target.activeAttemptId!, runId: target.id }], }); // Codex never lost the work, so it neither receives nor consumes the note. @@ -62,6 +65,30 @@ it("keeps the note for the provider thread that lost the work across a provider assert.deepEqual(pending(later, [root, onCodex, backOnClaude, later]), []); }); +it("delivers a resumed queued run's note even after a higher-ordinal run", () => { + // Run 3 ran ahead of held run 2; run 2 then resumed, lost background work in + // a second restart, and its continuation was superseded by a new message. + const ranFirst = run(3, claudeThread, { + completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"), + }); + const resumed = run(2, claudeThread, { + completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"), + restartCancelledBackgroundWork: lost, + }); + const next = run(4, claudeThread); + const runs = [resumed, ranFirst, next]; + assert.deepEqual( + pendingRestartCancelledBackgroundWork({ + runs, + providerTurns: [resumed, ranFirst].map(turnFor), + compactionMessageIds: new Set(), + run: next, + attempts: [{ id: next.activeAttemptId!, runId: next.id }], + }), + lost, + ); +}); + it("bounds the note so it cannot crowd out the turn's context", () => { const work = Array.from({ length: 25 }, (_, index) => ({ kind: "shell" as const, @@ -123,7 +150,7 @@ it("does not repeat the note when a steer restarts the run on a new attempt", () ], compactionMessageIds: new Set(), run: steered, - runAttemptIds, + attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })), }); // The first attempt reached the provider with the note; its replacement must not repeat it. @@ -131,3 +158,80 @@ it("does not repeat the note when a steer restarts the run on a new attempt", () // A first attempt that never reached the provider did not deliver it. assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], false), lost); }); + +it("counts a prompted mid-turn or chained continuation as delivering the note", () => { + const cut = run(1, claudeThread, { status: "cancelled", restartCancelledBackgroundWork: lost }); + const cutTurn = { ...turnFor(cut), status: "cancelled" as const }; + const continuation = run(2, claudeThread, { restartContinuationOfRunId: cut.id }); + // A turn cut mid-way that lost work is prompted with the note, not resumed natively. + assert.isTrue(isRestartNoteContinuation(continuation, [cut, continuation], [cutTurn], [])); + assert.isFalse( + isRestartNoteContinuation( + continuation, + [{ ...cut, restartCancelledBackgroundWork: [] }, continuation], + [cutTurn], + [], + ), + ); + const later = run(3, claudeThread); + const pending = (delivered: boolean) => + pendingRestartCancelledBackgroundWork({ + runs: [cut, continuation, later], + providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])], + compactionMessageIds: new Set(), + run: later, + attempts: [{ id: later.activeAttemptId!, runId: later.id }], + }); + assert.deepEqual(pending(true), []); + // A continuation that never reached the provider delivered nothing. + assert.deepEqual(pending(false), lost); + + // Its own continuation carries the original note forward. + const unstarted = { ...continuation, status: "cancelled" as const }; + const chained = run(3, claudeThread, { restartContinuationOfRunId: unstarted.id }); + assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], [cutTurn], []), { + work: lost, + settled: false, + }); + assert.isTrue(isRestartNoteContinuation(chained, [cut, unstarted, chained], [cutTurn], [])); + // Claude announces running before accepting the prompt. A second restart + // can cancel that turn without delivering anything to the provider. + for (const status of ["running", "cancelled"] as const) { + const turns = [cutTurn, { ...turnFor(unstarted), status }]; + assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], turns, []), { + work: lost, + settled: false, + }); + assert.deepEqual( + pendingRestartCancelledBackgroundWork({ + runs: [cut, unstarted, later], + providerTurns: turns, + compactionMessageIds: new Set(), + run: later, + attempts: [{ id: later.activeAttemptId!, runId: later.id }], + }), + lost, + ); + } + + // A steer replaced the attempt after its completed turn delivered the note. + const steered = { ...unstarted, activeAttemptId: RunAttemptId.make("attempt:replacement") }; + const attempts = [{ id: unstarted.activeAttemptId!, runId: steered.id }]; + const turns = [ + cutTurn, + turnFor(unstarted), + { ...turnFor(steered), status: "cancelled" as const }, + ]; + assert.deepEqual(restartContinuationNote(steered, [cut, steered], turns, attempts).work, []); + assert.isFalse(isRestartNoteContinuation(chained, [cut, steered, chained], turns, attempts)); + assert.deepEqual( + pendingRestartCancelledBackgroundWork({ + runs: [cut, steered, later], + providerTurns: turns, + compactionMessageIds: new Set(), + run: later, + attempts, + }), + [], + ); +}); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 50ea52895e77..11b2cfe37c08 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -3,10 +3,13 @@ import type { OrchestrationV2ProviderTurn, OrchestrationV2RestartCancelledBackgroundWork, OrchestrationV2Run, + OrchestrationV2RunAttempt, OrchestrationV2TurnItem, } from "@t3tools/contracts"; +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; +type Attempt = Pick; const MAX_LABEL_LENGTH = 160; @@ -120,25 +123,69 @@ export function isRestartNoteSource( ); } -/** A restart continuation whose prompt is the note rather than a resume. */ +/** + * The note a restart continuation of `source` carries, and whether the turn it + * continues had settled (the note is then the whole prompt). A continuation cut + * before its provider turn completed may not have delivered its own note: + * adapters can announce a running turn before accepting the prompt. Carry the + * note forward until a completed turn proves delivery. + */ +export function restartContinuationNote( + source: OrchestrationV2Run, + runs: ReadonlyArray, + providerTurns: ReadonlyArray>, + attempts: ReadonlyArray, +): { readonly work: ReadonlyArray; readonly settled: boolean } { + const completedAttempts = new Set( + providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId), + ); + const completedRuns = new Set( + attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId), + ); + let current = source; + let work = current.restartCancelledBackgroundWork ?? []; + const visited = new Set([current.id]); + while ( + current.restartContinuationOfRunId !== undefined && + !completedRuns.has(current.id) && + !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId)) + ) { + const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId); + if (previous === undefined || visited.has(previous.id)) break; + visited.add(previous.id); + current = previous; + work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work); + } + return { work, settled: isRestartNoteSource(current, providerTurns) }; +} + +/** + * A restart continuation prompted with the note rather than a native resume. + * A turn cut mid-way that lost background work is prompted too, so the note + * is delivered with it; only a continuation without a note resumes natively. + */ export function isRestartNoteContinuation( run: Pick, runs: ReadonlyArray, providerTurns: ReadonlyArray>, + attempts: ReadonlyArray, ): boolean { const source = run.restartContinuationOfRunId === undefined ? undefined : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId); - return source !== undefined && isRestartNoteSource(source, providerTurns); + return ( + source !== undefined && + restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0 + ); } /** * Work cancelled by a restart that the run's provider thread has not been told * about yet. The note belongs to the provider thread that lost the work: turns * on another provider (after a switch) neither owe it nor deliver it. A later - * run on the same provider thread delivers it once its attempt reaches the - * provider, so the pending set is derived rather than cleared. Compactions and + * completed turn on the same provider thread proves delivery, so the pending + * set is derived rather than cleared. Compactions and * resumed turns carry no note, and a rolled-back run left native history, so * none of them counts as delivery. A note continuation's own prompt is the note. */ @@ -150,13 +197,14 @@ export function pendingRestartCancelledBackgroundWork(input: { OrchestrationV2Run, | "id" | "ordinal" + | "completedAt" | "userMessageId" | "providerThreadId" | "restartContinuationOfRunId" | "activeAttemptId" >; - /** Every attempt id of `run`; a steer replaces the attempt but not the run. */ - readonly runAttemptIds: ReadonlyArray; + /** Include earlier attempts: a steer replaces the attempt but not the run. */ + readonly attempts: ReadonlyArray; }): ReadonlyArray { const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId); // The current run prepends the note unless it is a compaction or a @@ -170,7 +218,7 @@ export function pendingRestartCancelledBackgroundWork(input: { const providerThreadId = input.run.providerThreadId; const deliveredAttemptIds = new Set( input.providerTurns - .filter((turn) => turn.providerThreadId === providerThreadId) + .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed") .map((turn) => turn.runAttemptId), ); const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId); @@ -179,23 +227,29 @@ export function pendingRestartCancelledBackgroundWork(input: { candidate.id !== input.run.id && candidate.activeAttemptId !== null && candidate.status !== "rolled_back" && - deliveredAttemptIds.has(candidate.activeAttemptId) && + (deliveredAttemptIds.has(candidate.activeAttemptId) || + input.attempts.some( + (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id), + )) && !isCompaction(candidate) && (candidate.restartContinuationOfRunId === undefined || - isRestartNoteContinuation(candidate, input.runs, input.providerTurns)), + isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)), ); // A steer restarts this run on a new attempt: an earlier attempt that already // reached the provider delivered the note, so the replacement must not repeat it. - const alreadyDelivered = input.runAttemptIds.some( - (attemptId) => attemptId !== input.run.activeAttemptId && deliveredAttemptIds.has(attemptId), + const alreadyDelivered = input.attempts.some( + (attempt) => + attempt.runId === input.run.id && + attempt.id !== input.run.activeAttemptId && + deliveredAttemptIds.has(attempt.id), ); if (alreadyDelivered) return []; return sameThread .filter( (source) => - source.ordinal < input.run.ordinal && + runRanAfter(input.run, source) && (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && - !prompted.some((later) => later.ordinal > source.ordinal), + !prompted.some((later) => runRanAfter(later, source)), ) .reduce>( (work, source) => diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index c282fa7a26d6..e7cd4b9476a7 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -11,6 +12,7 @@ import { ThreadId, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ServerSettings from "../serverSettings.ts"; @@ -201,6 +203,7 @@ it.effect("prompts a settled thread's continuation with the note of its lost wor Layer.merge( Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: () => Effect.succeed(projection), + recoverDelegatedTask: () => Effect.void, dispatch: (command) => { commands.push(command); return Effect.succeed({} as never); @@ -246,6 +249,7 @@ it.effect("does not continue a failed run that lost background work", () => Layer.merge( Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: () => Effect.succeed(projection), + recoverDelegatedTask: () => Effect.void, dispatch: (command) => { commands.push(command); return Effect.succeed({} as never); @@ -328,6 +332,7 @@ it.effect("does not duplicate delivery and yields to newer user work or opt-out" >[0][] = []; const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: () => Effect.succeed(projection), + recoverDelegatedTask: () => Effect.void, dispatch: (command) => { commands.push(command); if (command.type === "message.dispatch") @@ -499,6 +504,7 @@ it.effect("does not cancel or resume a run that completes while shutdown intent ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: () => Effect.succeed(projection), + recoverDelegatedTask: () => Effect.void, dispatch: () => Effect.sync(() => { dispatched = true; @@ -511,3 +517,214 @@ it.effect("does not cancel or resume a run that completes while shutdown intent assert.isFalse(dispatched); }), ); + +const continuationTexts = (projection: OrchestrationV2ThreadProjection) => + Effect.gen(function* () { + const texts: Array = []; + yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe( + Effect.provide( + Layer.merge( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed(projection), + recoverDelegatedTask: () => Effect.void, + dispatch: (command) => { + if (command.type === "message.dispatch") texts.push(command.text); + return Effect.succeed({} as never); + }, + }), + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), + ), + ), + ); + return texts; + }); + +const cutMidTurn = (extra: Record = {}) => { + const base = makeProjection(); + return { + ...base, + runs: [ + { + ...base.runs[0]!, + status: "cancelled", + userMessageId: MessageId.make("message:user"), + ...extra, + }, + ], + providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }], + } as unknown as OrchestrationV2ThreadProjection; +}; + +const queuedFollowUp = { + id: RunId.make("run:queued"), + ordinal: 2, + providerInstanceId: instanceId, + providerThreadId, + status: "queued", + queueHeld: true, +}; + +it.effect("continues a cut run past queued follow-ups, which stay held", () => + Effect.gen(function* () { + const live = makeProjection(); + assert.equal( + restartContinuationRun({ + ...live, + runs: [...live.runs, queuedFollowUp], + } as unknown as OrchestrationV2ThreadProjection)?.id, + runId, + ); + const cut = cutMidTurn(); + const texts = yield* continuationTexts({ + ...cut, + runs: [...cut.runs, queuedFollowUp], + } as unknown as OrchestrationV2ThreadProjection); + assert.deepEqual(texts, ["Continue where you left off."]); + }), +); + +it.effect("continues a resumed queued run that ran after an earlier continuation", () => + Effect.gen(function* () { + // The continuation (ordinal 3) ran ahead of the held queue, then the user + // resumed the queued run (ordinal 1 here) and the server restarted again. + const finishedContinuation = { + id: RunId.make("run:earlier-continuation"), + ordinal: 3, + providerInstanceId: instanceId, + providerThreadId, + status: "completed", + completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"), + }; + const live = makeProjection(); + assert.equal( + restartContinuationRun({ + ...live, + runs: [...live.runs, finishedContinuation], + } as unknown as OrchestrationV2ThreadProjection)?.id, + runId, + ); + const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") }); + const texts = yield* continuationTexts({ + ...cut, + runs: [...cut.runs, finishedContinuation], + } as unknown as OrchestrationV2ThreadProjection); + assert.deepEqual(texts, ["Continue where you left off."]); + }), +); + +it.effect("does not continue a run the user asked to stop before the restart", () => + Effect.gen(function* () { + const texts = yield* continuationTexts({ + ...cutMidTurn(), + turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }], + } as unknown as OrchestrationV2ThreadProjection); + assert.deepEqual(texts, []); + }), +); + +it.effect("does not continue a cut /compact or /logout turn", () => + Effect.gen(function* () { + for (const text of ["/compact", " /LOGOUT "]) { + const texts = yield* continuationTexts({ + ...cutMidTurn(), + messages: [{ id: MessageId.make("message:user"), text, attachments: [] }], + } as unknown as OrchestrationV2ThreadProjection); + assert.deepEqual(texts, [], text); + } + const texts = yield* continuationTexts({ + ...cutMidTurn(), + messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }], + } as unknown as OrchestrationV2ThreadProjection); + assert.lengthOf(texts, 1); + }), +); + +it.effect("tells a turn cut mid-way about the background work it lost", () => + Effect.gen(function* () { + const texts = yield* continuationTexts( + cutMidTurn({ + restartCancelledBackgroundWork: [{ kind: "subagent", label: "Background reviewer" }], + }), + ); + assert.lengthOf(texts, 1); + assert.include(texts[0]!, "Background reviewer"); + assert.isTrue(texts[0]!.endsWith("Continue where you left off.")); + }), +); + +it.effect( + "carries the note forward when its continuation was cut before reaching the provider", + () => + Effect.gen(function* () { + const base = makeProjection(); + const original = { + ...base.runs[0]!, + id: RunId.make("run:original"), + status: "completed", + activeAttemptId: RunAttemptId.make("attempt:original"), + restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }], + }; + const projection = { + ...base, + runs: [ + original, + { + ...base.runs[0]!, + ordinal: 2, + status: "cancelled", + restartContinuationOfRunId: original.id, + }, + ], + // The original turn settled; the continuation's attempt never started one. + providerTurns: [ + { + ...base.providerTurns[0]!, + runAttemptId: original.activeAttemptId, + status: "completed", + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + const texts = yield* continuationTexts(projection); + assert.lengthOf(texts, 1); + assert.include(texts[0]!, "sleep 25 && echo DONE"); + assert.notInclude(texts[0]!, "Continue where"); + }), +); + +it.effect("prepares later threads' continuations when one thread fails", () => + Effect.gen(function* () { + const brokenThreadId = ThreadId.make("thread:broken"); + const writes: Parameters[0][] = []; + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provide( + Layer.mergeAll( + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]), + getRuntimeRecoveryProjection: (id) => + id === brokenThreadId + ? Effect.fail( + new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }), + ) + : Effect.succeed(makeProjection()), + }), + Layer.mock(EventSink.EventSinkV2)({ + writeWithEffects: (input) => + Effect.sync(() => { + writes.push(input); + return []; + }), + }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}), + Layer.mock(EffectOutbox.EffectOutboxV2)({}), + ), + ), + ); + yield* recovery.prepareForShutdown; + assert.deepEqual( + writes.map((write) => write.effects[0]?.request), + [{ type: "provider-runtime.continue", sourceRunId: runId }], + ); + }), +); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 216b830de41e..f91d1a1e5f73 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -1,3 +1,4 @@ +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, @@ -11,12 +12,16 @@ import * as Effect from "effect/Effect"; import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { isNativeMaintenanceCommand } from "./Orchestrator.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import { isRestartNoteSource, restartCancelledBackgroundWorkNote, + restartContinuationNote, } from "./RestartBackgroundNote.ts"; +const CONTINUE_PROMPT = "Continue where you left off."; + /** * The run a restart continuation resumes, if any: an unfinished root run, or a * settled one whose own provider thread lost background work in the restart @@ -30,8 +35,12 @@ export function restartContinuationRun( cancelledWorkProviderThreadIds: ReadonlySet = new Set(), ): OrchestrationV2Run | undefined { if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) return; + // Queued runs never started; recovery holds them behind the cut run. const run = projection.runs.reduce( - (latest, candidate) => (!latest || candidate.ordinal > latest.ordinal ? candidate : latest), + (latest, candidate) => + candidate.status !== "queued" && (!latest || runRanAfter(candidate, latest)) + ? candidate + : latest, undefined, ); if (!run) return; @@ -98,7 +107,7 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`); const projection = yield* threads.getThreadRecords( input.threadId, - ["messages", "runs", "providerTurns"], + ["messages", "runs", "providerTurns", "attempts"], { messageIds: [messageId] }, ); if ( @@ -114,17 +123,54 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta const noteSource = source !== undefined && isRestartNoteSource(source, projection.providerTurns); if (!source || (source.status !== "cancelled" && !noteSource)) return; - // A user submission after reconciliation takes precedence over an automatic prompt. - if (projection.runs.some((run) => run.ordinal > source.ordinal)) return; + // A user submission after reconciliation takes precedence over an automatic + // prompt. Queued runs never started and stay held behind this one. + if ( + projection.runs.some( + (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source), + ) + ) + return; if (projection.thread.providerInstanceId !== source.providerInstanceId) return; + const sourceRecords = yield* threads.getThreadRecords( + input.threadId, + ["messages", "turnItems"], + { + messageIds: [source.userMessageId], + turnItemRunIds: [source.id], + turnItemTypes: ["run_interrupt_request"], + }, + ); + // The user asked this run to stop before the restart cut it. + if ( + sourceRecords.turnItems.some( + (item) => item.runId === source.id && item.type === "run_interrupt_request", + ) + ) + return; + const sourceMessage = sourceRecords.messages.find( + (message) => message.id === source.userMessageId, + ); + if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return; + const note = restartContinuationNote( + source, + projection.runs, + projection.providerTurns, + projection.attempts, + ); + const noteText = + note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work); yield* threads.dispatch({ type: "message.dispatch", commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`), threadId: input.threadId, messageId, - text: noteSource - ? restartCancelledBackgroundWorkNote(source.restartCancelledBackgroundWork ?? []) - : "Continue where you left off.", + text: + noteText === undefined + ? CONTINUE_PROMPT + : note.settled + ? noteText + : `${noteText}\n\n${CONTINUE_PROMPT}`, attachments: [], modelSelection: source.modelSelection, dispatchMode: { type: "start_immediately" }, @@ -133,4 +179,15 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta restartContinuationOfRunId: input.sourceRunId, }); }, + // A delegated child this declined to continue still owes its parent a + // result. Once a continuation run exists this is a no-op; that run settles it. + (effect, input) => + effect.pipe( + Effect.andThen( + Effect.gen(function* () { + const threads = yield* ThreadManagementService.ThreadManagementService; + yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId); + }), + ), + ), ); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 370c30058346..3d6dca6151ab 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -50,6 +50,7 @@ import { type ProviderAdapterV2Event, type ProviderAdapterV2SessionRuntime, } from "./ProviderAdapter.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; @@ -590,6 +591,113 @@ it.effect("rechecks run ownership immediately before calling the provider", () = }).pipe(Effect.provide(RunExecutionTestLayer)), ); +it.effect("fails the run when its ownership check cannot be read before calling the provider", () => + Effect.gen(function* () { + const guardCalls = yield* Ref.make(0); + const providerStarts = yield* Ref.make(0); + const writes = yield* Ref.make>([]); + const threadId = ThreadId.make("thread:run-execution-start-guard-read"); + const runId = RunId.make("run:run-execution-start-guard-read"); + const attemptId = RunAttemptId.make("attempt:run-execution-start-guard-read"); + const providerInstanceId = ProviderInstanceId.make("codex"); + const testLayer = RunExecutionService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), + Layer.mock(EventSink.EventSinkV2)({ + writeIfRunCurrent: (input) => + Ref.update(writes, (current) => [...current, ...input.events]).pipe( + Effect.as({ committed: true, storedEvents: [] }), + ), + }), + IdAllocator.layer, + Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ + ingestNormalized: () => Effect.succeed([]), + }), + ServerSettings.layerTest(), + ), + ), + ); + + yield* Effect.gen(function* () { + const runExecution = yield* RunExecutionService.RunExecutionServiceV2; + yield* runExecution.startRootRun({ + commandId: CommandId.make("command:run-execution-start-guard-read"), + appThread: { id: threadId } as OrchestrationV2AppThread, + providerSessionId: ProviderSessionId.make("session:run-execution-start-guard-read"), + session: { + events: Stream.never, + startTurn: () => Ref.update(providerStarts, (count) => count + 1), + } as unknown as ProviderAdapterV2SessionRuntime, + run: { id: runId, threadId, ordinal: 1, providerInstanceId } as OrchestrationV2Run, + rootNode: { + id: NodeId.make("node:run-execution-start-guard-read"), + } as OrchestrationV2ExecutionNode, + checkpointScope: { + id: CheckpointScopeId.make("checkpoint-scope:run-execution-start-guard-read"), + } as OrchestrationV2CheckpointScope, + providerThread: { + id: ProviderThreadId.make("provider-thread:run-execution-start-guard-read"), + driver, + } as OrchestrationV2ProviderThread, + attempt: { id: attemptId, providerTurnId: null } as OrchestrationV2RunAttempt, + attemptId, + providerTurnOrdinal: 1, + // The preparation check passes; the check right before the provider + // call cannot read the run. + shouldStartProviderTurn: () => + Ref.getAndUpdate(guardCalls, (calls) => calls + 1).pipe( + Effect.flatMap((calls) => + calls === 0 + ? Effect.succeed(true) + : Effect.fail( + new ProjectionStore.ProjectionStoreReadError({ + threadId, + cause: "database unavailable", + }), + ), + ), + ), + // The failure is settled by the guarded write, not by another read. + shouldFinalizeRun: () => + Effect.fail( + new ProjectionStore.ProjectionStoreReadError({ + threadId, + cause: "database unavailable", + }), + ), + message: { + messageId: MessageId.make("message:run-execution-start-guard-read"), + text: "Start while the store is down.", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }); + }).pipe(Effect.provide(testLayer)); + + assert.equal(yield* Ref.get(guardCalls), 2); + assert.equal(yield* Ref.get(providerStarts), 0); + const runUpdate = (yield* Ref.get(writes)).find((event) => event.type === "run.updated"); + assert.equal( + runUpdate?.type === "run.updated" ? runUpdate.payload.status : undefined, + "failed", + ); + }), +); + it.effect( "dispatches only attachment-free compact commands through the native compaction path", () => @@ -3165,6 +3273,25 @@ it.effect.each(["completed", "interrupted", "cancelled", "failed"] as const)( }), ); +it.effect("records a finished run as failed when its ownership check cannot be read", () => + Effect.gen(function* () { + const { observed } = yield* captureRootRunTermination({ + key: "finalize-guard-read-failure", + shouldFinalizeRun: () => + Effect.fail( + new ProjectionStore.ProjectionStoreReadError({ + threadId: ThreadId.make("thread:finalize-guard-read-failure"), + cause: "database unavailable", + }), + ), + events: (ids) => Stream.make(rootTerminalEvent(ids, "completed")), + }); + // The fallback settles through the guarded write instead of the same + // failing read, so the run does not stay running. + assert.include(observed, "run:failed"); + }), +); + it.effect("does not refresh pull requests for auxiliary or stale provider terminals", () => Effect.gen(function* () { const { observed } = yield* captureRootRunTermination({ @@ -3254,7 +3381,7 @@ it.effect("keeps completed runs completed when pull request refresh fails", () = function captureRootRunTermination(input: { readonly key: string; - readonly shouldFinalizeRun: () => Effect.Effect; + readonly shouldFinalizeRun: () => Effect.Effect; readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -3278,6 +3405,17 @@ function captureRootRunTermination(input: { const ingestionDone = yield* Deferred.make(); const captureTurnItem = (payload: OrchestrationV2TurnItem) => Ref.update(writtenItems, (current) => [...current, payload]); + const captureFinalEvents = (events: ReadonlyArray) => + Effect.gen(function* () { + for (const event of events) { + if (event.type === "turn-item.updated") { + yield* captureTurnItem(event.payload); + } + if (event.type === "run.updated") { + yield* Ref.update(observed, (current) => [...current, `run:${event.payload.status}`]); + } + } + }); const testLayer = RunExecutionService.layer.pipe( Layer.provide( Layer.mergeAll( @@ -3292,22 +3430,11 @@ function captureRootRunTermination(input: { } return []; }), - writeWithEffects: (payload) => - Effect.gen(function* () { - for (const event of payload.events) { - if (event.type === "turn-item.updated") { - yield* captureTurnItem(event.payload); - } - if (event.type === "run.updated") { - yield* Ref.update(observed, (current) => [ - ...current, - `run:${event.payload.status}`, - ]); - } - } - return []; - }), - writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }), + writeWithEffects: (payload) => captureFinalEvents(payload.events).pipe(Effect.as([])), + writeIfRunCurrent: (payload) => + captureFinalEvents(payload.events).pipe( + Effect.as({ committed: true, storedEvents: [] }), + ), }), IdAllocator.layer, Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 71211c126545..6aff5da24f1e 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -28,6 +28,7 @@ import * as Context from "effect/Context"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; @@ -47,6 +48,7 @@ import type { } from "./ProviderAdapter.ts"; import { ProviderAdapterTurnStartError } from "./ProviderAdapter.ts"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; +import type { ProjectionStoreV2Error } from "./ProjectionStore.ts"; import { makeProviderFailure, makeProviderFailureTurnItem } from "./ProviderFailure.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; @@ -511,8 +513,8 @@ export interface RunExecutionServiceV2StartRootRunInput { >; readonly relatedThreadIds?: ReadonlyArray; readonly relatedProviderThreadIds?: ReadonlyArray; - readonly shouldStartProviderTurn?: () => Effect.Effect; - readonly shouldFinalizeRun?: () => Effect.Effect; + readonly shouldStartProviderTurn?: () => Effect.Effect; + readonly shouldFinalizeRun?: () => Effect.Effect; readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly message: ProviderAdapterV2TurnMessage; readonly modelSelection: ModelSelection; @@ -557,7 +559,7 @@ export const layer: Layer.Layer< readonly checkpointScope: OrchestrationV2CheckpointScope; readonly providerThread: OrchestrationV2ProviderThread; readonly attempt: OrchestrationV2RunAttempt; - readonly shouldFinalizeRun?: () => Effect.Effect; + readonly shouldFinalizeRun?: () => Effect.Effect; readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection; readonly terminal: ProviderTerminalEvent; @@ -1286,15 +1288,12 @@ export const layer: Layer.Layer< checkpointScope: input.checkpointScope, providerThread, attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: - input.hasUnpairedRunInterruptRequest, - }), + // The failure may be the ownership + // read itself, so check in the write. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running", + }, openRunOwnedSubagents: openSubagents, terminal: makeFailedTerminalEvent( makeProviderFailure({ @@ -1328,10 +1327,13 @@ export const layer: Layer.Layer< Effect.forkDetach, ); - if ( - input.shouldStartProviderTurn !== undefined && - !(yield* input.shouldStartProviderTurn()) - ) { + // A failed read fails the start below, so the run is recorded as + // failed instead of staying active with no provider turn. + const shouldStart = + input.shouldStartProviderTurn === undefined + ? Exit.succeed(true) + : yield* Effect.exit(input.shouldStartProviderTurn()); + if (Exit.isSuccess(shouldStart) && !shouldStart.value) { yield* Fiber.interrupt(providerEventFiber); return; } @@ -1373,7 +1375,7 @@ export const layer: Layer.Layer< }), )) : input.session.startTurn(turnInput); - yield* startTurn.pipe( + yield* Effect.andThen(shouldStart, startTurn).pipe( Effect.catchCause((cause) => Effect.logError("orchestration V2 provider turn start failed", { runId: input.run.id, @@ -1392,20 +1394,18 @@ export const layer: Layer.Layer< checkpointScope: input.checkpointScope, providerThread, attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: - input.hasUnpairedRunInterruptRequest, - }), + // Checked in the write transaction, not by another + // read that can fail like the one before the start. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running", + }, openRunOwnedSubagents: openSubagents, terminal: makeFailedTerminalEvent( makeProviderFailure({ cause: Cause.squash(cause), - class: "provider_error", + // A failed ownership read is not the provider's fault. + class: Exit.isFailure(shouldStart) ? "unknown" : "provider_error", }), latestItemOrdinal + 1, ), diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index dac4345c92dc..23d180102cd3 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -166,6 +166,28 @@ function taskFixture() { return { projection: { ...projection, runs: [run] }, run }; } +it("reports the run that ended last, not the highest ordinal", () => { + const { projection, run } = taskFixture(); + // A restart continuation (ordinal 4) ran ahead of held queued runs 2 and 3. + const ended = (ordinal: number, completedAt: string): OrchestrationV2Run => ({ + ...run, + id: RunId.make(`run:${ordinal}`), + ordinal, + completedAt: DateTime.makeUnsafe(completedAt), + }); + const progress = delegatedTaskProgress({ + ...projection, + runs: [ + { ...run, status: "cancelled" }, + ended(4, "2026-07-24T10:00:00.000Z"), + ended(2, "2026-07-24T10:05:00.000Z"), + ended(3, "2026-07-24T10:10:00.000Z"), + ], + }); + assert.equal(progress.state, "result_available"); + assert.equal(progress.resultRun?.ordinal, 3); +}); + it("waits for nested work and retains the report across monitor acknowledgements", () => { const { projection, run } = taskFixture(); assert.equal( diff --git a/apps/server/src/orchestration-v2/SubagentProjection.ts b/apps/server/src/orchestration-v2/SubagentProjection.ts index 8b3abf78fe85..fa912dfda0ba 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.ts @@ -16,6 +16,7 @@ import type { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; import { isOrchestrationV2WorkActive } from "@t3tools/contracts"; @@ -239,7 +240,7 @@ export function delegatedTaskProgress(projection: { projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0); const resultRun = workRuns .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1)) - .toSorted((a, b) => b.ordinal - a.ordinal)[0]; + .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0]; return { state: active || resultRun === undefined diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index ea8788c23bc7..37d4bdf3815f 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -314,6 +314,8 @@ export interface ThreadManagementServiceShape { input: ThreadManagementInterruptInput, ) => Effect.Effect; readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"]; + readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"]; + readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"]; readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"]; readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"]; readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"]; @@ -742,6 +744,8 @@ const make = Effect.gen(function* () { waitForThread, interruptThread, getThreadEventSequence: orchestrator.getThreadEventSequence, + recoverDelegatedTask: orchestrator.recoverDelegatedTask, + delegatedTaskResultPending: orchestrator.delegatedTaskResultPending, streamStoredEvents: orchestrator.streamStoredEvents, streamStoredEventsFrom: orchestrator.streamStoredEventsFrom, streamDomainEvents: orchestrator.streamDomainEvents, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 03933d9d0048..ef12204541b6 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -46,7 +46,12 @@ function at(offsetMs: number): DateTime.Utc { return DateTime.makeUnsafe(NOW_MS + offsetMs); } -function shell(overrides: Partial = {}): OrchestrationV2ThreadShell { +type SettlementShell = OrchestrationV2ThreadShell & + Pick; + +// A fixture's user message is one the user wrote unless the test sets +// latestUserAuthoredMessageAt on its own. +function shell(overrides: Partial = {}): SettlementShell { return { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), @@ -83,6 +88,7 @@ function shell(overrides: Partial = {}): Orchestrati latestRunStartedAt: null, latestRunCompletedAt: null, latestUserMessageAt: null, + latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null, createdAt: at(-30 * DAY_MS), updatedAt: at(-10 * DAY_MS), archivedAt: null, @@ -138,12 +144,25 @@ describe("isAutoSettlementCandidate", () => { ).toBe(false); expect( ThreadSettlementService.isAutoSettlementCandidate( - shell({ pendingBackgroundTasks: [{ label: "task" }] as never }), + shell({ pendingBackgroundTasks: [{ taskId: "review", kind: "subagent" }] }), NOW_MS, ), ).toBe(false); }); + it("settles a thread whose only background work is a command left running", () => { + expect( + ThreadSettlementService.isAutoSettlementCandidate( + shell({ + pendingBackgroundTasks: [ + { taskId: "dev", kind: "command", description: "vp run dev --share" }, + ], + }), + NOW_MS, + ), + ).toBe(true); + }); + it("keeps snoozed threads parked until they wake early on error or completion", () => { const snoozed = shell({ snoozedUntil: at(60 * 60 * 1_000), @@ -292,6 +311,31 @@ describe("resolveAutoSettlementAt", () => { ).toEqual(shell().createdAt); }); + it("settles on merge after agent-started runs, but not after the user writes again", () => { + // A background command stopped after the merge and its notification + // started a run. Only the user's own messages hold a merged thread open. + const woken = shell({ + latestUserMessageAt: at(-30 * 60 * 1_000), + latestUserAuthoredMessageAt: at(-2 * 60 * 60 * 1_000), + latestRunRequestedAt: at(-30 * 60 * 1_000), + latestRunCompletedAt: at(-29 * 60 * 1_000), + }); + const input = { + thread: woken, + pullRequest: { state: "merged" as const, mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)) }, + nowMs: NOW_MS, + autoSettleAfterDays: null, + autoSettleOnMerge: true, + }; + expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-29 * 60 * 1_000)); + expect( + ThreadSettlementService.resolveAutoSettlementAt({ + ...input, + thread: { ...woken, latestUserAuthoredMessageAt: at(-30 * 60 * 1_000) }, + }), + ).toBeNull(); + }); + it("settles inactive threads even when their pull request remains open", () => { const input = { thread: shell({ latestUserMessageAt: at(-30 * DAY_MS) }), @@ -370,10 +414,7 @@ function makeProject( }; } -function makeThread( - id: string, - overrides: Partial = {}, -): OrchestrationV2ThreadShell { +function makeThread(id: string, overrides: Partial = {}): SettlementShell { return shell({ id: ThreadId.make(id), projectId: PROJECT_ID, @@ -385,10 +426,14 @@ function makeThread( }); } +type SettlementSnapshot = Omit & { + readonly threads: ReadonlyArray; +}; + function makeSnapshot( - threads: ReadonlyArray, + threads: ReadonlyArray, projects: ReadonlyArray = [makeProject()], -): OrchestrationV2ShellSnapshot { +): SettlementSnapshot { return { schemaVersion: 1, snapshotSequence: 1, @@ -435,7 +480,7 @@ function makeBranchPullRequest(state: "open" | "closed" | "merged") { } interface HarnessOptions { - readonly snapshot: OrchestrationV2ShellSnapshot; + readonly snapshot: SettlementSnapshot; readonly settings?: ContractServerSettings; readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"]; readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"]; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 74c9de8d6b37..7c64ce02804a 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -1,3 +1,4 @@ +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { @@ -105,10 +106,15 @@ export function threadHasQueuedTurnStart( ].every((value) => value === null || value < messageAtMs); } +/** + * A merged or closed pull request settles the thread unless the user wrote to + * it afterwards. Runs that background work, a PR watch, or another agent + * started do not count, so they cannot hold a merged thread open. + */ function pullRequestSettles( thread: Pick< - OrchestrationV2ThreadShell, - "createdAt" | "latestUserMessageAt" | "latestRunRequestedAt" + ProjectionStore.ProjectionSettlementCandidate, + "createdAt" | "latestUserAuthoredMessageAt" >, pullRequest: SettlementPullRequest, autoSettleOnMerge: boolean, @@ -120,8 +126,7 @@ function pullRequestSettles( if (terminalAt == null) return false; const userAnchorMs = latestMillis([ toMillis(thread.createdAt), - toMillis(thread.latestUserMessageAt), - toMillis(thread.latestRunRequestedAt), + toMillis(thread.latestUserAuthoredMessageAt), ]); if (userAnchorMs === null) return false; const pullRequestAtMs = Date.parse(terminalAt); @@ -131,16 +136,17 @@ function pullRequestSettles( /** Cheap checks that run before any source control lookup. */ export function isAutoSettlementCandidate( - thread: ProjectionStore.ProjectionSettlementCandidate, + thread: Omit, nowMs: number, ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; // Blocked-on-you work must never park behind a settled override. if (thread.pendingRuntimeRequest !== null) return false; - // A live run — or post-settlement background work — is not staleness. + // A live run, or background work that will wake the agent, is not + // staleness. A dev server left running is: the agent is done. if (thread.activityRunStatus != null) return false; - if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) return false; + if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false; if (threadHasQueuedTurnStart(thread, nowMs)) return false; const snoozedUntilMs = toMillis(thread.snoozedUntil); if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return true; diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts new file mode 100644 index 000000000000..c247d78fd332 --- /dev/null +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -0,0 +1,217 @@ +import type { + PullRequestCheck, + PullRequestComment, + PullRequestDetail, + ThreadPullRequestWatch, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; + +import { + PULL_REQUEST_WATCH_WAKE_LIMIT, + evaluatePullRequestWatch, + pullRequestWatchMessage, +} from "./pullRequestWatch.ts"; + +const STARTED = "2026-10-02T12:00:00.000Z"; + +const watch = (overrides: Partial = {}): ThreadPullRequestWatch => ({ + startedAt: STARTED, + headSha: null, + failedChecks: [], + passed: false, + remarksThrough: STARTED, + remarkIds: [], + conflicting: false, + wakes: 0, + ...overrides, +}); + +const check = (name: string, status: PullRequestCheck["status"]): PullRequestCheck => ({ + name, + status, + description: null, + url: `https://ci.example/${name}`, +}); + +type Detail = Parameters[1]; + +const detail = (overrides: Partial = {}): Detail => ({ + headSha: "aaaaaaaaaa", + checks: [check("lint", "success"), check("test", "pending")], + mergeability: "mergeable", + viewer: "agent-user", + author: { login: "agent-user", name: null, avatarUrl: null }, + ...overrides, +}); + +const remark = ( + login: string, + createdAt: string, + body = "Please rename this.", +): PullRequestComment => ({ + id: `${login}-${createdAt}`, + kind: "review-comment", + author: { login, name: null, avatarUrl: null }, + body, + createdAt, + url: `https://github.com/o/r/pull/1#${login}`, + path: "src/index.ts", + reviewState: null, +}); + +const noRemarks: ReadonlyArray = []; + +describe("evaluatePullRequestWatch", () => { + it("reports each failure at once, even while another check never finishes", () => { + const bot = check("CodeRabbit", "pending"); + const first = detail({ checks: [check("lint", "failure"), check("test", "pending"), bot] }); + const lint = evaluatePullRequestWatch(watch(), first, noRemarks); + assert.deepEqual(lint.changes, [{ kind: "checks-failed", failed: [check("lint", "failure")] }]); + assert.deepEqual(evaluatePullRequestWatch(lint.next, first, noRemarks).changes, []); + + // A different job failing later is news of its own. + const second = detail({ checks: [check("lint", "failure"), check("test", "failure"), bot] }); + const test = evaluatePullRequestWatch(lint.next, second, noRemarks); + assert.deepEqual(test.changes, [{ kind: "checks-failed", failed: [check("test", "failure")] }]); + + // A rerun leaves the list while it runs, so failing again is reported again. + const rerun = evaluatePullRequestWatch(test.next, first, noRemarks); + assert.equal(evaluatePullRequestWatch(rerun.next, second, noRemarks).changes.length, 1); + + // A push reports its failures, even ones that failed between two passes. + const pushed = detail({ ...second, headSha: "bbbbbbbbbb" }); + assert.equal(evaluatePullRequestWatch(test.next, pushed, noRemarks).changes.length, 1); + }); + + it("reports passed once the required checks pass, whatever the others do", () => { + const required = (name: string, status: PullRequestCheck["status"]) => ({ + ...check(name, status), + required: true, + }); + const green = detail({ + checks: [required("test", "success"), required("lint", "success"), check("bot", "pending")], + }); + const passed = evaluatePullRequestWatch(watch(), green, noRemarks); + assert.deepEqual(passed.changes, [{ kind: "checks-passed", count: 2, required: true }]); + assert.deepEqual(evaluatePullRequestWatch(passed.next, green, noRemarks).changes, []); + + // Where nothing is marked required, every check has to pass. + const plain = detail({ checks: [check("test", "success"), check("bot", "pending")] }); + assert.deepEqual(evaluatePullRequestWatch(watch(), plain, noRemarks).changes, []); + }); + + it("keeps remarks for a later pass when the conversation was not read whole", () => { + const comments = [remark("reviewer", "2026-10-02T12:06:00Z")]; + const partial = evaluatePullRequestWatch(watch(), detail(), null); + assert.deepEqual(partial.changes, []); + assert.equal( + evaluatePullRequestWatch(partial.next, detail(), comments).changes[0]?.kind, + "remarks", + ); + }); + + it("reports a remark that shows up late with the same time as a reported one", () => { + const first = remark("reviewer", "2026-10-02T12:06:00Z"); + const late = { ...remark("bot", "2026-10-02T12:06:00Z"), id: "late" }; + const reported = evaluatePullRequestWatch(watch(), detail(), [first]); + const again = evaluatePullRequestWatch(reported.next, detail(), [first, late]); + assert.deepEqual(again.changes, [{ kind: "remarks", remarks: [late] }]); + assert.deepEqual(again.next.remarkIds, [first.id, "late"]); + }); + + it("does not treat a failed check read as a rerun", () => { + const failed = detail({ checks: [check("lint", "failure")] }); + const reported = evaluatePullRequestWatch(watch(), failed, noRemarks); + assert.equal(reported.changes.length, 1); + const unreadable = evaluatePullRequestWatch(reported.next, detail({ checks: [] }), noRemarks); + assert.deepEqual(evaluatePullRequestWatch(unreadable.next, failed, noRemarks).changes, []); + }); + + it("wakes for the pull request's author when the agent is someone else", () => { + const contributor = detail({ author: { login: "contributor", name: null, avatarUrl: null } }); + const reply = remark("contributor", "2026-10-02T12:06:00Z"); + assert.deepEqual(evaluatePullRequestWatch(watch(), contributor, [reply]).changes, [ + { kind: "remarks", remarks: [reply] }, + ]); + // Without a viewer, the author is taken to be the agent. + const noViewer = detail({ viewer: undefined, author: contributor.author }); + assert.deepEqual(evaluatePullRequestWatch(watch(), noViewer, [reply]).changes, []); + }); + + it("reports remarks from others once and never the agent's own", () => { + const comments = [ + remark("agent-user", "2026-10-02T12:05:00Z", "Fixed in the latest push."), + remark("macroscope-app[bot]", "2026-10-02T12:06:00Z"), + remark("reviewer", "2026-10-02T11:00:00Z", "Older than the watch."), + ]; + const report = evaluatePullRequestWatch(watch(), detail(), comments); + assert.deepEqual(report.changes, [{ kind: "remarks", remarks: [comments[1]!] }]); + assert.equal(report.next.remarksThrough, "2026-10-02T12:06:00Z"); + assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); + }); + + it("reports a conflict once, until the branch is clean again", () => { + const conflicting = detail({ mergeability: "conflicting" }); + const first = evaluatePullRequestWatch(watch(), conflicting, noRemarks); + assert.deepEqual(first.changes, [{ kind: "conflicting" }]); + // GitHub answers "unknown" while it recomputes after a push; that is not a resolution. + const recomputing = evaluatePullRequestWatch( + first.next, + detail({ mergeability: "unknown" }), + noRemarks, + ); + assert.deepEqual( + evaluatePullRequestWatch(recomputing.next, conflicting, noRemarks).changes, + [], + ); + const clean = evaluatePullRequestWatch(first.next, detail(), noRemarks); + assert.deepEqual(evaluatePullRequestWatch(clean.next, conflicting, noRemarks).changes, [ + { kind: "conflicting" }, + ]); + }); + + it("does not spend the comment wake limit on check results", () => { + const tired = watch({ headSha: "aaaaaaaaaa", wakes: PULL_REQUEST_WATCH_WAKE_LIMIT - 1 }); + const result = evaluatePullRequestWatch( + tired, + detail({ checks: [check("lint", "failure")] }), + noRemarks, + ); + assert.isFalse(result.exhausted); + assert.equal(result.next.wakes, 0); + }); + + it("stops after the wake limit unless the head moves", () => { + const comments = [remark("reviewer", "2026-10-02T12:10:00Z")]; + const tired = watch({ headSha: "aaaaaaaaaa", wakes: PULL_REQUEST_WATCH_WAKE_LIMIT - 1 }); + assert.isTrue(evaluatePullRequestWatch(tired, detail(), comments).exhausted); + const pushed = evaluatePullRequestWatch(tired, detail({ headSha: "cccccccccc" }), comments); + assert.isFalse(pushed.exhausted); + assert.equal(pushed.next.wakes, 1); + }); +}); + +describe("pullRequestWatchMessage", () => { + it("tells the agent what changed and marks failures for the timeline", () => { + const report = evaluatePullRequestWatch( + watch(), + detail({ checks: [check("lint", "failure")] }), + [remark("reviewer", "2026-10-02T12:10:00Z", "Needs a test.")], + ); + const message = pullRequestWatchMessage({ + number: 12, + url: "https://github.com/o/r/pull/12", + baseBranch: "main", + headSha: report.next.headSha, + report, + }); + assert.include(message.text, "- Checks failed on aaaaaaa:\n - lint https://ci.example/lint"); + assert.include(message.text, ' - reviewer on src/index.ts: "Needs a test."'); + assert.include(message.text, "unwatch_pull_request"); + assert.deepEqual(message.notification, { + source: { kind: "monitor" }, + outcome: "failed", + summary: "#12: checks failed, new comments", + }); + }); +}); diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts new file mode 100644 index 000000000000..af9ce27636ee --- /dev/null +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -0,0 +1,209 @@ +import type { + OrchestrationV2Notification, + PullRequestCheck, + PullRequestComment, + PullRequestDetail, + ThreadPullRequestWatch, +} from "@t3tools/contracts"; + +/** + * Wakes in a row that bring only comments. Check, conflict, or push news resets the count, so + * this only stops a chatty bot looping an agent that is replying to it. + */ +export const PULL_REQUEST_WATCH_WAKE_LIMIT = 10; +const LISTED_ITEMS = 10; +const SNIPPET_LENGTH = 200; + +export type PullRequestWatchChange = + | { readonly kind: "checks-failed"; readonly failed: ReadonlyArray } + | { readonly kind: "checks-passed"; readonly count: number; readonly required: boolean } + | { readonly kind: "remarks"; readonly remarks: ReadonlyArray } + | { readonly kind: "conflicting" }; + +export interface PullRequestWatchReport { + /** What the agent has not been told yet. Empty means no wake. */ + readonly changes: ReadonlyArray; + /** The watch to record, whether or not anything is reported. */ + readonly next: ThreadPullRequestWatch; + /** This report spends the last wake before the limit, so watching stops after it. */ + readonly exhausted: boolean; +} + +// "action-required" is a finished check that needs someone, so the agent hears about it. +const isFailedCheck = (check: PullRequestCheck) => + check.status === "failure" || check.status === "cancelled" || check.status === "action-required"; + +/** + * Compares a watched pull request with what its agent was last told. Each check is reported as + * soon as it fails, so a check that never finishes (an advisory review bot) cannot hold the + * news back. "Passed" is reported once the checks the base branch requires all passed, or all + * checks where the host marks none required. Remarks count when someone other than the agent's + * own account wrote them, so its own replies never wake it. `remarks` is null when the + * conversation could not be read; remarks then wait for a later pass. + */ +export function evaluatePullRequestWatch( + watch: ThreadPullRequestWatch, + detail: Pick, + remarks: ReadonlyArray | null, +): PullRequestWatchReport { + const changes: Array = []; + const headSha = detail.headSha ?? null; + const headMoved = headSha !== watch.headSha; + + // An empty list keeps the last state: a host can answer with one when its check read fails. + let failedChecks = headMoved ? [] : watch.failedChecks; + let passed = headMoved ? false : watch.passed; + if (detail.checks.length > 0) { + const failed = detail.checks.filter(isFailedCheck); + const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name)); + if (newlyFailed.length > 0) changes.push({ kind: "checks-failed", failed: newlyFailed }); + // A check that runs again leaves the list, so a rerun that fails again is reported. + failedChecks = failed.map((check) => check.name); + + const required = detail.checks.filter((check) => check.required === true); + const gate = required.length > 0 ? required : detail.checks; + const passedNow = gate.every((check) => check.status !== "pending" && !isFailedCheck(check)); + if (passedNow && !passed) { + changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 }); + } + passed = passedNow; + } + + const own = (detail.viewer ?? detail.author?.login)?.toLowerCase(); + const through = Date.parse(watch.remarksThrough); + // GitHub times are per second, so remarks at the boundary time are told apart by ID. + const fresh = (remarks ?? []).filter((remark) => { + const at = Date.parse(remark.createdAt); + return ( + (at > through || (at === through && !watch.remarkIds.includes(remark.id))) && + remark.author?.login.toLowerCase() !== own + ); + }); + if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); + const latest = Math.max(through, ...fresh.map((remark) => Date.parse(remark.createdAt))); + const atLatest = fresh.filter((remark) => Date.parse(remark.createdAt) === latest); + const remarksThrough = latest === through ? watch.remarksThrough : atLatest[0]!.createdAt; + const remarkIds = [ + ...(latest === through ? watch.remarkIds : []), + ...atLatest.map((remark) => remark.id), + ]; + + if (detail.mergeability === "conflicting" && !watch.conflicting) { + changes.push({ kind: "conflicting" }); + } + // "unknown" is GitHub still computing after a push; only a clean answer clears a conflict. + const conflicting = + detail.mergeability === "unknown" ? watch.conflicting : detail.mergeability === "conflicting"; + + const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks"); + const progress = headMoved || (changes.length > 0 && !commentsOnly); + const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0); + return { + changes, + next: { + startedAt: watch.startedAt, + headSha, + failedChecks, + passed, + remarksThrough, + remarkIds, + conflicting, + wakes, + }, + exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT, + }; +} + +function snippet(body: string): string { + const text = body + .replaceAll(//g, " ") + .replaceAll(/\s+/g, " ") + .trim(); + return text.length <= SNIPPET_LENGTH ? text : `${text.slice(0, SNIPPET_LENGTH - 3)}...`; +} + +function listed(items: ReadonlyArray, line: (item: T) => string): Array { + const lines = items.slice(0, LISTED_ITEMS).map(line); + if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`); + return lines; +} + +function changeLines( + change: PullRequestWatchChange, + context: { readonly baseBranch: string; readonly commit: string }, +): Array { + switch (change.kind) { + case "checks-failed": + return [ + `- Checks failed${context.commit}:`, + ...listed( + change.failed, + (check) => + ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`, + ), + ]; + case "checks-passed": + return [ + `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`, + ]; + case "remarks": + return [ + `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`, + ...listed(change.remarks, (remark) => { + const where = remark.path === null ? "" : ` on ${remark.path}`; + const body = snippet(remark.body); + const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`; + return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`; + }), + ]; + case "conflicting": + return [`- The branch now conflicts with ${context.baseBranch}.`]; + } +} + +const SUMMARY: Record = { + "checks-failed": "checks failed", + "checks-passed": "checks passed", + remarks: "new comments", + conflicting: "merge conflict", +}; + +/** The wake the agent reads and the timeline notification the user sees. */ +export function pullRequestWatchMessage(input: { + readonly number: number; + readonly url: string; + readonly baseBranch: string; + readonly headSha: string | null; + readonly report: PullRequestWatchReport; +}): { readonly text: string; readonly notification: OrchestrationV2Notification } { + const { changes, exhausted } = input.report; + const context = { + baseBranch: input.baseBranch, + commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`, + }; + const text = [ + `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`, + ...changes.flatMap((change) => changeLines(change, context)), + "", + exhausted + ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.` + : "Look into each item and act on it as your task requires. T3 Code keeps watching and wakes you on the next change, so end your turn when you are done. Call unwatch_pull_request when you no longer need updates.", + ].join("\n"); + const failed = changes.some( + (change) => change.kind === "checks-failed" || change.kind === "conflicting", + ); + const summary = changes.map((change) => SUMMARY[change.kind]); + if (exhausted) summary.push("stopped watching"); + return { + text, + notification: { + source: { kind: "monitor" }, + outcome: failed + ? "failed" + : changes.every((change) => change.kind === "checks-passed") + ? "completed" + : "updated", + summary: `#${input.number}: ${summary.join(", ")}`, + }, + }; +} diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index d077f7e20910..2c5235c767d7 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -17,6 +17,7 @@ import { type ModelSelection, type OrchestrationV2Run, ProjectId, + type PullRequestDetail, ProviderDriverKind, ProviderInstanceId, ProviderThreadId, @@ -58,6 +59,9 @@ import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; import * as ProviderRuntimeRecoveryService from "./ProviderRuntimeRecoveryService.ts"; import * as ProjectionMaintenance from "./ProjectionMaintenance.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as PullRequestWatchReactor from "./PullRequestWatchReactor.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ProjectStore from "./ProjectStore.ts"; import type { ProviderAdapterV2SessionRuntime, ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -212,6 +216,7 @@ const TestLayer = Layer.mergeAll( OrchestrationV2LayerLive, OrchestrationV2EventSinkLayerLive, ProjectStore.layer, + ProjectionStore.layer, EffectOutbox.layer, ThreadCommandExecutor.layer, ).pipe( @@ -2148,6 +2153,298 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("starts, records, and stops a pull request watch", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; + const threadId = ThreadId.make("runtime-pull-request-watch"); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-create"), + threadId, + projectId: ProjectId.make("pr-watch-project"), + title: "Watch", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 7 }; + const url = "https://github.com/pingdotgg/t3code/pull/7"; + const watchOf = Effect.map( + orchestrator.getThreadShell(threadId), + (thread) => thread?.pullRequests?.[0]?.watch, + ); + + // Watching an unlinked pull request links it in the same command. + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-start"), + threadId, + ...key, + watching: true, + link: { url, source: "agent" }, + }); + assert.equal( + (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.source, + "agent", + ); + const started = yield* watchOf; + assert.isDefined(started); + if (started === undefined) return; + + // A legacy client re-linking the same pull request keeps its watch. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("pr-watch-legacy-relink"), + threadId, + linkedPullRequest: { projectId: ProjectId.make("pr-watch-project"), ...key, url }, + }); + assert.deepEqual(yield* watchOf, started); + + const recorded = { ...started, headSha: "abc123", failedChecks: ["lint"], wakes: 1 }; + yield* orchestrator.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make("pr-watch-record"), + threadId, + ...key, + startedAt: started.startedAt, + watch: recorded, + }); + assert.deepEqual(yield* watchOf, recorded); + assert.isTrue((yield* maintenance.rebuild).valid); + assert.deepEqual(yield* watchOf, recorded); + + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-stop"), + threadId, + ...key, + watching: false, + }); + // A wake read before the stop must neither wake the agent nor bring the watch back. + const late = yield* orchestrator + .dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make("pr-watch-late-record"), + threadId, + ...key, + startedAt: started.startedAt, + watch: { ...recorded, wakes: 2 }, + wake: { + messageId: MessageId.make("pr-watch-late-wake"), + text: "Update", + notification: { source: { kind: "monitor" }, outcome: "updated", summary: "#7" }, + }, + }) + .pipe(Effect.flip); + assert.equal(late._tag, "OrchestratorDispatchError"); + assert.isUndefined(yield* watchOf); + const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]); + assert.deepEqual(messages, []); + }), + ); + + it.effect("ends a watch it cannot read, and tells the agent", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-pull-request-watch-unreadable"); + const projectId = ProjectId.make("pr-watch-unreadable-project"); + yield* seedProject({ + projectId, + title: "Watch unreadable", + workspaceRoot: "/workspace/watch-unreadable", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-unreadable-create"), + threadId, + projectId, + title: "Watch unreadable", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-unreadable-start"), + threadId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 8, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/8", source: "agent" }, + }); + const reactor = yield* PullRequestWatchReactor.make.pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => Effect.die("host unreachable"), + activity: () => Effect.die("host unreachable"), + }), + ), + ), + ); + for (let pass = 0; pass < 15; pass += 1) yield* reactor.sweep; + + const thread = yield* orchestrator.getThreadShell(threadId); + assert.isUndefined(thread?.pullRequests?.[0]?.watch); + const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]); + assert.deepEqual( + messages.flatMap((message) => message.notification?.summary ?? []), + ["#8: stopped watching, could not read it"], + ); + }), + ); + + it.effect("wakes a watched thread once for failed checks and a review comment", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-pull-request-watch-wake"); + const projectId = ProjectId.make("pr-watch-wake-project"); + yield* seedProject({ + projectId, + title: "Watch wake", + workspaceRoot: "/workspace/watch", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-wake-create"), + threadId, + projectId, + title: "Watch wake", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 7 }; + const url = "https://github.com/pingdotgg/t3code/pull/7"; + yield* orchestrator.dispatch({ + type: "thread.pull-request.link", + commandId: CommandId.make("pr-watch-wake-link"), + threadId, + ...key, + url, + source: "agent", + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-wake-start"), + threadId, + ...key, + watching: true, + }); + + const at = "2026-10-02T12:00:00.000Z"; + const detail: PullRequestDetail = { + provider: "github", + capabilities: { + diff: true, + comment: true, + actions: [], + mergeMethods: [], + search: false, + review: { inlineComment: false, reply: false, resolve: false, verdicts: [] }, + reviewers: { request: false, listCandidates: false }, + }, + viewerPermissions: { + actions: [], + comment: true, + resolve: true, + verdicts: [], + requestReviewers: false, + }, + projectId, + projectTitle: "Watch wake", + workspaceRoot: "/workspace/watch", + repository: key.repository, + number: key.number, + title: "Watched pull request", + body: "", + url, + author: { login: "agent-user", name: null, avatarUrl: null }, + state: "open", + isDraft: false, + mergeability: "mergeable", + additions: 1, + deletions: 0, + changedFiles: 1, + headBranch: "feature", + headSha: "abc1234def", + baseBranch: "main", + createdAt: at, + updatedAt: at, + mergedAt: null, + closedAt: null, + reviewers: [], + labels: [], + checks: [{ name: "lint", status: "failure", description: null, url: null }], + mergeCapabilities: { merge: true, squash: true, rebase: true }, + viewer: "agent-user", + }; + const reactor = yield* PullRequestWatchReactor.make.pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => Effect.succeed(detail), + activity: () => + Effect.succeed({ + comments: [ + { + id: "review-1", + kind: "review-comment", + author: { login: "reviewer", name: null, avatarUrl: null }, + body: "One more thing.", + createdAt: "2999-01-01T00:00:00.000Z", + url: null, + path: "src/index.ts", + reviewState: null, + }, + ], + commentCount: 1, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ), + ), + ); + yield* reactor.sweep; + yield* reactor.sweep; + + const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]); + assert.deepEqual( + messages.flatMap((message) => + message.notification === undefined ? [] : [message.notification.summary], + ), + ["#7: checks failed, new comments"], + ); + const watch = (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch; + assert.deepEqual( + { headSha: watch?.headSha, failedChecks: watch?.failedChecks, wakes: watch?.wakes }, + { headSha: "abc1234def", failedChecks: ["lint"], wakes: 0 }, + ); + }), + ); + it.effect("persists rejected command receipts across retries", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 4cc834dddd62..b9cad107409a 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -153,6 +153,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray( dispatch: orchestrator.dispatch, getThreadRecords: orchestrator.getThreadRecords, getThreadProjection: orchestrator.getThreadProjection, + recoverDelegatedTask: orchestrator.recoverDelegatedTask, + delegatedTaskResultPending: orchestrator.delegatedTaskResultPending, }); }), ).pipe(Layer.provide(orchestratorProvided)); @@ -498,6 +500,8 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( Orchestrator.OrchestratorV2, Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + // As in serverRuntimeStartup: after runtime recovery, before the worker. + yield* orchestrator.recoverDelegatedTasks; yield* EffectWorker.runDaemon.pipe(Effect.forkScoped); return orchestrator; }), diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_interrupt/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_interrupt/output.ts index 120f1cfc435a..c58112b37202 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_interrupt/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_interrupt/output.ts @@ -44,7 +44,7 @@ export function assertClaudeBackgroundTaskInterruptOutput( projection.turnItems.flatMap((item) => item.type === "command_execution" ? [item.status] : [], ), - ["completed", "failed"], - "the background launch completed; the interrupted foreground command did not", + ["completed", "interrupted"], + "the background launch completed; the foreground command was interrupted", ); } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/claude_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/claude_output.ts index 72884607068b..d90531499a80 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/claude_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/claude_output.ts @@ -81,7 +81,7 @@ export function assertTurnInterruptMidToolClaudeOutput( assert.isDefined(commandItem); assert.isDefined(interruptRequest); assert.isDefined(interruptResult); - assert.equal(commandItem.status, "failed"); + assert.equal(commandItem.status, "interrupted"); assert.include(commandItem.input, "node -e"); assert.equal(interruptRequest.status, "completed"); assert.equal(interruptResult.status, "interrupted"); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_restart/claude_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_restart/claude_output.ts index 1da224a8485b..f05b470d32d8 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_restart/claude_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_restart/claude_output.ts @@ -111,7 +111,7 @@ export function assertTurnInterruptRestartClaudeOutput( assert.equal(projection.providerThreads[0]?.status, "idle"); const commandItem = projection.turnItems.find((item) => item.type === "command_execution"); assert.isDefined(commandItem); - assert.equal(commandItem.status, "failed"); + assert.equal(commandItem.status, "interrupted"); assert.include(commandItem.input, "node -e"); const outboundFrames = transcript.entries.flatMap((entry) => diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index cccc826478b7..9c1115ca0df7 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -209,6 +209,36 @@ describe("threadHistoryPaging", () => { ); }); + it("pages agent-only child transcripts instead of dropping their earlier activity", () => { + const commandRows = Array.from({ length: 90 }, (_, index) => makeRow(index + 1)); + const first = makeRow(0); + const prompt = { + ...first, + item: { + ...first.item, + type: "user_message" as const, + createdBy: "agent" as const, + creationSource: "provider" as const, + inputIntent: "turn_start" as const, + messageId: MessageId.make("child-prompt"), + text: "Inspect this project", + attachments: [], + }, + } as OrchestrationV2ProjectedTurnItem; + const items = [prompt, ...commandRows]; + const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 }); + + expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems); + expect(recent.hasMoreHistory).toBe(true); + const older = selectHistoryPageFromCursor({ + items, + cursor: recent.nextCursor!, + snapshotSequence: 1, + }); + expect(older.items[0]?.item.type).toBe("user_message"); + expect([...older.items, ...recent.items]).toHaveLength(items.length); + }); + it("encodes opaque cursors with stable source identity", () => { const cursor = encodeThreadHistoryCursor({ snapshotSequence: 9, diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 98ae11afdad0..a2e6c87e20df 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -185,7 +185,7 @@ function selectOlderTimelinePage(input: { let encodedBytes = 0; let userTurns = 0; let rawTurns = 0; - const turnLimit = input.items.slice(0, end).some((row) => isThreadHistoryTurnStart(row.item)) + const turnLimit = input.items.slice(0, end).some((row) => isThreadHistoryUserTurn(row.item)) ? policy.maxUserTurns : undefined; for (let index = end - 1; index >= 0; index -= 1) { diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index aab4d78f4d71..9a5c8b99ce7d 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -6,6 +6,7 @@ import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -1186,26 +1187,24 @@ it.effect("memoizes editor discovery and refreshes after the cache window", () = ); }); -// A client that disconnects mid-scan interrupts the shared discovery effect on -// the connection fiber. The cache must not retain that interrupt: doing so -// replayed it to every later connect for the whole TTL, so `server.getConfig` -// failed and no client could reconnect until the server restarted. -it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => { +// Connects run discovery under a timeout and may disconnect mid-scan. Neither +// may cancel the scan: on a busy host every connect would time out partway +// through, cache nothing, and leave every client without editors. +it.effect("keeps scanning after the caller is interrupted and shares that scan", () => { const fileInfo = { type: "File" } as FileSystem.File.Info; - let blockFirstScan = true; - let scans = 0; + const release = Deferred.makeUnsafe(); + let parkedStats = 0; const launcherLayer = ExternalLauncher.layer.pipe( Layer.provide( Layer.mergeAll( FileSystem.layerNoop({ - // The first scan parks inside `stat` so the interrupt lands while - // discovery is in flight, which is what a client disconnecting - // mid-connect does to the shared effect. + // Scans park inside `stat` until released, so the interrupt lands + // while discovery is in flight. stat: () => Effect.gen(function* () { - scans += 1; - if (blockFirstScan) { - return yield* Effect.never; + if (!Deferred.isDoneUnsafe(release)) { + parkedStats += 1; + yield* Deferred.await(release); } return fileInfo; }), @@ -1222,16 +1221,18 @@ it.effect("rescans after an interrupted discovery instead of caching the interru return Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; - const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors()); + const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors()); yield* Effect.yieldNow; - yield* Fiber.interrupt(fiber); + yield* Fiber.interrupt(interrupted); - // The next connect must still get a real answer well inside the TTL. - blockFirstScan = false; - scans = 0; - const editors = yield* launcher.resolveAvailableEditors(); + // The next connect joins the running scan instead of starting its own. + const next = yield* Effect.forkChild(launcher.resolveAvailableEditors()); + yield* Effect.yieldNow; + assert.equal(parkedStats, 1); + + yield* Deferred.succeed(release, undefined); + const editors = yield* Fiber.join(next); assert.equal(editors.includes("vscode"), true); - assert.isAbove(scans, 0); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index ab287e4d78ee..058318ea9d55 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -28,13 +28,16 @@ import { import * as Clock from "effect/Clock"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/unstable/process/ChildProcess"; import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; @@ -462,21 +465,21 @@ const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileMana // the discovered set for a bounded window so repeat connects skip even the // per-command cache lookups in @t3tools/shared/shell. // -// This deliberately does not use `Effect.cachedWithTTL`: that memoizes the -// first caller's Exit whatever it is, including an interrupt. Callers run this -// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`), -// so one client disconnecting mid-scan would cache the interrupt and replay it -// to every later connect for the whole TTL, breaking `server.getConfig` -// permanently. Storing only on success means an interrupted scan leaves the -// cache untouched and the next connect simply rescans. +// The scan runs on its own fiber in the service scope, and every caller awaits +// that one scan. Callers apply a timeout (`resolveAvailableEditorsForConfig`) +// and disconnect mid-connect; neither may cancel a scan other connects are +// waiting on, or throw away work a slow host (a busy server at startup, a +// long PATH) needs more than one connect to finish. A failed scan clears the +// entry so the next caller starts over rather than replaying the failure. // Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the // command-resolution cache in @t3tools/shared/shell, so a backward wall-clock // adjustment cannot keep an expired entry alive. const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n; interface EditorDiscoveryCacheEntry { - readonly editors: ReadonlyArray; - readonly expiresAtNanos: bigint; + readonly scan: Deferred.Deferred>; + /** Undefined while the scan is still running. */ + readonly expiresAtNanos: bigint | undefined; } /** @@ -760,27 +763,57 @@ export const make = Effect.gen(function* () { Effect.provideService(Path.Path, path), ); + const scope = yield* Scope.Scope; const editorDiscoveryCache = yield* Ref.make>( Option.none(), ); - const cachedAvailableEditors = Effect.gen(function* () { - const nowNanos = yield* Clock.currentTimeNanos; - const entry = yield* Ref.get(editorDiscoveryCache); - if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) { - return entry.value.editors; - } - const editors = yield* provideCommandResolutionServices(resolveAvailableEditors()).pipe( + const runEditorDiscovery = (scan: Deferred.Deferred>) => + provideCommandResolutionServices(resolveAvailableEditors()).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.onExit((exit) => + Effect.gen(function* () { + const expiresAtNanos = (yield* Clock.currentTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS; + yield* Ref.update(editorDiscoveryCache, (current) => + Option.isNone(current) || current.value.scan !== scan + ? current + : Exit.isSuccess(exit) + ? Option.some({ scan, expiresAtNanos }) + : Option.none(), + ); + yield* Deferred.done(scan, exit); + }), + ), + Effect.interruptible, + Effect.forkIn(scope), ); - yield* Ref.set( + // Claiming the cache entry and starting its scan must not be split by an + // interrupt, or the entry would wait on a scan that never runs. + const acquireEditorDiscovery = Effect.gen(function* () { + const nowNanos = yield* Clock.currentTimeNanos; + const [scan, isNewScan] = yield* Ref.modify( editorDiscoveryCache, - Option.some({ - editors, - expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS, - }), + ( + current, + ): [ + [EditorDiscoveryCacheEntry["scan"], boolean], + Option.Option, + ] => { + if ( + Option.isSome(current) && + (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos) + ) { + return [[current.value.scan, false], current]; + } + const scan = Deferred.makeUnsafe>(); + return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })]; + }, ); - return editors; - }); + if (isNewScan) { + yield* runEditorDiscovery(scan); + } + return scan; + }).pipe(Effect.uninterruptible); + const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await); return ExternalLauncher.of({ resolveAvailableEditors: () => cachedAvailableEditors, diff --git a/apps/server/src/provider/RuntimeInstructions.ts b/apps/server/src/provider/RuntimeInstructions.ts index afaba915d785..545e8be58443 100644 --- a/apps/server/src/provider/RuntimeInstructions.ts +++ b/apps/server/src/provider/RuntimeInstructions.ts @@ -1,5 +1,5 @@ const PULL_REQUEST_LINKING_INSTRUCTIONS = ` -When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked. +When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked. When asked to monitor, watch, or babysit a PR and watch_pull_request is available, call it and end your turn: T3 Code wakes you when checks finish, someone else comments, or the branch conflicts, so do not poll or run your own watcher. `; /** diff --git a/apps/server/src/provider/T3OrchestrationInstructions.test.ts b/apps/server/src/provider/T3OrchestrationInstructions.test.ts index dbcd209a136f..e625e40c1125 100644 --- a/apps/server/src/provider/T3OrchestrationInstructions.test.ts +++ b/apps/server/src/provider/T3OrchestrationInstructions.test.ts @@ -13,6 +13,11 @@ describe("T3 orchestration provider instructions", () => { assert.include(T3_CODE_ORCHESTRATION_INSTRUCTIONS, "ordinary top-level T3 conversations"); assert.include(T3_CODE_ORCHESTRATION_INSTRUCTIONS, "Never use them merely"); assert.include(T3_CODE_ORCHESTRATION_INSTRUCTIONS, "cross-provider"); + assert.include(T3_CODE_ORCHESTRATION_INSTRUCTIONS, "call `delegate_task` again"); + assert.include( + T3_CODE_ORCHESTRATION_INSTRUCTIONS, + "Do not use `t3_thread_send` on `childThreadId`", + ); }); it("documents structured schedules instead of JSON strings", () => { diff --git a/apps/server/src/provider/T3OrchestrationInstructions.ts b/apps/server/src/provider/T3OrchestrationInstructions.ts index ed510b879c0f..a70ef35bffcd 100644 --- a/apps/server/src/provider/T3OrchestrationInstructions.ts +++ b/apps/server/src/provider/T3OrchestrationInstructions.ts @@ -6,8 +6,9 @@ export const T3_CODE_ORCHESTRATION_INSTRUCTIONS = ` The \`t3-code\` MCP server provides app-owned orchestration. Treat these concepts distinctly: -- A delegated task/subagent is child work owned by the current thread. Use \`orchestrator_capabilities\` to discover the current provider/model IDs from the same live catalog as the composer, including configured custom models. Do not treat a native tool's model list as the full list of available subagent models. Prefer native subagent tools for same-provider work only when they support the chosen model. Use \`delegate_task\` with that provider instance and model when native tools cannot, including for same-provider work. Also use \`delegate_task\` for cross-provider or explicitly T3-owned child tasks. Retain each returned \`taskId\`, and use \`task_status\` or \`task_cancel\` to manage it. The returned \`childThreadId\` is backing storage for the subagent; do not replace delegation with ordinary thread creation. +- A delegated task/subagent is child work owned by the current thread. Use \`orchestrator_capabilities\` to discover the current provider/model IDs from the same live catalog as the composer, including configured custom models. Do not treat a native tool's model list as the full list of available subagent models. Prefer native subagent tools for same-provider work only when they support the chosen model. Use \`delegate_task\` with that provider instance and model when native tools cannot, including for same-provider work. Also use \`delegate_task\` for cross-provider or explicitly T3-owned child tasks. Retain each returned \`taskId\`, and use \`task_status\` or \`task_cancel\` to manage it. The returned \`childThreadId\` is backing storage for the subagent, not the target for starting another delegated review round. - \`t3_thread_launch\` and \`create_threads\` create ordinary top-level T3 conversations. Use them only when the user explicitly asks for separate/new/top-level threads or conversations. Never use them merely because the user said "subagent" or requested parallel delegated work. +- For every T3 delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. Do not use \`t3_thread_send\` on \`childThreadId\` to continue a delegated review. - \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule. By default runs return to the current thread; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling, report the returned cadence and next run time. ### Choose the workspace before starting a new thread diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.ts index 020b571fe248..f40cff8f50bf 100644 --- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts +++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts @@ -52,7 +52,7 @@ import { decodePullRequestActivityJson, decodePullRequestDetailJson, decodePullRequestCoreJson, - PULL_REQUEST_CORE_GRAPHQL_QUERY, + pullRequestCoreGraphQlQuery, type GitHubPullRequestCore, type GitHubPullRequestSummary, decodePullRequestPreviewJson, @@ -1595,7 +1595,7 @@ export const make = Effect.gen(function* () { ["-F", `number=${input.number}`], ["-f", `headRef=refs/pull/${input.number}/head`], ], - query: PULL_REQUEST_CORE_GRAPHQL_QUERY, + query: pullRequestCoreGraphQlQuery(input.host), decode: decodePullRequestCoreJson, }), ), diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.ts index ed4312c125c7..cc370637c601 100644 --- a/apps/server/src/pullRequest/PullRequestProvider.ts +++ b/apps/server/src/pullRequest/PullRequestProvider.ts @@ -213,6 +213,8 @@ export interface ProviderChangeRequestStat { } export interface ProviderChangeRequestDetail extends ProviderChangeRequest { + /** The head commit, where the host's detail read reports it. */ + readonly headSha?: string | null; readonly body: string; readonly changedFiles: number; readonly mergedAt: string | null; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 44c175ab652f..293318f91c4b 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1697,6 +1697,7 @@ export const make = Effect.gen(function* () { ...(changeRequest.headRepositoryNameWithOwner === undefined ? {} : { headRepositoryNameWithOwner: changeRequest.headRepositoryNameWithOwner }), + ...(changeRequest.headSha ? { headSha: changeRequest.headSha } : {}), baseBranch: changeRequest.baseBranch, createdAt: changeRequest.createdAt, updatedAt: changeRequest.updatedAt, diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts index 12239a2af0ee..1393ab6e6b6a 100644 --- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts +++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts @@ -26,6 +26,7 @@ import { decodeWorkflowRunApprovalsJson, reviewThreadConversation, REVIEW_THREADS_GRAPHQL_QUERY, + pullRequestCoreGraphQlQuery, pullRequestSearchGraphQlQuery, } from "./gitHubPullRequestJson.ts"; @@ -285,6 +286,25 @@ describe("pull request detail decoding", () => { ]); }); + it("keeps what branch protection requires, and asks for it on github.com only", () => { + const raw = JSON.parse(detailJson) as Record; + const detail = expectSuccess( + decodePullRequestDetailJson( + JSON.stringify({ + ...raw, + statusCheckRollup: [ + { __typename: "CheckRun", name: "test", status: "IN_PROGRESS", isRequired: true }, + { __typename: "StatusContext", context: "bot", state: "PENDING", isRequired: false }, + { __typename: "StatusContext", context: "legacy", state: "SUCCESS" }, + ], + }), + ), + ); + expect(detail.checks.map((check) => check.required)).toEqual([true, false, undefined]); + expect(pullRequestCoreGraphQlQuery("github.com")).toContain("isRequired"); + expect(pullRequestCoreGraphQlQuery("github.example.com")).not.toContain("isRequired"); + }); + it("keeps a workflow waiting for approval out of the passing state", () => { const raw = JSON.parse(detailJson) as Record; const detail = expectSuccess( diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.ts index 8e3a9ee330b8..d1600754b50b 100644 --- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts +++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts @@ -93,6 +93,8 @@ const RawCheckSchema = Schema.Struct({ workflowName: Schema.optional(Schema.NullOr(Schema.String)), startedAt: Schema.optional(Schema.NullOr(Schema.String)), completedAt: Schema.optional(Schema.NullOr(Schema.String)), + /** Branch protection requires this check; read by the detail query on github.com only. */ + isRequired: Schema.optional(Schema.NullOr(Schema.Boolean)), }); const RawListItemSchema = Schema.Struct({ @@ -706,8 +708,15 @@ export const PULL_REQUEST_LIST_JSON_FIELDS = export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,isCrossRepository,headRepositoryOwner,headRefOid,autoMergeRequest`; -/** Pull refs let the comparison share the detail read without first resolving a fork branch. */ -export const PULL_REQUEST_CORE_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $headRef: String!) { +/** + * Pull refs let the comparison share the detail read without first resolving a fork branch. + * `isRequired` is asked for on github.com only: an older Enterprise server may not know it, and + * an unknown field fails the whole read. + */ +export const pullRequestCoreGraphQlQuery = (host: string) => { + const required = + host.toLowerCase() === "github.com" ? " isRequired(pullRequestNumber: $number)" : ""; + return `query($owner: String!, $name: String!, $number: Int!, $headRef: String!) { repository(owner: $owner, name: $name) { mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerPermission pullRequest(number: $number) { @@ -727,9 +736,9 @@ export const PULL_REQUEST_CORE_GRAPHQL_QUERY = `query($owner: String!, $name: St nodes { commit { statusCheckRollup { contexts(first: 100) { nodes { __typename - ... on StatusContext { context state targetUrl createdAt description } + ... on StatusContext { context state targetUrl createdAt description${required} } ... on CheckRun { - name status conclusion startedAt completedAt detailsUrl + name status conclusion startedAt completedAt detailsUrl${required} checkSuite { workflowRun { workflow { name } } } } } @@ -739,6 +748,7 @@ export const PULL_REQUEST_CORE_GRAPHQL_QUERY = `query($owner: String!, $name: St } } }`; +}; export const PULL_REQUEST_PREVIEW_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { @@ -1468,6 +1478,7 @@ function toCheckEntries( status: toCheckStatus(check), description: trimmed(check.description), url: trimmed(check.detailsUrl) ?? trimmed(check.targetUrl), + ...(typeof check.isRequired === "boolean" ? { required: check.isRequired } : {}), }, workflowName: trimmed(check.workflowName), at: realTimestamp(check.completedAt) ?? realTimestamp(check.startedAt), diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index a90226f67c7e..003403fc5c09 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -206,6 +206,8 @@ const makeTestRelay = Effect.fnUntraced(function* ( waitForThread: unused, interruptThread: unused, getThreadEventSequence: unused, + recoverDelegatedTask: unused, + delegatedTaskResultPending: unused, streamStoredEvents: Stream.empty, streamStoredEventsFrom: () => Stream.empty, streamDomainEvents: options.domainEvents ?? Stream.empty, diff --git a/apps/server/src/scheduling/Scheduler.test.ts b/apps/server/src/scheduling/Scheduler.test.ts index dd3ac3948a12..fbbf15ced75e 100644 --- a/apps/server/src/scheduling/Scheduler.test.ts +++ b/apps/server/src/scheduling/Scheduler.test.ts @@ -6,6 +6,7 @@ import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; +import * as ServerActivation from "../serverActivation.ts"; import * as Scheduler from "./Scheduler.ts"; it.effect("keeps other sources running after a source defects", () => @@ -84,3 +85,26 @@ it.effect("unregisters closed sources and interrupts their in-flight work", () = assert.equal(yield* Ref.get(runs), 1); }).pipe(Effect.provide(Scheduler.layer)), ); + +it.effect("holds due work and the clock until startup recovery activates the server", () => + Effect.gen(function* () { + const activation = yield* Deferred.make(); + const runs = yield* Ref.make(0); + const ran = yield* Deferred.make(); + yield* Effect.gen(function* () { + const scheduler = yield* Scheduler.Scheduler; + yield* scheduler.register( + "due", + Ref.update(runs, (n) => n + 1).pipe(Effect.andThen(Deferred.succeed(ran, undefined))), + ); + yield* TestClock.adjust("10 seconds"); + assert.equal(yield* Ref.get(runs), 0); + yield* Deferred.succeed(activation, undefined); + yield* Deferred.await(ran); + }).pipe( + Effect.provide(Scheduler.layer), + Effect.provideService(ServerActivation.ServerActivation, Deferred.await(activation)), + ); + assert.isAtLeast(yield* Ref.get(runs), 1); + }), +); diff --git a/apps/server/src/scheduling/Scheduler.ts b/apps/server/src/scheduling/Scheduler.ts index 957ba11e2ea0..e2214094cffb 100644 --- a/apps/server/src/scheduling/Scheduler.ts +++ b/apps/server/src/scheduling/Scheduler.ts @@ -6,6 +6,8 @@ import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; +import { forkParked } from "../serverActivation.ts"; + /** Sources load due work from their durable state; registration owns its execution lifetime. */ export class Scheduler extends Context.Service< Scheduler, @@ -47,14 +49,15 @@ const make = Effect.gen(function* () { return next; }), ); - yield* run; + // Due work waits for startup recovery, which would cancel runs it started. + yield* forkParked(run); }); const tick = Ref.get(sources).pipe( Effect.flatMap((current) => Effect.forEach(current.values(), (run) => run, { discard: true })), ); // One clock for all due-work sources. A slow source cannot block another // source or overlap itself, and no extra missed-tick backlog is queued. - yield* Effect.sleep("5 seconds").pipe(Effect.andThen(tick), Effect.forever, Effect.forkScoped); + yield* forkParked(Effect.sleep("5 seconds").pipe(Effect.andThen(tick), Effect.forever)); return Scheduler.of({ register }); }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ac9326aaffed..01385136f832 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -4,6 +4,7 @@ import * as Random from "effect/Random"; import * as Semaphore from "effect/Semaphore"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; +import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -528,6 +529,16 @@ const RuntimeCoreDependenciesBaseLive = Layer.mergeAll( Layer.provide(PullRequestServiceLive), Layer.provide(ProjectionStoreV2.layer), ), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* PullRequestWatchReactor.PullRequestWatchReactor; + yield* service.start(); + }), + ).pipe( + Layer.provide(PullRequestWatchReactor.layer), + Layer.provide(PullRequestServiceLive), + Layer.provide(ProjectionStoreV2.layer), + ), // Subscribes to `account.rate-limits.updated` so usage bars track live // telemetry instead of waiting for the next status probe. ProviderUsageLimitsIngestionLive, diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index a89d010fab75..9aa6ebfaa45f 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -31,11 +31,20 @@ it.effect("starts without scanning or rebuilding projection history", () => const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({ importLegacyShells: record("import"), recover: record("recover").pipe(Effect.as({ closedRequests: 2 })), + recoverDelegatedTasks: record("delegated"), startEffectWorker: record("worker"), autoBootstrap: record("bootstrap").pipe(Effect.as({ projectId: "project-1" })), }); - assert.deepEqual(yield* Ref.get(calls), ["import", "recover", "worker", "bootstrap"]); + // Delegated recovery reads the runs recovery terminalizes, and settles them + // before the worker runs restart continuations that would otherwise race it. + assert.deepEqual(yield* Ref.get(calls), [ + "import", + "recover", + "delegated", + "worker", + "bootstrap", + ]); assert.deepEqual(result, { recovery: { closedRequests: 2 }, bootstrap: { projectId: "project-1" }, diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 0f51cfcbfeda..e5e14a45f214 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -32,6 +32,7 @@ import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; +import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; @@ -387,21 +388,26 @@ export function runOrderedV2StartupPhases< Bootstrap, ImportError, RecoveryError, + DelegationError, WorkerError, BootstrapError, ImportContext, RecoveryContext, + DelegationContext, WorkerContext, BootstrapContext, >(input: { readonly importLegacyShells: Effect.Effect; readonly recover: Effect.Effect; + /** Settles delegated tasks whose runs recovery just terminalized. */ + readonly recoverDelegatedTasks: Effect.Effect; readonly startEffectWorker: Effect.Effect; readonly autoBootstrap: Effect.Effect; }) { return Effect.gen(function* () { yield* input.importLegacyShells; const recovery = yield* input.recover; + yield* input.recoverDelegatedTasks; yield* input.startEffectWorker; const bootstrap = yield* input.autoBootstrap; return { recovery, bootstrap } as const; @@ -414,6 +420,7 @@ const make = (options?: StartupOptions) => const keybindings = yield* Keybindings.Keybindings; const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const orchestrator = yield* Orchestrator.OrchestratorV2; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; @@ -510,6 +517,10 @@ const make = (options?: StartupOptions) => ), ), recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), + recoverDelegatedTasks: runStartupPhase( + "orchestration-v2.delegated-tasks.recover", + orchestrator.recoverDelegatedTasks, + ), startEffectWorker: runStartupPhase( "orchestration-v2.effect-worker.start", startEffectWorkerWithRelay({ diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index cc14c77ae494..b343870b1089 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -23,10 +23,12 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as ServerConfig from "./config.ts"; import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts"; +import { writeFileStringAtomically } from "./atomicWrite.ts"; import * as ServerSettingsModule from "./serverSettings.ts"; import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts"; @@ -131,6 +133,114 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("saves through a symlinked settings file without replacing the link", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const service = yield* ServerSettingsModule.ServerSettingsService; + const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); + const linkedSettingsPath = path.join(dotfiles, "settings.json"); + yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`); + yield* fs.remove(config.settingsPath, { force: true }); + yield* fs.symlink(linkedSettingsPath, config.settingsPath); + + yield* service.updateSettings({ responseStreamingMode: "paragraph" }); + + assert.equal(yield* fs.readLink(config.settingsPath), linkedSettingsPath); + const persisted = yield* decodeServerSettingsJson( + yield* fs.readFileString(linkedSettingsPath), + ); + assert.equal(persisted.responseStreamingMode, "paragraph"); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("reloads when the destination of a symlinked settings file changes", () => + Effect.scoped( + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const service = yield* ServerSettingsModule.ServerSettingsService; + const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); + const linkedSettingsPath = path.join(dotfiles, "settings.json"); + yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`); + yield* fs.remove(config.settingsPath, { force: true }); + yield* fs.symlink(linkedSettingsPath, config.settingsPath); + yield* service.start; + const changes = yield* service.subscribeChanges; + + yield* writeFileStringAtomically({ + filePath: linkedSettingsPath, + contents: `{ "responseStreamingMode": "paragraph" }`, + }); + + const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds")); + assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph"); + }), + ).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("follows a settings link that is repointed to another directory", () => + Effect.scoped( + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const service = yield* ServerSettingsModule.ServerSettingsService; + const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); + const firstSettingsPath = path.join(dotfiles, "first", "settings.json"); + const secondSettingsPath = path.join(dotfiles, "second", "settings.json"); + yield* fs.makeDirectory(path.dirname(firstSettingsPath), { recursive: true }); + yield* fs.makeDirectory(path.dirname(secondSettingsPath), { recursive: true }); + yield* fs.writeFileString(firstSettingsPath, `{ "responseStreamingMode": "turn" }`); + yield* fs.writeFileString(secondSettingsPath, `{ "responseStreamingMode": "paragraph" }`); + yield* fs.remove(config.settingsPath, { force: true }); + yield* fs.symlink(firstSettingsPath, config.settingsPath); + yield* service.start; + + const repointChanges = yield* service.subscribeChanges; + yield* fs.remove(config.settingsPath); + yield* fs.symlink(secondSettingsPath, config.settingsPath); + const repointed = yield* repointChanges.pipe(Stream.runHead, Effect.timeout("2 seconds")); + assert.equal(Option.getOrUndefined(repointed)?.responseStreamingMode, "paragraph"); + + const editChanges = yield* service.subscribeChanges; + yield* writeFileStringAtomically({ + filePath: secondSettingsPath, + contents: `{ "responseStreamingMode": "turn" }`, + }); + const edited = yield* editChanges.pipe(Stream.runHead, Effect.timeout("2 seconds")); + assert.equal(Option.getOrUndefined(edited)?.responseStreamingMode, "turn"); + }), + ).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("reloads when a dangling settings link gets its destination", () => + Effect.scoped( + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const service = yield* ServerSettingsModule.ServerSettingsService; + const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); + const linkedSettingsPath = path.join(dotfiles, "not-yet", "settings.json"); + yield* fs.remove(config.settingsPath, { force: true }); + yield* fs.symlink(linkedSettingsPath, config.settingsPath); + yield* service.start; + const changes = yield* service.subscribeChanges; + + yield* writeFileStringAtomically({ + filePath: linkedSettingsPath, + contents: `{ "responseStreamingMode": "paragraph" }`, + }); + + const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds")); + assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph"); + }), + ).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())), + ); + it.effect("preserves context when reading a provider environment secret fails", () => { const platformCause = PlatformError.systemError({ _tag: "PermissionDenied", diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 372506e0e508..7d4d8b4c268e 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -52,6 +52,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { writeFileStringAtomically } from "./atomicWrite.ts"; +import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import * as ServerConfig from "./config.ts"; import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson"; @@ -1181,10 +1182,24 @@ const make = Effect.gen(function* () { }), ); + const watchFileChanges = (filePath: string) => { + const directory = pathService.dirname(filePath); + const fileName = pathService.basename(filePath); + const resolvedFilePath = pathService.resolve(filePath); + return fs + .watch(directory) + .pipe( + Stream.filter( + (event) => + event.path === fileName || + event.path === filePath || + pathService.resolve(directory, event.path) === resolvedFilePath, + ), + ); + }; + const startWatcher = Effect.gen(function* () { const settingsDir = pathService.dirname(settingsPath); - const settingsFile = pathService.basename(settingsPath); - const settingsPathResolved = pathService.resolve(settingsPath); yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe( Effect.mapError( @@ -1199,19 +1214,43 @@ const make = Effect.gen(function* () { const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); + // A symlinked settings file is rewritten in its destination's directory, + // which a watch on the link's directory never sees. The link is resolved + // again whenever it changes, so repointing it moves the watch along. + const watchLinkTarget = Effect.gen(function* () { + const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, pathService), + ); + if (linkTargetPath === pathService.resolve(settingsPath)) { + return Option.none(); + } + yield* fs + .makeDirectory(pathService.dirname(linkTargetPath), { recursive: true }) + .pipe(Effect.ignore({ log: true })); + return Option.some(linkTargetPath); + }).pipe(Effect.orElseSucceed(() => Option.none())); + + const initialLinkTarget = yield* watchLinkTarget; + const linkTargetEvents = Stream.make(initialLinkTarget).pipe( + Stream.concat(watchFileChanges(settingsPath).pipe(Stream.mapEffect(() => watchLinkTarget))), + Stream.changes, + Stream.switchMap( + Option.match({ + onNone: () => Stream.empty, + onSome: (linkTargetPath) => + watchFileChanges(linkTargetPath).pipe(Stream.ignore({ log: true })), + }), + ), + ); + // Debounce watch events so the file is fully written before we read it. // Editors emit multiple events per save (truncate, write, rename) and // `fs.watch` can fire before the content has been flushed to disk. - const debouncedSettingsEvents = fs.watch(settingsDir).pipe( - Stream.filter((event) => { - return ( - event.path === settingsFile || - event.path === settingsPath || - pathService.resolve(settingsDir, event.path) === settingsPathResolved - ); - }), - Stream.debounce(Duration.millis(100)), - ); + const debouncedSettingsEvents = Stream.merge( + watchFileChanges(settingsPath), + linkTargetEvents, + ).pipe(Stream.debounce(Duration.millis(100))); yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe( Effect.ignoreCause({ log: true }), diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 29fcecdc234e..62345d8472e1 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off - the suite seeds and grows real // transcript trees on disk, outside the service's Effect FileSystem. +import * as NodeChildProcess from "node:child_process"; import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; @@ -34,6 +35,7 @@ import * as UsageService from "./UsageService.ts"; const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeUnknownJsonString = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown)); function claudeLine(id: number, outputTokens: number, model = "claude-fable-5"): string { return `${JSON.stringify({ @@ -116,6 +118,41 @@ const serviceLayers = (input: { ), ); +/** Outside `NARROW_WINDOW`, inside `WINDOW`. Seconds, as `utimes` takes them. */ +const BEFORE_NARROW_WINDOW = Date.parse("2026-08-01T10:00:00Z") / 1000; +const NARROW_WINDOW: UsageSummaryInput = { + timeZone: "UTC", + sinceDay: UsageDay.make("2026-09-01"), + untilDay: UsageDay.make("2026-09-02"), +}; + +/** + * A FIFO named like a transcript. A scan's read of it waits in `open` until + * `openGate`, then fails at once, so a gate holds that scan's directory reads + * in flight. Each waiting gate holds one libuv pool thread; keep at most three. + */ +const makeGate = (path: string, lastWriteSeconds?: number) => + Effect.promise(async () => { + NodeChildProcess.execFileSync("mkfifo", [path]); + if (lastWriteSeconds !== undefined) { + await NodeFSP.utimes(path, lastWriteSeconds, lastWriteSeconds); + } + }); + +/** + * Returns once a scan has opened the gate. A scan opens every file of a + * directory at once, so it then holds the directory's transcripts open too. + */ +const openGate = (path: string) => + Effect.promise(async () => (await NodeFSP.open(path, "w")).close()); + +/** Replaces a file by rename, so a scan holding the old one keeps reading it. */ +const replaceFile = (path: string, content: string) => + Effect.promise(async () => { + await NodeFSP.writeFile(path + ".next", content); + await NodeFSP.rename(path + ".next", path); + }); + function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens: number } }[] }) { return summary.buckets.reduce((sum, bucket) => sum + bucket.totals.outputTokens, 0); } @@ -788,6 +825,98 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live( + "upgrades a v4 cache: reprices live Codex tiers, keeps deleted rollouts, leaves v4 intact", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const sessions = NodePath.join(home, "codex", "sessions"); + const rollout = (sessionId: string, outputTokens: number) => + [ + { type: "session_meta", payload: { id: sessionId } }, + { type: "turn_context", payload: { model: "gpt-6-astra" } }, + { + type: "event_msg", + payload: { + type: "thread_settings_applied", + thread_settings: { service_tier: "ultrafast" }, + }, + }, + { + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { last_token_usage: { input_tokens: 0, output_tokens: outputTokens } }, + }, + }, + ] + .map((line) => encodeUnknownJsonString(line)) + .join("\n") + "\n"; + const live = NodePath.join(sessions, "live.jsonl"); + const deleted = NodePath.join(sessions, "deleted.jsonl"); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(sessions, { recursive: true }); + await NodeFSP.writeFile(live, rollout("live", 10)); + await NodeFSP.writeFile(deleted, rollout("deleted", 20)); + }); + + yield* Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const cachePath = NodePath.join(stateDir, "usage-scan-cache-v5.json"); + const legacyPath = NodePath.join(stateDir, "usage-scan-cache.json"); + yield* (yield* UsageService.make).readSummary(WINDOW); + + // Rewrite the cache as a v4 server left it: every Codex record at + // speed 0 (standard), and no tier in the reducer state. + const legacy = yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record; + }; + for (const file of Object.values(document.files)) { + file.r = file.r.map((row) => [...row.slice(0, 10), 0]); + delete file.cs.speed; + } + const text = encodeUnknownJsonString({ ...document, version: 4 }); + await NodeFSP.writeFile(legacyPath, text); + await NodeFSP.rm(cachePath); + await NodeFSP.rm(deleted); + return text; + }); + + const summary = yield* (yield* UsageService.make).readSummary(WINDOW); + // The live rollout re-parses at the ultrafast rate (10 x 6); the + // deleted one keeps its saved v4 usage at the standard rate (20 x 1). + assert.strictEqual(totalOutputTokens(summary), 30); + assert.strictEqual( + summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0), + 80, + ); + // A v4 server sharing this state directory still finds its own cache. + assert.strictEqual( + yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")), + legacy, + ); + }).pipe( + Effect.provide( + serviceLayers({ + prefix: "usage-service-v4-upgrade-test", + home, + settings, + ratesDocument: { + "gpt-6-astra": { + input_cost_per_token: 0, + output_cost_per_token: 1, + input_cost_per_token_ultrafast: 0, + output_cost_per_token_ultrafast: 6, + }, + }, + }), + ), + ); + }).pipe(Effect.scoped), + ); + it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; @@ -879,6 +1008,157 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("credits the same copy of a duplicate after its transcripts are deleted", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + // The walk-first file is the original, padded so it finishes parsing + // after the small fork copy that repeats its record under a new session. + const [first = "", second = ""] = yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + return (await NodeFSP.readdir(dir)).map((name) => NodePath.join(dir, name)); + }); + const forked = (line: string) => line.replace('"session-1"', '"session-2"'); + yield* Effect.promise(async () => { + await NodeFSP.writeFile( + first, + claudeLine(1, 5).replace( + '"message":', + '"padding":' + encodeUnknownJsonString("x".repeat(9 * 1024 * 1024)) + ',"message":', + ), + ); + await NodeFSP.writeFile(second, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const live = yield* service.readSummary(WINDOW); + assert.strictEqual(live.buckets[0]?.sessions, 2); + + yield* Effect.promise(() => Promise.all([NodeFSP.rm(first), NodeFSP.rm(second)])); + const saved = yield* service.readSummary(WINDOW); + assert.deepStrictEqual(saved.buckets, live.buckets); + assert.deepStrictEqual(saved.sources, live.sources); + const restored = yield* (yield* UsageService.make).readSummary(WINDOW); + assert.deepStrictEqual(restored.buckets, live.buckets); + }).pipe( + Effect.provide(serviceLayers({ prefix: "usage-service-copy-order-test", home, settings })), + ); + }).pipe(Effect.scoped), + ); + + it.live.skipIf(HostProcessPlatform.defaultValue() === "win32")( + "keeps a newer cached read when a slower scan of another window finishes later", + () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + const probe = NodePath.join(dir, "probe.jsonl"); + const hold = NodePath.join(dir, "hold.jsonl"); + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); + yield* makeGate(probe, BEFORE_NARROW_WINDOW); + yield* makeGate(hold, BEFORE_NARROW_WINDOW); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const wide = yield* service.readSummary(WINDOW).pipe(Effect.forkChild); + yield* openGate(probe); + yield* replaceFile(transcript, claudeLine(1, 5) + claudeLine(2, 7)); + // The narrow scan caches the newer read while the wide one waits. + yield* service.readSummary(NARROW_WINDOW); + yield* openGate(hold); + yield* Fiber.join(wide); + + yield* Effect.promise(() => + Promise.all([transcript, probe, hold].map((path) => NodeFSP.rm(path))), + ); + assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 12); + }).pipe( + Effect.provide( + serviceLayers({ prefix: "usage-service-stale-read-test", home, settings }), + ), + ); + }).pipe(Effect.scoped), + ); + + it.live.skipIf(HostProcessPlatform.defaultValue() === "win32")( + "keeps the later read when a scan that read earlier finishes first", + () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + const gate = (name: string) => NodePath.join(dir, `${name}.jsonl`); + const wideProbe = gate("wide-probe"); + const wideHold = gate("wide-hold"); + const narrowProbe = gate("narrow-probe"); + const narrowHold = gate("narrow-hold"); + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); + yield* makeGate(wideProbe, BEFORE_NARROW_WINDOW); + yield* makeGate(wideHold, BEFORE_NARROW_WINDOW); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const wide = yield* service.readSummary(WINDOW).pipe(Effect.forkChild); + yield* openGate(wideProbe); + yield* replaceFile(transcript, claudeLine(1, 5) + claudeLine(2, 7)); + // Made after the wide scan's walk, so only the narrow scan waits on them. + yield* makeGate(narrowProbe); + yield* makeGate(narrowHold); + const narrow = yield* service.readSummary(NARROW_WINDOW).pipe(Effect.forkChild); + yield* openGate(narrowProbe); + // Both scans started from an empty cache entry; the earlier read lands first. + yield* openGate(wideHold); + yield* Fiber.join(wide); + yield* openGate(narrowHold); + yield* Fiber.join(narrow); + + yield* Effect.promise(() => + Promise.all( + [transcript, wideProbe, wideHold, narrowProbe, narrowHold].map((path) => + NodeFSP.rm(path), + ), + ), + ); + assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 12); + }).pipe( + Effect.provide(serviceLayers({ prefix: "usage-service-late-read-test", home, settings })), + ); + }).pipe(Effect.scoped), + ); + + it.live("reports saved usage of a removed directory only for windows it reaches", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(async () => { + await NodeFSP.writeFile(transcript, claudeLine(1, 5)); + const lastWrite = Date.parse("2026-08-01T10:00:00Z") / 1000; + await NodeFSP.utimes(transcript, lastWrite, lastWrite); + }); + const service = yield* UsageService.make.pipe( + Effect.provide( + serviceLayers({ prefix: "usage-service-saved-window-test", home, settings }), + ), + ); + const first = yield* service.readSummary(WINDOW); + yield* Effect.promise(() => + NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }), + ); + + const reached = yield* service.readSummary(WINDOW); + assert.deepStrictEqual(reached.buckets, first.buckets); + assert.strictEqual(reached.sources[0]?.status, "ok"); + + // A missing source cannot claim this directory from another environment + // that still reads it, so it adds nothing to a window after its last write. + const later = yield* service.readSummary({ + timeZone: "UTC", + sinceDay: UsageDay.make("2026-08-10"), + untilDay: UsageDay.make("2026-08-12"), + }); + assert.deepStrictEqual(later.buckets, []); + assert.strictEqual(later.sources[0]?.status, "missing"); + assert.strictEqual(later.sources[0]?.scannedFiles, 0); + }).pipe(Effect.scoped), + ); + it.live("does not share an in-flight scan after custom prices change", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 3336ad1d0d63..dea865791a63 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -55,7 +55,7 @@ import { readOpenCodeUsage } from "./opencodeUsageReader.ts"; import { readAntigravityUsage } from "./antigravityUsageReader.ts"; import { makeCursorAccountHistory } from "./cursorAccountHistory.ts"; import { readOtherCursorLogins } from "./cursorLogins.ts"; -import { UsageAggregator } from "./usageAggregation.ts"; +import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; import { BoxUsageStore, makeBoxUsageReads, usageHostId } from "./boxUsage.ts"; import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts"; import { @@ -66,8 +66,11 @@ import { import { decodeScanCache, dedupeWithinFile, - encodeScanCache, + LEGACY_SCAN_CACHE_FILE_NAME, + makeScanCacheWriter, pruneScanCache, + SCAN_CACHE_FILE_NAME, + type CachedFile, type ScanCache, } from "./usageScanCache.ts"; import type { UsageRecord } from "./usageTranscripts.ts"; @@ -91,6 +94,9 @@ const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000; /** Longest window the UI offers, plus slack. Older entries are pruned. */ const CACHE_RETENTION_DAYS = 90; +/** Transcripts parsed at once. More gains little once the disk stays busy. */ +const TRANSCRIPT_READ_CONCURRENCY = 4; + const decodeCodexSettings = Schema.decodeOption(CodexSettings); const decodeClaudeSettings = Schema.decodeOption(ClaudeSettings); @@ -109,9 +115,37 @@ const encodeRatesCache = Schema.encodeEffect( /** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */ const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec); const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson); -const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson); const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson); const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String }); + +/** Whether `a` read a later state of its file than `b`. Transcripts only grow. */ +function isLaterRead(a: CachedFile, b: CachedFile): boolean { + return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size); +} + +/** + * Codex sessions with records in more than one file, such as a rollout that + * moved after it was read. Only these need cross-file dedupe keys: within one + * file the occurrence count already keeps every key unique, so keying the rest + * would only build and hash a string for each of their records. + */ +function sharedCodexSessions( + files: readonly { readonly records: readonly UsageRecord[] }[], +): ReadonlySet { + const firstFile = new Map(); + const shared = new Set(); + for (const [index, file] of files.entries()) { + let previous = ""; + for (const { provider, sessionId } of file.records) { + if (provider !== "codex" || sessionId === previous || sessionId.length === 0) continue; + previous = sessionId; + const first = firstFile.get(sessionId); + if (first === undefined) firstFile.set(sessionId, index); + else if (first !== index) shared.add(sessionId); + } + } + return shared; +} const decodeCachedSources = Schema.decodeUnknownOption( Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }), ); @@ -174,7 +208,8 @@ export const make = Effect.gen(function* () { }; const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json"); - const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json"); + const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME); + const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME); let rates: RateTable = new Map(); let ratesFetchedAtMs: number | null = null; let ratesStatus: UsagePricing["status"] = "unavailable"; @@ -368,10 +403,17 @@ export const make = Effect.gen(function* () { */ const ensureScanCacheLoaded = yield* Effect.cached( Effect.gen(function* () { - const document = yield* fileSystem.readFileString(scanCachePath).pipe( - Effect.flatMap((raw) => decodeScanCacheFile(raw)), - Effect.catchCause(() => Effect.succeed(null)), - ); + const readDocument = (filePath: string) => + fileSystem.readFileString(filePath).pipe( + Effect.flatMap((raw) => decodeScanCacheFile(raw)), + Effect.catchCause(() => Effect.succeed(null)), + ); + let document = yield* readDocument(scanCachePath); + if (document === null) { + document = yield* readDocument(legacyScanCachePath); + // Write the migrated cache to its own file on the next scan. + cacheDirty = document !== null; + } if (document === null) return; for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry); const sources = decodeCachedSources(document); @@ -382,20 +424,28 @@ export const make = Effect.gen(function* () { }), ); + const writeScanCache = makeScanCacheWriter(); + // Scans with different windows can finish together; two writes interleaved + // in one file would corrupt it. + const persistLock = yield* Semaphore.make(1); + const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () { if (!cacheDirty) return; - // Cleared only after the write lands, so a failed persist is retried on - // the next scan instead of leaving disk permanently stale. - yield* encodeScanCacheFile({ - ...encodeScanCache(fileCache), - sources: Object.fromEntries(sourceCache), - }).pipe( + // Cleared before encoding, so a scan that changes the cache while this + // write is in flight marks it dirty again. A failed write restores the + // flag, so the next scan retries instead of leaving disk stale. + cacheDirty = false; + yield* Effect.sync(() => + writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }), + ).pipe( Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)), - Effect.map(() => { - cacheDirty = false; - }), // A cache we cannot write is a slower next start, not a failed read. - Effect.ignoreCause, + Effect.catchCause(() => + Effect.sync(() => { + cacheDirty = true; + }), + ), + persistLock.withPermit, ); }); @@ -406,13 +456,22 @@ export const make = Effect.gen(function* () { * written multi-hundred-megabyte rollout costs its appended bytes per scan * rather than a full re-read. The reader verifies the position's guard bytes * and silently restarts from byte 0 when they no longer match. + * + * A fresh parse comes back as `update` for the caller to cache, with the + * entry it was built from. Reads run concurrently, and the caller stores + * updates in walk order rather than completion order: saved records of + * deleted transcripts aggregate in cache order, where the first copy of a + * duplicate wins. */ const readFileRecords = ( filePath: string, size: number, mtimeMs: number, provider: UsageProviderKind, - ): Effect.Effect => + ): Effect.Effect<{ + readonly records: readonly UsageRecord[]; + readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined }; + }> => Effect.gen(function* () { const cached = fileCache.get(filePath); // Provider is part of the identity: if both providers were ever pointed @@ -423,9 +482,12 @@ export const make = Effect.gen(function* () { cached.mtimeMs === mtimeMs && cached.provider === provider ) { - return cached.tailRecords.length === 0 - ? cached.records - : [...cached.records, ...cached.tailRecords]; + return { + records: + cached.tailRecords.length === 0 + ? cached.records + : [...cached.records, ...cached.tailRecords], + }; } // Only a strictly grown file may resume. Same size with a new mtime, or @@ -441,7 +503,9 @@ export const make = Effect.gen(function* () { // A read failure is not an empty transcript: caching it under this // (size, mtime) would silently drop the file's usage until it changes. if (parsed === null) - return cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : []; + return { + records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], + }; // Stored already de-duplicated within the file, which is 99% of all // duplicates. The aggregator still runs the cross-file dedupe pass. One @@ -452,16 +516,13 @@ export const make = Effect.gen(function* () { const records = dedupeWithinFile([...base, ...parsed.records], seen); const tailRecords = dedupeWithinFile(parsed.tailRecords, seen); - fileCache.set(filePath, { - size, - mtimeMs, - provider, - records, - tailRecords, - position: parsed.position, - }); - cacheDirty = true; - return tailRecords.length === 0 ? records : [...records, ...tailRecords]; + return { + records: tailRecords.length === 0 ? records : [...records, ...tailRecords], + update: { + entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position }, + replaces: cached, + }, + }; }); /** One provider directory's walk and parse, before rates are involved. */ @@ -501,11 +562,32 @@ export const make = Effect.gen(function* () { const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }), ); - const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = []; - for (const file of files) { - const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider); - parsedFiles.push({ path: file.path, records }); - } + // A cold parse waits on disk reads, so a few files in flight read + // close to twice as fast. Results keep walk order. + const read = yield* Effect.forEach( + files, + (file) => + readFileRecords(file.path, file.size, file.mtimeMs, provider).pipe( + Effect.map((result) => ({ path: file.path, ...result })), + ), + { concurrency: TRANSCRIPT_READ_CONCURRENCY }, + ); + const parsedFiles = read.map(({ path, records, update }) => { + if (update === undefined) return { path, records }; + // A scan of another window may have cached its own read of this file + // meanwhile. Then keep whichever read saw the later file, so a slower + // scan never replaces newer usage with older. + const current = fileCache.get(path); + if ( + current === update.replaces || + current === undefined || + !isLaterRead(current, update.entry) + ) { + fileCache.set(path, update.entry); + cacheDirty = true; + } + return { path, records }; + }); scanned.push({ provider, dir, volumeId, files: parsedFiles }); } @@ -756,41 +838,44 @@ export const make = Effect.gen(function* () { ...hourlyWindow, rates, priceOverrides: createOverrideRateTable(settings.usagePriceOverrides), + modelAliases: resolveModelAliases(settings.usageModelAliases), }); const sources: UsageSource[] = []; - for (const { - provider, - dir, - volumeId, - files, - status, - message, - action, - hostId: sourceHostId, - } of scannedDirs) { + // Cleanup may remove transcripts, but the usage we already saved still + // contributes to its source through the normal aggregation and dedupe + // path. Like the walk, skip files last written before the window: they + // cannot hold records inside it. + const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs); + const filesByDir = scannedDirs.map(({ provider, dir, files }) => { const retainedFiles = [...(files ?? [])]; const livePaths = new Set(retainedFiles.map((file) => file.path)); - // Cleanup may remove transcripts, but the usage we already saved still - // contributes to this source. Keep the normal aggregation and dedupe path. for (const [filePath, entry] of fileCache) { if ( entry.provider !== provider || - entry.mtimeMs < retentionCutoffMs || + entry.mtimeMs < retainedSinceMs || livePaths.has(filePath) || !isWithinDirectory(filePath, dir) ) continue; retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] }); } + return retainedFiles; + }); + const sharedSessions = sharedCodexSessions(filesByDir.flat()); + + for (const [ + index, + { provider, dir, volumeId, files, status, message, action, hostId: sourceHostId }, + ] of scannedDirs.entries()) { let scannedFiles = 0; let skippedFiles = 0; // Distinct per directory. Buckets carry per-cell session counts, but a // session spans days and models, so clients total this figure instead. const sessionIds = new Set(); - for (const file of retainedFiles) { + for (const file of filesByDir[index] ?? []) { if (file.records.length === 0) { skippedFiles += 1; continue; @@ -799,9 +884,10 @@ export const make = Effect.gen(function* () { const codexEventOccurrences = new Map(); for (const record of file.records) { let usageRecord = record; - if (record.provider === "codex" && record.sessionId.length > 0) { + if (record.provider === "codex" && sharedSessions.has(record.sessionId)) { // Match moved rollout copies without collapsing repeated equal events // within one rollout (timestamps can have only second precision). + // Only sessions seen in several files can have a copy to match. const key = encodeUsageRecordKey([ record.provider, record.sessionId, @@ -857,17 +943,13 @@ export const make = Effect.gen(function* () { }); /** - * In-flight scans by window and custom prices, so concurrent identical requests (the usage + * In-flight scans by window and usage settings, so concurrent identical requests (the usage * page open on two clients at once) share one scan instead of racing over * the same corpus twice. */ const inflightScans = new Map>(); - const scanKey = ( - input: UsageSummaryInput, - priceOverrides: ServerSettingsValue["usagePriceOverrides"], - cursorKeychainUsageEnabled: boolean, - ): string => + const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string => JSON.stringify([ input.timeZone, input.sinceDay, @@ -875,8 +957,9 @@ export const make = Effect.gen(function* () { input.resolution ?? "day", input.sinceTime ?? null, input.untilTime ?? null, - priceOverrides, - cursorKeychainUsageEnabled, + settings.usagePriceOverrides, + settings.usageModelAliases, + settings.cursorKeychainUsageEnabled, ]); const readSummary = Effect.fn("UsageService.readSummary")(function* ( @@ -884,7 +967,7 @@ export const make = Effect.gen(function* () { maxHourlyWindowMs = MAX_HOURLY_WINDOW_MS, ) { const settings = yield* readSettings; - const key = `${maxHourlyWindowMs}:${scanKey(input, settings.usagePriceOverrides, settings.cursorKeychainUsageEnabled)}`; + const key = `${maxHourlyWindowMs}:${scanKey(input, settings)}`; const deferred = yield* Effect.uninterruptible( Effect.gen(function* () { const existing = inflightScans.get(key); diff --git a/apps/server/src/usage/antigravityUsageReader.ts b/apps/server/src/usage/antigravityUsageReader.ts index 54c00b804b7a..34a88114f42e 100644 --- a/apps/server/src/usage/antigravityUsageReader.ts +++ b/apps/server/src/usage/antigravityUsageReader.ts @@ -240,7 +240,7 @@ async function readDatabase(path: string, fallbackTimestamp: number): Promise { ); }); + it("keeps a box's cost split by token type and speed", () => { + const folded = foldBoxUsage( + hostSummary, + { timeZone: "UTC", sinceDay: hostSummary.sinceDay, untilDay: hostSummary.untilDay }, + [ + row("lease-live", false, [ + hourBucket("2026-09-01T03:00:00.000Z", 10, { + categoryCostUsd: { input: 4, cacheRead: 1, cacheWrite: 0, output: 5 }, + fastCostUsd: 10, + speedPremiumUsd: 5, + }), + hourBucket("2026-09-01T04:00:00.000Z", 20, { + categoryCostUsd: { input: 8, cacheRead: 2, cacheWrite: 0, output: 10 }, + }), + ]), + ], + { hostId: "host", path: "/state/cloud-box-usage" }, + ); + + assert.deepStrictEqual( + folded.buckets.map((bucket) => [ + bucket.categoryCostUsd, + bucket.fastCostUsd, + bucket.ultrafastCostUsd, + bucket.speedPremiumUsd, + ]), + [[{ input: 12, cacheRead: 3, cacheWrite: 0, output: 15 }, 10, undefined, 5]], + ); + }); + it("keeps hour buckets in an hourly window", () => { const folded = foldBoxUsage( hostSummary, diff --git a/apps/server/src/usage/boxUsage.ts b/apps/server/src/usage/boxUsage.ts index f183d606cf06..f5d58d71f3a2 100644 --- a/apps/server/src/usage/boxUsage.ts +++ b/apps/server/src/usage/boxUsage.ts @@ -39,7 +39,6 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as ServerConfig from "../config.ts"; import { makeDayFormatter } from "./usageAggregation.ts"; -import { addTotals } from "./usageTranscripts.ts"; const HOUR_MS = 60 * 60 * 1000; const DAY_MS = 24 * HOUR_MS; @@ -360,11 +359,35 @@ export function boxUsageListWindow(input: UsageSummaryInput): { } function sumBuckets(a: UsageBucket, b: UsageBucket): UsageBucket { + const ca = a.categoryCostUsd; + const cb = b.categoryCostUsd; + const fastCostUsd = (a.fastCostUsd ?? 0) + (b.fastCostUsd ?? 0); + const ultrafastCostUsd = (a.ultrafastCostUsd ?? 0) + (b.ultrafastCostUsd ?? 0); + const speedPremiumUsd = (a.speedPremiumUsd ?? 0) + (b.speedPremiumUsd ?? 0); return { ...a, - totals: addTotals(a.totals, b.totals), + totals: { + uncachedInputTokens: a.totals.uncachedInputTokens + b.totals.uncachedInputTokens, + cachedInputTokens: a.totals.cachedInputTokens + b.totals.cachedInputTokens, + cacheCreationTokens: a.totals.cacheCreationTokens + b.totals.cacheCreationTokens, + outputTokens: a.totals.outputTokens + b.totals.outputTokens, + reasoningTokens: a.totals.reasoningTokens + b.totals.reasoningTokens, + }, costUsd: a.costUsd + b.costUsd, cacheSavingsUsd: a.cacheSavingsUsd + b.cacheSavingsUsd, + ...(ca === undefined && cb === undefined + ? {} + : { + categoryCostUsd: { + input: (ca?.input ?? 0) + (cb?.input ?? 0), + cacheRead: (ca?.cacheRead ?? 0) + (cb?.cacheRead ?? 0), + cacheWrite: (ca?.cacheWrite ?? 0) + (cb?.cacheWrite ?? 0), + output: (ca?.output ?? 0) + (cb?.output ?? 0), + }, + }), + ...(fastCostUsd === 0 ? {} : { fastCostUsd }), + ...(ultrafastCostUsd === 0 ? {} : { ultrafastCostUsd }), + ...(speedPremiumUsd === 0 ? {} : { speedPremiumUsd }), // Mixed provenance reads as model-priced, as a scanned bucket would. costSource: a.costSource === b.costSource ? a.costSource : "modelPriced", records: a.records + b.records, @@ -414,19 +437,12 @@ export function foldBoxUsage( const day = toDay(hourMs) as UsageBucket["day"]; if (!hourly && (day < input.sinceDay || day > input.untilDay)) continue; const sourcePath = row.retired ? retiredHome.path : `${row.leaseId}:${bucket.sourcePath}`; + const { hourStart, ...measures } = bucket; const cell: UsageBucket = { + ...measures, day, - ...(hourly ? { hourStart: bucket.hourStart } : {}), - provider: bucket.provider, - model: bucket.model, + ...(hourly ? { hourStart } : {}), sourcePath, - totals: bucket.totals, - costUsd: bucket.costUsd, - cacheSavingsUsd: bucket.cacheSavingsUsd, - costSource: bucket.costSource, - records: bucket.records, - unpricedRecords: bucket.unpricedRecords, - sessions: bucket.sessions, }; const cellKey = [day, cell.hourStart ?? "", cell.provider, cell.model, sourcePath].join( "\u0000", diff --git a/apps/server/src/usage/cursorAccountHistory.test.ts b/apps/server/src/usage/cursorAccountHistory.test.ts index d5a493b088a2..1dce9150c836 100644 --- a/apps/server/src/usage/cursorAccountHistory.test.ts +++ b/apps/server/src/usage/cursorAccountHistory.test.ts @@ -20,7 +20,7 @@ const record = (timestampMs: number): UsageRecord => ({ reasoningTokens: 0, }, reportedCostUsd: 0.01, - fast: false, + speed: "standard", dedupeKey: `cursor-account:a:${timestampMs}`, }); diff --git a/apps/server/src/usage/cursorUsageReader.ts b/apps/server/src/usage/cursorUsageReader.ts index 31fae24c3cf5..0931718cea64 100644 --- a/apps/server/src/usage/cursorUsageReader.ts +++ b/apps/server/src/usage/cursorUsageReader.ts @@ -253,7 +253,7 @@ export async function readCursorAccountUsage( sessionId, totals, reportedCostUsd, - fast: false, + speed: "standard", dedupeKey: `cursor-account:${accountKey}:${key}:${occurrence}`, }); } diff --git a/apps/server/src/usage/opencodeUsageReader.ts b/apps/server/src/usage/opencodeUsageReader.ts index 45d6ef33a584..d4414ac7b9a6 100644 --- a/apps/server/src/usage/opencodeUsageReader.ts +++ b/apps/server/src/usage/opencodeUsageReader.ts @@ -64,7 +64,7 @@ function parseOpenCodeMessage( // OpenCode writes zero for models without a known rate, including paid // subscription models. Let the shared price table estimate those records. reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null, - fast: false, + speed: "standard", dedupeKey: id ? `opencode:${id}` : null, }; } diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index 75435de08ff7..a27a9b101cc3 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; -import { UsageAggregator } from "./usageAggregation.ts"; +import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; import type { RateTable } from "./usagePricing.ts"; import type { UsageRecord } from "./usageTranscripts.ts"; @@ -12,7 +12,13 @@ const rates: RateTable = new Map([ outputCostPerToken: 5e-5, cacheReadCostPerToken: 1e-6, cacheCreationCostPerToken: 1.25e-5, - fastMultiplier: 1, + fast: { + inputCostPerToken: 2e-5, + outputCostPerToken: 1e-4, + cacheReadCostPerToken: 2e-6, + cacheCreationCostPerToken: 2.5e-5, + }, + ultrafast: null, }, ], ]); @@ -32,7 +38,7 @@ function record(overrides: Partial = {}): UsageRecord { reasoningTokens: 0, }, reportedCostUsd: null, - fast: false, + speed: "standard", dedupeKey: null, ...overrides, }; @@ -76,6 +82,24 @@ describe("UsageAggregator", () => { ).toThrow("requires exact time bounds"); }); + it("splits a bucket's cost by category and speed", () => { + const [bucket] = aggregate([record(), record({ speed: "fast" })]).buckets; + + // Standard costs $0.005625 and fast twice that. + expect(bucket).toMatchObject({ + costUsd: expect.closeTo(0.016875), + categoryCostUsd: { + input: expect.closeTo(0.003), + cacheRead: expect.closeTo(0.003), + cacheWrite: expect.closeTo(0.000375), + output: expect.closeTo(0.0075), + }, + fastCostUsd: expect.closeTo(0.01125), + speedPremiumUsd: expect.closeTo(0.005625), + }); + expect(bucket).not.toHaveProperty("ultrafastCostUsd"); + }); + it("keeps only the first record for a repeated dedupe key", () => { const result = aggregate([ record({ dedupeKey: "msg_1:" }), @@ -104,6 +128,41 @@ describe("UsageAggregator", () => { expect(losAngeles.buckets[0]?.day).toBe("2026-08-06"); }); + it("finds the day at a quarter-hour zone's midnight across interleaved buckets", () => { + // Kathmandu is UTC+5:45, so its midnight falls at 18:15 UTC. + const result = aggregate( + [ + record({ timestampMs: Date.parse("2026-08-01T18:14:59.999Z") }), + record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z") }), + record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z"), model: "claude-opus-5" }), + record({ timestampMs: Date.parse("2026-08-01T18:16:00.000Z") }), + ], + "Asia/Kathmandu", + ); + + expect(result.buckets.map((bucket) => [bucket.day, bucket.model, bucket.records])).toEqual([ + ["2026-08-01", "claude-fable-5", 1], + ["2026-08-02", "claude-fable-5", 2], + ["2026-08-02", "claude-opus-5", 1], + ]); + }); + + it("finds the day at a fixed offset's midnight between quarter hours", () => { + // At +00:01, midnight falls at 23:59 UTC. + const result = aggregate( + [ + record({ timestampMs: Date.parse("2026-08-01T23:58:59.999Z") }), + record({ timestampMs: Date.parse("2026-08-01T23:59:00.000Z") }), + ], + "+00:01", + ); + + expect(result.buckets.map((bucket) => [bucket.day, bucket.records])).toEqual([ + ["2026-08-01", 1], + ["2026-08-02", 1], + ]); + }); + it("splits an hourly request into fixed buckets anchored to its exact start", () => { const result = aggregate( [ @@ -194,6 +253,25 @@ describe("UsageAggregator", () => { expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false); }); + it("folds a mapped model into its target and prices it there", () => { + const aggregator = new UsageAggregator({ + timeZone: "UTC", + sinceDay: "2026-08-01", + untilDay: "2026-08-31", + rates, + modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }), + }); + aggregator.add(record()); + aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" })); + const result = aggregator.finish(); + + expect(result.buckets).toHaveLength(1); + expect(result.buckets[0]?.model).toBe("claude-fable-5"); + expect(result.buckets[0]?.records).toBe(2); + expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9); + expect(result.buckets[0]?.unpricedRecords).toBe(0); + }); + it("separates providers and models into their own buckets", () => { const result = aggregate([ record(), @@ -204,3 +282,23 @@ describe("UsageAggregator", () => { expect(result.buckets).toHaveLength(3); }); }); + +describe("resolveModelAliases", () => { + it("follows chains to the final model and drops chains that enter a loop", () => { + expect( + resolveModelAliases({ + "preview[1m]": "preview", + preview: "example-model", + loop: "back", + back: "loop", + intoLoop: "loop", + self: "self", + }), + ).toEqual( + new Map([ + ["preview[1m]", "example-model"], + ["preview", "example-model"], + ]), + ); + }); +}); diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index b4715f1044e4..c1731273ce70 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -12,9 +12,15 @@ * * @module usageAggregation */ -import type { UsageBucket, UsageDay, UsageResolution, UsageTokenTotals } from "@t3tools/contracts"; +import type { + UsageBucket, + UsageCategoryCost, + UsageDay, + UsageResolution, + UsageTokenTotals, +} from "@t3tools/contracts"; -import { addTotals, EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts"; +import { EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts"; import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts"; /** @@ -41,15 +47,36 @@ export function makeDayFormatter(timeZone: string): (timestampMs: number) => str day: "2-digit", }); } - return (timestampMs) => format.format(new Date(timestampMs)); + // Formatting once per quarter-hour slot keeps `Intl` (about 2µs a call) off + // the per-record path. A slot whose two ends fall on one day lies wholly in + // that day. Named zones put midnight on a quarter hour, so their slots never + // split; a fixed offset such as `+00:01` can, and records in a split slot are + // formatted exactly. `null` marks a split slot. + const days = new Map(); + return (timestampMs) => { + const slot = Math.floor(timestampMs / QUARTER_HOUR_MS); + let day = days.get(slot); + if (day === undefined) { + const first = format.format(new Date(slot * QUARTER_HOUR_MS)); + const last = format.format(new Date((slot + 1) * QUARTER_HOUR_MS - 1)); + day = first === last ? first : null; + days.set(slot, day); + } + return day ?? format.format(new Date(timestampMs)); + }; } +const QUARTER_HOUR_MS = 15 * 60 * 1000; const HOUR_MS = 60 * 60 * 1000; interface MutableBucket { - totals: UsageTokenTotals; + totals: { -readonly [K in keyof UsageTokenTotals]: number }; costUsd: number; cacheSavingsUsd: number; + categoryCostUsd: UsageCategoryCost | null; + fastCostUsd: number; + ultrafastCostUsd: number; + speedPremiumUsd: number; records: number; unpricedRecords: number; providerReportedRecords: number; @@ -62,11 +89,35 @@ export interface AggregateOptions { readonly untilDay: string; readonly rates: RateTable; readonly priceOverrides?: RateTable; + /** From {@link resolveModelAliases}. Mapped records bucket and price as their target. */ + readonly modelAliases?: ReadonlyMap; readonly resolution?: UsageResolution; readonly sinceTimeMs?: number; readonly untilTimeMs?: number; } +/** + * Resolves user model mappings to their final target, so `a -> b` and + * `b -> c` both land on `c`. A model whose chain enters a loop is left + * unmapped. + */ +export function resolveModelAliases( + aliases: Readonly>, +): ReadonlyMap { + const resolved = new Map(); + for (const model of Object.keys(aliases)) { + const seen = new Set([model]); + let target = aliases[model]!; + while (Object.hasOwn(aliases, target) && !seen.has(target)) { + seen.add(target); + target = aliases[target]!; + } + // Stopping on a mapped model means the chain entered a loop. + if (!Object.hasOwn(aliases, target)) resolved.set(model, target); + } + return resolved; +} + export interface AggregateResult { readonly buckets: readonly UsageBucket[]; /** Records dropped because an earlier record carried the same dedupe key. */ @@ -88,6 +139,14 @@ export class UsageAggregator { readonly #toDay: (timestampMs: number) => string; readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null; readonly #options: AggregateOptions; + #lastBucket: { + readonly day: string; + readonly hourIndex: number; + readonly provider: string; + readonly model: string; + readonly source: string; + readonly bucket: MutableBucket; + } | null = null; #duplicatesDropped = 0; #outOfWindow = 0; @@ -112,7 +171,8 @@ export class UsageAggregator { * can derive per-window facts (distinct sessions, for one) from the records * that landed rather than everything the mtime prefilter happened to admit. */ - add(record: UsageRecord, sourcePath?: string): boolean { + add(input: UsageRecord, sourcePath?: string): boolean { + const record = this.#mapModel(input); if (record.dedupeKey !== null) { if (this.#seen.has(record.dedupeKey)) { this.#duplicatesDropped += 1; @@ -139,32 +199,37 @@ export class UsageAggregator { return false; } - const hourStart = + const hourIndex = this.#hourlyWindow === null - ? "" - : new Date( - this.#hourlyWindow.sinceTimeMs + - Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS, - ).toISOString(); - const key = `${day}\u0000${hourStart}\u0000${record.provider}\u0000${record.model}\u0000${sourcePath ?? ""}`; - let bucket = this.#buckets.get(key); - if (bucket === undefined) { - bucket = { - totals: EMPTY_TOTALS, - costUsd: 0, - cacheSavingsUsd: 0, - records: 0, - unpricedRecords: 0, - providerReportedRecords: 0, - sessions: new Set(), - }; - this.#buckets.set(key, bucket); - } + ? -1 + : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS); + const bucket = this.#bucketFor(day, hourIndex, record.provider, record.model, sourcePath ?? ""); const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides); - bucket.totals = addTotals(bucket.totals, record.totals); + const totals = bucket.totals; + totals.uncachedInputTokens += record.totals.uncachedInputTokens; + totals.cachedInputTokens += record.totals.cachedInputTokens; + totals.cacheCreationTokens += record.totals.cacheCreationTokens; + totals.outputTokens += record.totals.outputTokens; + totals.reasoningTokens += record.totals.reasoningTokens; bucket.costUsd += priced.costUsd; + if (priced.categoryCostUsd !== null) { + const sum = bucket.categoryCostUsd; + const add = priced.categoryCostUsd; + bucket.categoryCostUsd = + sum === null + ? add + : { + input: sum.input + add.input, + cacheRead: sum.cacheRead + add.cacheRead, + cacheWrite: sum.cacheWrite + add.cacheWrite, + output: sum.output + add.output, + }; + } + if (record.speed === "fast") bucket.fastCostUsd += priced.costUsd; + if (record.speed === "ultrafast") bucket.ultrafastCostUsd += priced.costUsd; + bucket.speedPremiumUsd += priced.speedPremiumUsd; bucket.cacheSavingsUsd += cacheSavingsUsd( this.#options.rates, record, @@ -177,20 +242,94 @@ export class UsageAggregator { return true; } + /** The target's own rate applies, so a provider-specific `rateModel` is dropped. */ + #mapModel(record: UsageRecord): UsageRecord { + const model = this.#options.modelAliases?.get(record.model); + if (model === undefined) return record; + const { rateModel: _rateModel, ...rest } = record; + return { ...rest, model }; + } + + /** + * Records arrive file by file in time order, so most land in the bucket the + * previous record used. Checking that first skips building and hashing a + * key string per record. + */ + #bucketFor( + day: string, + hourIndex: number, + provider: string, + model: string, + source: string, + ): MutableBucket { + const last = this.#lastBucket; + if ( + last !== null && + last.day === day && + last.hourIndex === hourIndex && + last.provider === provider && + last.model === model && + last.source === source + ) { + return last.bucket; + } + const window = this.#hourlyWindow; + const hourStart = + window === null ? "" : new Date(window.sinceTimeMs + hourIndex * HOUR_MS).toISOString(); + const key = `${day}\u0000${hourStart}\u0000${provider}\u0000${model}\u0000${source}`; + let bucket = this.#buckets.get(key); + if (bucket === undefined) { + bucket = { + totals: { ...EMPTY_TOTALS }, + costUsd: 0, + cacheSavingsUsd: 0, + categoryCostUsd: null, + fastCostUsd: 0, + ultrafastCostUsd: 0, + speedPremiumUsd: 0, + records: 0, + unpricedRecords: 0, + providerReportedRecords: 0, + sessions: new Set(), + }; + this.#buckets.set(key, bucket); + } + this.#lastBucket = { day, hourIndex, provider, model, source, bucket }; + return bucket; + } + finish(): AggregateResult { const buckets: UsageBucket[] = []; for (const [key, bucket] of this.#buckets) { const [day = "", hourStart = "", provider = "", model = "", sourcePath = ""] = key.split("\u0000"); + const category = bucket.categoryCostUsd; + const fastCostUsd = roundUsd(bucket.fastCostUsd); + const ultrafastCostUsd = roundUsd(bucket.ultrafastCostUsd); + const speedPremiumUsd = roundUsd(bucket.speedPremiumUsd); buckets.push({ day: day as UsageDay, ...(hourStart === "" ? {} : { hourStart }), provider: provider as UsageBucket["provider"], model, ...(sourcePath === "" ? {} : { sourcePath }), - totals: bucket.totals, + totals: { ...bucket.totals }, costUsd: bucket.costUsd, cacheSavingsUsd: bucket.cacheSavingsUsd, + // Zero and unknown figures are omitted to keep payloads small. + ...(category === null + ? {} + : { + categoryCostUsd: { + input: roundUsd(category.input), + cacheRead: roundUsd(category.cacheRead), + cacheWrite: roundUsd(category.cacheWrite), + output: roundUsd(category.output), + }, + }), + ...(fastCostUsd === 0 ? {} : { fastCostUsd }), + ...(ultrafastCostUsd === 0 ? {} : { ultrafastCostUsd }), + ...(speedPremiumUsd === 0 ? {} : { speedPremiumUsd }), costSource: resolveCostSource(bucket), records: bucket.records, unpricedRecords: bucket.unpricedRecords, @@ -214,6 +353,14 @@ export class UsageAggregator { } } +/** + * Rounds to micro-dollars. The split and speed figures need no more precision, + * and shorter numbers keep them cheap on the wire. + */ +function roundUsd(value: number): number { + return Math.round(value * 1e6) / 1e6; +} + /** * A bucket mixes records from one model, but their cost provenance can differ * when only some records carried a reported cost. The weakest provenance in the diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index db4f68c2cb42..0a324dd734b4 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "@effect/vitest"; import { cursorRateModel } from "./cursorUsageReader.ts"; +import type { UsageSpeed } from "./usageTranscripts.ts"; import { cacheSavingsUsd, createOverrideRateTable, @@ -23,11 +24,15 @@ describe("usage pricing", () => { outputTokens: 1_000_000, reasoningTokens: 500_000, }; - const record = (model: string, reportedCostUsd: number | null = null, fast = false) => ({ + const record = ( + model: string, + reportedCostUsd: number | null = null, + speed: UsageSpeed = "standard", + ) => ({ model, totals, reportedCostUsd, - fast, + speed, }); it("uses custom token rates ahead of public and provider-reported costs", () => { @@ -42,7 +47,7 @@ describe("usage pricing", () => { }); for (const reportedCostUsd of [null, 99]) { - expect(priceUsage(table, record("example-model", reportedCostUsd), overrides)).toEqual({ + expect(priceUsage(table, record("example-model", reportedCostUsd), overrides)).toMatchObject({ costUsd: 13.5, costSource: "modelPriced", }); @@ -64,7 +69,7 @@ describe("usage pricing", () => { expect(cacheSavingsUsd(table, cursorRecord("claude-fable-5-1-thinking-high"))).toBeCloseTo(9); expect(cacheSavingsUsd(table, cursorRecord("cursor-grok-4.7-high-fast"))).toBeCloseTo(1.5); expect(cacheSavingsUsd(table, cursorRecord("default"))).toBe(0); - expect(priceUsage(table, cursorRecord("grok-4.7-xhigh-fast"))).toEqual({ + expect(priceUsage(table, cursorRecord("grok-4.7-xhigh-fast"))).toMatchObject({ costUsd: 0.25, costSource: "providerReported", }); @@ -76,7 +81,7 @@ describe("usage pricing", () => { "example-model": { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 }, }); - expect(priceUsage(table, record("example-model"), overrides)).toEqual({ + expect(priceUsage(table, record("example-model"), overrides)).toMatchObject({ costUsd: 14, costSource: "modelPriced", }); @@ -91,7 +96,7 @@ describe("usage pricing", () => { outputCostPerMillionTokens: 0, }, }); - expect(priceUsage(table, record(" vendor/example-model[1m] ", 99), overrides)).toEqual({ + expect(priceUsage(table, record(" vendor/example-model[1m] ", 99), overrides)).toMatchObject({ costUsd: 0, costSource: "modelPriced", }); @@ -105,6 +110,8 @@ describe("usage pricing", () => { expect(priceUsage(table, record(model, 99), overrides)).toEqual({ costUsd: 99, costSource: "providerReported", + categoryCostUsd: null, + speedPremiumUsd: 0, }); } }); @@ -117,20 +124,82 @@ describe("usage pricing", () => { const overrides = createOverrideRateTable({ "claude-opus-5-5": { inputCostPerMillionTokens: 4, outputCostPerMillionTokens: 20 }, }); - const cost = (model: string, fast: boolean, custom?: typeof overrides) => - priceUsage(table, record(model, null, fast), custom).costUsd; + const cost = (model: string, speed: UsageSpeed, custom?: typeof overrides) => + priceUsage(table, record(model, null, speed), custom).costUsd; - expect(cost("claude-opus-5-5", true)).toBeCloseTo(2 * cost("claude-opus-5-5", false)); - expect(cacheSavingsUsd(table, record("claude-opus-5-5", null, true))).toBeCloseTo( + expect(cost("claude-opus-5-5", "fast")).toBeCloseTo(2 * cost("claude-opus-5-5", "standard")); + expect(cacheSavingsUsd(table, record("claude-opus-5-5", null, "fast"))).toBeCloseTo( 2 * cacheSavingsUsd(table, record("claude-opus-5-5")), ); // No published fast tier, and custom prices, both stay at the standard rate. - expect(cost("claude-fable-5-1", true)).toBe(cost("claude-fable-5-1", false)); - expect(cost("claude-opus-5-5", true, overrides)).toBe( - cost("claude-opus-5-5", false, overrides), + expect(cost("claude-fable-5-1", "fast")).toBe(cost("claude-fable-5-1", "standard")); + expect(cost("claude-opus-5-5", "fast", overrides)).toBe( + cost("claude-opus-5-5", "standard", overrides), ); }); + it("splits cost by category and prices the speed premium", () => { + const table = parseRateTable({ + "claude-opus-5-5": { + ...rate(4e-6, 4e-7), + cache_creation_input_token_cost: 5e-6, + provider_specific_entry: { fast: 2 }, + }, + }); + const split = (input: number, cacheRead: number, cacheWrite: number, output: number) => ({ + input: expect.closeTo(input), + cacheRead: expect.closeTo(cacheRead), + cacheWrite: expect.closeTo(cacheWrite), + output: expect.closeTo(output), + }); + + expect(priceUsage(table, record("claude-opus-5-5", null, "fast"))).toEqual({ + costUsd: expect.closeTo(58.8), + costSource: "modelPriced", + categoryCostUsd: split(8, 0.8, 10, 40), + speedPremiumUsd: expect.closeTo(29.4), + }); + // A reported cost keeps its total and splits in proportion to list rates. + expect(priceUsage(table, record("claude-opus-5-5", 29.4, "fast"))).toEqual({ + costUsd: 29.4, + costSource: "providerReported", + categoryCostUsd: split(4, 0.4, 5, 20), + speedPremiumUsd: expect.closeTo(14.7), + }); + // Without rates there is nothing to split it by. + expect(priceUsage(table, record("unknown-model", 29.4, "fast"))).toMatchObject({ + costUsd: 29.4, + categoryCostUsd: null, + speedPremiumUsd: 0, + }); + }); + + it("prices Codex priority and ultrafast requests at their published tier rates", () => { + const table = parseRateTable({ + "gpt-6-astra": { + ...rate(1e-5, 1e-6), + input_cost_per_token_priority: 2e-5, + output_cost_per_token_priority: 1e-4, + cache_read_input_token_cost_priority: 2e-6, + input_cost_per_token_ultrafast: 6e-5, + output_cost_per_token_ultrafast: 3e-4, + // No ultrafast cache rate: keeps the standard 10:1 input-to-cache ratio. + }, + "gpt-6-sol": rate(2e-6, 2e-7), + }); + const cost = (model: string, speed: UsageSpeed) => + priceUsage(table, record(model, null, speed)).costUsd; + const standard = cost("gpt-6-astra", "standard"); + + expect(cost("gpt-6-astra", "fast")).toBeCloseTo(2 * standard); + expect(cost("gpt-6-astra", "ultrafast")).toBeCloseTo(6 * standard); + expect(cacheSavingsUsd(table, record("gpt-6-astra", null, "ultrafast"))).toBeCloseTo( + 6 * cacheSavingsUsd(table, record("gpt-6-astra")), + ); + // A tier the model does not publish bills at the standard rate. + expect(cost("gpt-6-sol", "ultrafast")).toBe(cost("gpt-6-sol", "standard")); + }); + it("keeps the canonical Fable rate separate from DeepInfra in either order", () => { const canonical = ["claude-fable-5", rate(1e-5, 1e-6)] as const; const deepInfra = ["deepinfra/anthropic/claude-fable-5", rate(1e-5)] as const; diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 78f6cf2c5cd9..0ec7ef8d622f 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -7,35 +7,46 @@ * * @module usagePricing */ -import type { UsageCostSource, UsageModelPriceOverride } from "@t3tools/contracts"; +import type { + UsageCategoryCost, + UsageCostSource, + UsageModelPriceOverride, + UsageTokenTotals, +} from "@t3tools/contracts"; -import type { UsageRecord } from "./usageTranscripts.ts"; +import type { UsageRecord, UsageSpeed } from "./usageTranscripts.ts"; -/** - * The subset of a LiteLLM entry we price against. All values are USD per token. - * - * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`, - * `*_priority`, `*_batches`). We deliberately price at the base tier: the - * transcripts don't record which tier served a request, so anything else would - * be a guess dressed up as precision. - */ -export interface ModelRate { +/** Token rates for one billing speed. All values are USD per token. */ +export interface TokenRates { readonly inputCostPerToken: number; readonly outputCostPerToken: number; readonly cacheReadCostPerToken: number; readonly cacheCreationCostPerToken: number; +} + +/** + * The subset of a LiteLLM entry we price against: standard rates, plus rates + * for each faster speed the model publishes. A request at a speed with no + * published rates bills at the standard rates. + * + * LiteLLM also publishes `*_above_272k_tokens`, `*_flex`, and `*_batches` + * variants. Transcripts don't record those, so we don't price them. + */ +export interface ModelRate extends TokenRates { /** - * Multiple of the rates above billed for a fast-mode request, from LiteLLM's - * `provider_specific_entry.fast`. `1` when the model publishes no fast tier. + * From LiteLLM's `provider_specific_entry.fast` multiple (Claude fast mode), + * or else its `*_priority` rates (Codex `priority`). */ - readonly fastMultiplier: number; + readonly fast: TokenRates | null; + /** From LiteLLM's `*_ultrafast` rates (Codex `ultrafast`). */ + readonly ultrafast: TokenRates | null; } export type RateTable = ReadonlyMap; /** * Custom IDs keep their case, provider prefix, and variant suffix. Custom rates - * apply as entered, fast-mode requests included. + * apply as entered, at every speed. */ export function createOverrideRateTable( overrides: Readonly>, @@ -50,31 +61,68 @@ export function createOverrideRateTable( (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, cacheCreationCostPerToken: (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - fastMultiplier: 1, + fast: null, + ultrafast: null, }, ]), ); } -/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */ -interface LiteLlmEntry { - readonly input_cost_per_token?: unknown; - readonly output_cost_per_token?: unknown; - readonly cache_read_input_token_cost?: unknown; - readonly cache_creation_input_token_cost?: unknown; - readonly provider_specific_entry?: unknown; -} +/** One raw LiteLLM entry. Field names carry a tier suffix, e.g. `_priority`. */ +type LiteLlmEntry = Readonly>; function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } +/** + * Reads one rate set, `suffix` selecting a tier such as `_priority`. Returns + * `null` without both an input and an output rate. + * + * Anthropic bills cache reads at a discount and cache writes at a premium. + * When the standard tier omits them, cached input is priced as plain input + * rather than as free. A faster tier that omits them keeps the standard tier's + * cache-to-input ratio. + */ +function readTokenRates( + entry: LiteLlmEntry, + suffix: string, + standard?: TokenRates, +): TokenRates | null { + const input = finiteNumber(entry[`input_cost_per_token${suffix}`]); + const output = finiteNumber(entry[`output_cost_per_token${suffix}`]); + if (input === null || output === null) return null; + const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") => + finiteNumber(entry[`${name}${suffix}`]) ?? + (standard !== undefined && standard.inputCostPerToken > 0 + ? (standard[field] / standard.inputCostPerToken) * input + : input); + return { + inputCostPerToken: input, + outputCostPerToken: output, + cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"), + cacheCreationCostPerToken: cacheRate( + "cache_creation_input_token_cost", + "cacheCreationCostPerToken", + ), + }; +} + +function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates { + return { + inputCostPerToken: rates.inputCostPerToken * multiple, + outputCostPerToken: rates.outputCostPerToken * multiple, + cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple, + cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple, + }; +} + /** Reads `provider_specific_entry.fast`, e.g. `2` for Claude Opus 5.5. */ -function fastMultiplier(entry: LiteLlmEntry): number { - const specific = entry.provider_specific_entry; - if (typeof specific !== "object" || specific === null) return 1; +function fastMultiplier(entry: LiteLlmEntry): number | null { + const specific = entry["provider_specific_entry"]; + if (typeof specific !== "object" || specific === null) return null; const fast = finiteNumber((specific as Record)["fast"]); - return fast !== null && fast > 0 ? fast : 1; + return fast !== null && fast > 0 ? fast : null; } /** @@ -94,21 +142,19 @@ export function parseRateTable(document: unknown): RateTable { for (const [name, raw] of Object.entries(document as Record)) { if (typeof raw !== "object" || raw === null) continue; const entry = raw as LiteLlmEntry; - const input = finiteNumber(entry.input_cost_per_token); - const output = finiteNumber(entry.output_cost_per_token); - if (input === null || output === null) continue; + const standard = readTokenRates(entry, ""); + if (standard === null) continue; const key = normalizeRateKey(name); if (key.length === 0) continue; + const multiple = fastMultiplier(entry); table.set(key, { - inputCostPerToken: input, - outputCostPerToken: output, - // Anthropic bills cache reads at a discount and cache writes at a - // premium. When a model omits them, cached input is priced as plain - // input rather than as free. - cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input, - cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input, - fastMultiplier: fastMultiplier(entry), + ...standard, + fast: + multiple === null + ? readTokenRates(entry, "_priority", standard) + : scaleTokenRates(standard, multiple), + ultrafast: readTokenRates(entry, "_ultrafast", standard), }); } @@ -131,16 +177,29 @@ export function parseRateTable(document: unknown): RateTable { return table; } -function sameRate(a: ModelRate, b: ModelRate): boolean { +function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean { + if (a === null || b === null) return a === b; return ( a.inputCostPerToken === b.inputCostPerToken && a.outputCostPerToken === b.outputCostPerToken && a.cacheReadCostPerToken === b.cacheReadCostPerToken && - a.cacheCreationCostPerToken === b.cacheCreationCostPerToken && - a.fastMultiplier === b.fastMultiplier + a.cacheCreationCostPerToken === b.cacheCreationCostPerToken + ); +} + +function sameRate(a: ModelRate, b: ModelRate): boolean { + return ( + sameTokenRates(a, b) && + sameTokenRates(a.fast, b.fast) && + sameTokenRates(a.ultrafast, b.ultrafast) ); } +/** The rates a request at `speed` bills at. */ +function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates { + return (speed === "standard" ? null : rate[speed]) ?? rate; +} + function normalizeRateKey(model: string): string { return model.trim().toLowerCase(); } @@ -176,7 +235,27 @@ const UNPRICEABLE_MODELS = new Set([ "fable", ]); +/** + * Lookups per table, by raw model name. A scan prices every record twice + * against a few dozen models, and tables are never mutated once built. + */ +const resolvedRates = new WeakMap>(); + export function lookupRate(table: RateTable, model: string): ModelRate | null { + let resolved = resolvedRates.get(table); + if (resolved === undefined) { + resolved = new Map(); + resolvedRates.set(table, resolved); + } + let rate = resolved.get(model); + if (rate === undefined) { + rate = resolveRate(table, model); + resolved.set(model, rate); + } + return rate; +} + +function resolveRate(table: RateTable, model: string): ModelRate | null { const key = stripVariantSuffix(normalizeRateKey(model)); const bareName = bareModelName(key); if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null; @@ -186,17 +265,37 @@ export function lookupRate(table: RateTable, model: string): ModelRate | null { /** The parts of a transcript record that decide its price. */ export type PricedRecord = Pick< UsageRecord, - "model" | "rateModel" | "totals" | "fast" | "reportedCostUsd" + "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd" >; export interface PricedUsage { readonly costUsd: number; readonly costSource: UsageCostSource; + /** `costUsd` by token category, or `null` when no rates are known to split it. */ + readonly categoryCostUsd: UsageCategoryCost | null; + /** What `costUsd` exceeds the same tokens at standard rates. `0` without rates. */ + readonly speedPremiumUsd: number; +} + +function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost { + return { + input: totals.uncachedInputTokens * rates.inputCostPerToken, + cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken, + cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken, + output: totals.outputTokens * rates.outputCostPerToken, + }; +} + +function sumCategories(cost: UsageCategoryCost): number { + return cost.input + cost.cacheRead + cost.cacheWrite + cost.output; } /** * Prices one record's tokens. * + * A provider-reported cost is kept as is, and split by category and speed in + * proportion to the model's list rates when those are known. + * * `reasoningTokens` is intentionally not charged separately: it is already * counted inside `outputTokens`. */ @@ -207,22 +306,37 @@ export function priceUsage( ): PricedUsage { const { model, totals, reportedCostUsd } = record; const override = overrides?.get(model.trim()); - if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) { - return { costUsd: reportedCostUsd, costSource: "providerReported" }; - } - + const reported = + override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd) + ? reportedCostUsd + : null; + const unsplit = (costUsd: number, costSource: UsageCostSource): PricedUsage => ({ + costUsd, + costSource, + categoryCostUsd: null, + speedPremiumUsd: 0, + }); const rate = override ?? lookupRate(table, record.rateModel ?? model); - if (rate === null) return { costUsd: 0, costSource: "unpriced" }; - - const standardCostUsd = - totals.uncachedInputTokens * rate.inputCostPerToken + - totals.cachedInputTokens * rate.cacheReadCostPerToken + - totals.cacheCreationTokens * rate.cacheCreationCostPerToken + - totals.outputTokens * rate.outputCostPerToken; + if (rate === null) { + return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported"); + } + const listCost = costByCategory(totals, ratesAt(rate, record.speed)); + const listCostUsd = sumCategories(listCost); + if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported"); + const premiumUsd = + record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate)); + const scale = reported === null ? 1 : reported / listCostUsd; return { - costUsd: standardCostUsd * (record.fast ? rate.fastMultiplier : 1), - costSource: "modelPriced", + costUsd: reported ?? listCostUsd, + costSource: reported === null ? "modelPriced" : "providerReported", + categoryCostUsd: { + input: listCost.input * scale, + cacheRead: listCost.cacheRead * scale, + cacheWrite: listCost.cacheWrite * scale, + output: listCost.output * scale, + }, + speedPremiumUsd: premiumUsd * scale, }; } @@ -238,9 +352,6 @@ export function cacheSavingsUsd( const rate = overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model); if (rate === null) return 0; - return ( - record.totals.cachedInputTokens * - (rate.inputCostPerToken - rate.cacheReadCostPerToken) * - (record.fast ? rate.fastMultiplier : 1) - ); + const rates = ratesAt(rate, record.speed); + return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken); } diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 6455b1eb7770..b59768cf892b 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -4,6 +4,7 @@ import { decodeScanCache, dedupeWithinFile, encodeScanCache, + makeScanCacheWriter, pruneScanCache, type CachedFile, type ScanCache, @@ -24,7 +25,7 @@ function record(overrides: Partial = {}): UsageRecord { reasoningTokens: 0, }, reportedCostUsd: null, - fast: false, + speed: "standard", dedupeKey: "msg_1:", ...overrides, }; @@ -61,7 +62,7 @@ describe("scan cache round trip", () => { [ "/a.jsonl", 100, - [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", fast: true })], + [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })], ], ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]], ]); @@ -79,11 +80,14 @@ describe("scan cache round trip", () => { size: 80, mtimeMs: 400, provider: "codex", - records: [record({ provider: "codex", model: "gpt-5.2-codex", dedupeKey: null })], + records: [ + record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null, speed: "ultrafast" }), + ], tailRecords: [], position: position({ codexState: { - model: "gpt-5.2-codex", + model: "gpt-6-astra", + speed: "ultrafast", sessionId: "session-c", lastUsageSignature: '{"input_tokens":1}', sawSessionMeta: true, @@ -128,8 +132,8 @@ describe("scan cache round trip", () => { expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false); }); - it("drops an entry whose fast flag is not 0 or 1", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ fast: true })]]])); + it("drops an entry whose speed is not a known index", () => { + const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ speed: "fast" })]]])); const row = encoded.files["/a.jsonl"]!.r[0]!; const poisoned = { ...encoded, @@ -139,13 +143,33 @@ describe("scan cache round trip", () => { expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false); }); - it("rejects a document from the previous cache version", () => { + it("rejects a document from before records carried a speed", () => { const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); const previous = { ...encoded, version: 3 }; expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0); }); + it("rewrites only changed entries and still restores the whole cache", () => { + const write = makeScanCacheWriter(); + const cache = cacheWith([ + ["/a.jsonl", 100, [record()]], + ["/b.jsonl", 200, [record({ sessionId: "session-b" })]], + ]); + const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; + expect(decodeScanCache(JSON.parse(write(cache, { sources })))).toEqual(cache); + + // The replacement adds intern entries; /a's memoised indexes must hold. + cache.set("/b.jsonl", { + ...cache.get("/b.jsonl")!, + size: 30, + records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], + }); + const document = JSON.parse(write(cache, { sources })); + expect(decodeScanCache(document)).toEqual(cache); + expect(document.sources).toEqual(sources); + }); + it("interns repeated model and session strings", () => { const encoded = encodeScanCache( cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]), diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 79cca5cff8e2..04e7ab4ce982 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -17,14 +17,33 @@ import type { UsageProviderKind } from "@t3tools/contracts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -import type { CodexScanState, UsageRecord } from "./usageTranscripts.ts"; +import type { CodexScanState, UsageRecord, UsageSpeed } from "./usageTranscripts.ts"; // v2: Codex fork-copy suppression changed what a file parses to, so v1 // entries would keep serving double-counted records forever. // v3: entries carry the parse position and reducer state so a grown file // re-parses only its appended bytes instead of starting over. // v4: records carry Claude fast mode, which v3 rows never captured. -const USAGE_SCAN_CACHE_VERSION = 4 as const; +// v5: Codex records carry their service tier. v4 rows store speed the same +// way, so v4 entries still load; see `decodeScanCache` for v4 Codex entries. +const USAGE_SCAN_CACHE_VERSION = 5 as const; +const SPEED_COMPATIBLE_SINCE_VERSION = 4; + +/** + * Each cache version writes its own file in the state directory. An older + * server sharing that directory cannot read a newer cache and would replace + * it, dropping saved usage for deleted transcripts. Separate files keep both. + * A v5 server reads the legacy (v4) file once, when its own file is missing. + */ +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json"; +export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json"; + +/** Serialised as the index into this list. */ +const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"]; + +function isSpeed(value: unknown): value is UsageSpeed { + return SPEEDS.some((speed) => speed === value); +} export interface CachedFile { readonly size: number; @@ -59,7 +78,7 @@ type SerializedRecord = readonly [ reasoningTokens: number, dedupeKey: string | null, reportedCostUsd: number | null, - fast: 0 | 1, + speed: number, ]; interface SerializedFile { @@ -84,26 +103,32 @@ interface SerializedCache { readonly files: Readonly>; } -/** Serialises the cache, interning the repeated model and session strings. */ -export function encodeScanCache(cache: ScanCache): SerializedCache { - const models: string[] = []; - const sessions: string[] = []; - const modelIndex = new Map(); - const sessionIndex = new Map(); +/** Model and session strings, each stored once and referenced by index. */ +interface InternTables { + readonly models: string[]; + readonly sessions: string[]; + readonly modelIndex: Map; + readonly sessionIndex: Map; +} - const intern = (table: string[], index: Map, value: string): number => { - const existing = index.get(value); - if (existing !== undefined) return existing; - const next = table.length; - table.push(value); - index.set(value, next); - return next; - }; +function makeInternTables(): InternTables { + return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() }; +} + +function intern(table: string[], index: Map, value: string): number { + const existing = index.get(value); + if (existing !== undefined) return existing; + const next = table.length; + table.push(value); + index.set(value, next); + return next; +} +function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile { const serializeRecord = (record: UsageRecord): SerializedRecord => [ record.timestampMs, - intern(models, modelIndex, record.model), - intern(sessions, sessionIndex, record.sessionId), + intern(tables.models, tables.modelIndex, record.model), + intern(tables.sessions, tables.sessionIndex, record.sessionId), record.totals.uncachedInputTokens, record.totals.cachedInputTokens, record.totals.cacheCreationTokens, @@ -111,25 +136,70 @@ export function encodeScanCache(cache: ScanCache): SerializedCache { record.totals.reasoningTokens, record.dedupeKey, record.reportedCostUsd, - record.fast ? 1 : 0, + SPEEDS.indexOf(record.speed), ]; + return { + s: entry.size, + m: entry.mtimeMs, + p: entry.provider, + r: entry.records.map(serializeRecord), + t: entry.tailRecords.map(serializeRecord), + o: entry.position.resumeOffset, + gl: entry.position.guardLength, + gh: entry.position.guardHash, + cs: entry.position.codexState, + }; +} +/** Serialises the cache, interning the repeated model and session strings. */ +export function encodeScanCache(cache: ScanCache): SerializedCache { + const tables = makeInternTables(); const files: Record = {}; - for (const [path, entry] of cache) { - files[path] = { - s: entry.size, - m: entry.mtimeMs, - p: entry.provider, - r: entry.records.map(serializeRecord), - t: entry.tailRecords.map(serializeRecord), - o: entry.position.resumeOffset, - gl: entry.position.guardLength, - gh: entry.position.guardHash, - cs: entry.position.codexState, - }; - } + for (const [path, entry] of cache) files[path] = serializeFile(entry, tables); + return { + version: USAGE_SCAN_CACHE_VERSION, + models: tables.models, + sessions: tables.sessions, + files, + }; +} - return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files }; +/** + * Returns a function that serialises the cache to JSON text, re-encoding only + * the entries that changed since its last call. Call it once per persist. + * + * Writes the same document as `encodeScanCache`. Most entries never change + * between scans, and encoding all of them made each persist cost close to a + * second on a large cache. Entries are replaced, never mutated, when their file + * changes, so an entry's JSON is memoised by identity. The intern tables only + * grow, so a memoised entry's indexes stay valid; a pruned entry can leave an + * unused string behind until the next process start. + */ +export function makeScanCacheWriter(): ( + cache: ScanCache, + extra: Readonly>, +) => string { + const tables = makeInternTables(); + const fragments = new WeakMap(); + return (cache, extra) => { + const files: string[] = []; + for (const [path, entry] of cache) { + let fragment = fragments.get(entry); + if (fragment === undefined) { + fragment = JSON.stringify(serializeFile(entry, tables)); + fragments.set(entry, fragment); + } + files.push(`${JSON.stringify(path)}:${fragment}`); + } + // Encoded after the files, which may have added to the intern tables. + const head = JSON.stringify({ + ...extra, + version: USAGE_SCAN_CACHE_VERSION, + models: tables.models, + sessions: tables.sessions, + }); + return `${head.slice(0, -1)},"files":{${files.join(",")}}}`; + }; } function isRecordArray(value: unknown): value is readonly unknown[] { @@ -147,7 +217,14 @@ export function decodeScanCache(document: unknown): ScanCache { if (typeof document !== "object" || document === null) return cache; const root = document as Partial; - if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache; + const version = root.version; + if ( + typeof version !== "number" || + version < SPEED_COMPATIBLE_SINCE_VERSION || + version > USAGE_SCAN_CACHE_VERSION + ) { + return cache; + } if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache; if (typeof root.files !== "object" || root.files === null) return cache; @@ -180,8 +257,9 @@ export function decodeScanCache(document: unknown): ScanCache { reasoning, dedupeKey, reportedCostUsd, - fast, + speedIndex, ] = row as SerializedRecord; + const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined; const model = typeof modelIndex === "number" ? models[modelIndex] : undefined; if ( @@ -193,7 +271,7 @@ export function decodeScanCache(document: unknown): ScanCache { !Number.isFinite(cacheCreation) || !Number.isFinite(output) || !Number.isFinite(reasoning) || - (fast !== 0 && fast !== 1) + speed === undefined ) { return null; } @@ -211,7 +289,7 @@ export function decodeScanCache(document: unknown): ScanCache { reasoningTokens: reasoning, }, reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, - fast: fast === 1, + speed, dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, }); } @@ -242,7 +320,11 @@ export function decodeScanCache(document: unknown): ScanCache { ) { continue; } - const codexState = decodeCodexState(entry.cs); + // v4 Codex records predate service tiers, so they all priced as standard. + // Keep them, because the rollout may be gone, but make a live rollout + // re-parse whole: no file has size -1, and a zero position cannot resume. + const legacyCodex = entry.p === "codex" && version < USAGE_SCAN_CACHE_VERSION; + const codexState = legacyCodex ? null : decodeCodexState(entry.cs); if (codexState === undefined) continue; const provider: UsageProviderKind = entry.p; @@ -251,17 +333,14 @@ export function decodeScanCache(document: unknown): ScanCache { if (records === null || tailRecords === null) continue; cache.set(path, { - size: entry.s, + size: legacyCodex ? -1 : entry.s, mtimeMs: entry.m, provider, records, tailRecords, - position: { - resumeOffset: entry.o, - guardLength: entry.gl, - guardHash: entry.gh, - codexState, - }, + position: legacyCodex + ? { resumeOffset: 0, guardLength: 0, guardHash: 0, codexState: null } + : { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, codexState }, }); } @@ -279,6 +358,7 @@ function decodeCodexState(value: unknown): CodexScanState | null | undefined { const state = value as Partial; if ( typeof state.model !== "string" || + !isSpeed(state.speed) || typeof state.sessionId !== "string" || (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") || typeof state.sawSessionMeta !== "boolean" || @@ -290,6 +370,7 @@ function decodeCodexState(value: unknown): CodexScanState | null | undefined { } return { model: state.model, + speed: state.speed, sessionId: state.sessionId, lastUsageSignature: state.lastUsageSignature ?? null, sawSessionMeta: state.sawSessionMeta, diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index 6c95a36df19b..e55c01ad4919 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -76,6 +76,14 @@ function codexModelLine(model: string): string { })}\n`; } +function codexTierLine(serviceTier: string): string { + return `${JSON.stringify({ + type: "event_msg", + timestamp: "2026-08-01T10:00:01Z", + payload: { type: "thread_settings_applied", thread_settings: { service_tier: serviceTier } }, + })}\n`; +} + function codexUsageLine(outputTokens: number, secondsOffset: number): string { return `${JSON.stringify({ type: "event_msg", @@ -111,19 +119,24 @@ describe("readTranscriptRecords resume", () => { it("carries the Codex reducer state across the resume boundary", async () => { const path = NodePath.join(dir, "rollout.jsonl"); - await NodeFSP.writeFile(path, codexMetaLine() + codexModelLine("gpt-5.2-codex")); + await NodeFSP.writeFile( + path, + codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"), + ); const first = await readTranscriptRecords(path, "codex"); assert.isNotNull(first); assert.strictEqual(first.records.length, 0); - // The appended usage event has no turn_context or session_meta of its own; - // model and session must come from the state captured before the boundary. + // The appended usage event has no turn_context, thread settings, or + // session_meta of its own; model, tier, and session must come from the + // state captured before the boundary. await NodeFSP.appendFile(path, codexUsageLine(9, 5)); const second = await readTranscriptRecords(path, "codex", first.position); assert.isNotNull(second); assert.isTrue(second.resumed); assert.strictEqual(second.records.length, 1); assert.strictEqual(second.records[0]?.model, "gpt-5.2-codex"); + assert.strictEqual(second.records[0]?.speed, "ultrafast"); assert.strictEqual(second.records[0]?.sessionId, "codex-session-1"); }); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index faa686990777..bca22468a95e 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -85,6 +85,8 @@ export const GUARD_LENGTH = 64; // readers; it never discards a record because of its size. const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024; const NEWLINE = 0x0a; +/** `stat` calls one transcript walk keeps in flight. The libuv pool has 4 threads. */ +const STAT_CONCURRENCY = 32; const CARRIAGE_RETURN = 0x0d; type SelectedFields = { readonly [key: string]: true | SelectedFields }; @@ -108,6 +110,7 @@ const USAGE_FIELDS: Record<"claude" | "codex" | "grok", SelectedFields> = { id: true, session_id: true, model: true, + thread_settings: { service_tier: true }, forked_from_id: true, source: { subagent: { thread_spawn: { parent_thread_id: true } } }, info: { last_token_usage: true }, @@ -155,15 +158,19 @@ function fnv1a(buffer: Buffer): number { * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`). * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that * never carry usage, so the basename filter keeps a cold scan off those files. + * + * Directories are listed depth-first, one at a time, then the candidates are + * stat'd by a fixed pool of workers: a warm scan stats thousands of files, and + * one at a time each waits its own trip through the thread pool. Results keep + * `readdir` order, which the aggregator's first-seen dedupe relies on. */ export async function listTranscriptFiles( root: string, sinceMs: number, options?: { readonly fileName?: string }, ): Promise { - const found: TranscriptFile[] = []; const fileName = options?.fileName; - + const candidates: string[] = []; const walk = async (dir: string): Promise => { let entries; try { @@ -173,28 +180,33 @@ export async function listTranscriptFiles( } for (const entry of entries) { const child = NodePath.join(dir, entry.name); - if (entry.isDirectory()) { - await walk(child); - continue; - } - if (fileName !== undefined) { - if (entry.name !== fileName) continue; - } else if (!entry.name.endsWith(".jsonl")) { - continue; + if (entry.isDirectory()) await walk(child); + else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) { + candidates.push(child); } + } + }; + await walk(root); + + const found: Array = Array.from({ length: candidates.length }); + // Each worker pulls the next candidate from one shared iterator. + const queue = candidates.entries(); + const statQueued = async (): Promise => { + for (const [index, path] of queue) { try { - const stats = await NodeFSP.stat(child); + const stats = await NodeFSP.stat(path); if (stats.mtimeMs >= sinceMs) { - found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs }); + found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs }; } } catch { // Vanished between readdir and stat. } } }; - - await walk(root); - return found; + await Promise.all( + Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued), + ); + return found.filter((file) => file !== undefined); } /** @@ -245,9 +257,10 @@ async function guardMatches( * still match, so only appended lines are read; otherwise the whole file is * re-parsed from the start and `resumed` reports `false`. * - * Codex carries the active model on `turn_context` lines that hold no usage of - * their own, so those still have to pass through the reducer to keep model - * attribution correct. + * Codex carries the active model on `turn_context` lines and the service tier + * on `thread_settings_applied` lines. Neither holds usage of its own, but both + * still have to pass through the reducer to keep attribution and pricing + * correct. */ export async function readTranscriptRecords( filePath: string, @@ -283,6 +296,7 @@ export async function readTranscriptRecords( if ( !mightCarryUsage(line, provider) && !line.includes('"turn_context"') && + !line.includes('"thread_settings_applied"') && !line.includes('"session_meta"') ) { return; diff --git a/apps/server/src/usage/usageTranscriptStreaming.test.ts b/apps/server/src/usage/usageTranscriptStreaming.test.ts index 2187fd4aa431..fd23593e5523 100644 --- a/apps/server/src/usage/usageTranscriptStreaming.test.ts +++ b/apps/server/src/usage/usageTranscriptStreaming.test.ts @@ -122,7 +122,7 @@ describe("large usage records", () => { reasoningTokens: 0, }, reportedCostUsd: 0.25, - fast: true, + speed: "fast", dedupeKey: "m1:r-m1", }, ]); diff --git a/apps/server/src/usage/usageTranscripts.test.ts b/apps/server/src/usage/usageTranscripts.test.ts index ace3b7d18cf7..8d668a139822 100644 --- a/apps/server/src/usage/usageTranscripts.test.ts +++ b/apps/server/src/usage/usageTranscripts.test.ts @@ -53,15 +53,15 @@ describe("parseClaudeLine", () => { reasoningTokens: 0, }); expect(record?.dedupeKey).toBe("msg_1:"); - expect(record?.fast).toBe(false); + expect(record?.speed).toBe("standard"); }); it("marks fast-mode requests", () => { const line = (speed: string) => parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed })); - expect(line("fast")?.fast).toBe(true); - expect(line("standard")?.fast).toBe(false); + expect(line("fast")?.speed).toBe("fast"); + expect(line("standard")?.speed).toBe("standard"); }); it("gives every content block of one message the same dedupe key", () => { @@ -148,6 +148,27 @@ describe("parseCodexLine", () => { expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull(); }); + it("carries the service tier from the latest thread settings", () => { + const settings = (thread_settings: Record) => + JSON.stringify({ + type: "event_msg", + timestamp: "2026-08-01T05:17:42.000Z", + payload: { type: "thread_settings_applied", thread_settings }, + }); + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const speedAfter = (line: string, output: number) => { + parseCodexLine(line, state); + return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed; + }; + + expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard"); + expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast"); + expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast"); + // Codex omits the field when no tier was requested. + expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard"); + }); + // A forked/subagent rollout opens with the parent's history copied in and // every line re-stamped to the fork instant, then the ancestors' session // metas. Counting those again multiplied usage ~1.85x on real data (#5758). diff --git a/apps/server/src/usage/usageTranscripts.ts b/apps/server/src/usage/usageTranscripts.ts index c3903ef47194..451f8a726b3e 100644 --- a/apps/server/src/usage/usageTranscripts.ts +++ b/apps/server/src/usage/usageTranscripts.ts @@ -8,6 +8,13 @@ */ import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts"; +/** + * Billing speed of a request. Faster speeds bill at a model-specific premium. + * Claude fast mode and Codex `priority` are `fast`; Codex `ultrafast` is its + * own, more expensive tier. + */ +export type UsageSpeed = "standard" | "fast" | "ultrafast"; + export interface UsageRecord { readonly provider: UsageProviderKind; readonly timestampMs: number; @@ -20,11 +27,8 @@ export interface UsageRecord { readonly sessionId: string; readonly totals: UsageTokenTotals; readonly reportedCostUsd: number | null; - /** - * Whether the request ran in fast mode, which bills at a model-specific - * multiple of the standard rate. Only Claude Code records this. - */ - readonly fast: boolean; + /** Only Claude Code and Codex record a speed; other providers are `standard`. */ + readonly speed: UsageSpeed; /** * Key for cross-file de-duplication, or `null` when the record is inherently * unique and needs no dedup. @@ -50,16 +54,6 @@ function parseTimestampMs(value: unknown): number | null { return Number.isNaN(parsed) ? null : parsed; } -export function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals { - return { - uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens, - cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens, - cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens, - outputTokens: a.outputTokens + b.outputTokens, - reasoningTokens: a.reasoningTokens + b.reasoningTokens, - }; -} - export function totalTokens(totals: UsageTokenTotals): number { // reasoningTokens is a subset of outputTokens and must not be added again. return ( @@ -159,7 +153,7 @@ export function parseClaudeRecord(parsed: unknown): UsageRecord | null { reasoningTokens: 0, }, reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null, - fast: usageRecord["speed"] === "fast", + speed: usageRecord["speed"] === "fast" ? "fast" : "standard", dedupeKey, }; } @@ -171,12 +165,14 @@ export function parseClaudeRecord(parsed: unknown): UsageRecord | null { /** * Rolling state for a single Codex rollout file. * - * Codex `token_count` events carry no model, so the model is carried forward - * from the most recent `turn_context`. Sessions that switch models mid-run - * attribute correctly from the switch onward. + * Codex `token_count` events carry no model or service tier, so both are + * carried forward: the model from the most recent `turn_context`, the tier from + * the most recent `thread_settings_applied`. Sessions that switch either + * mid-run attribute correctly from the switch onward. */ export interface CodexScanState { model: string; + speed: UsageSpeed; sessionId: string; lastUsageSignature: string | null; sawSessionMeta: boolean; @@ -188,6 +184,7 @@ export interface CodexScanState { export function initialCodexScanState(): CodexScanState { return { model: "", + speed: "standard", sessionId: "", lastUsageSignature: null, sawSessionMeta: false, @@ -265,6 +262,14 @@ export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageR return null; } + if (payloadType === "thread_settings_applied") { + const settings = payloadRecord["thread_settings"]; + if (typeof settings === "object" && settings !== null) { + state.speed = codexSpeed((settings as Record)["service_tier"]); + } + return null; + } + if (payloadType !== "token_count") return null; const info = payloadRecord["info"]; @@ -323,13 +328,24 @@ export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageR totals, // Codex does not report cost in the rollout. reportedCostUsd: null, - fast: false, + speed: state.speed, // Events surviving the fork-copy suppression above are unique to this // rollout, so they need no global dedup. dedupeKey: null, }; } +/** + * Maps a Codex `service_tier` to its billing speed. Codex omits the field when + * no tier was requested, which bills as standard, as do `default` and + * `standard`. `fast` is accepted as an alias of `priority`. + */ +function codexSpeed(serviceTier: unknown): UsageSpeed { + if (serviceTier === "priority" || serviceTier === "fast") return "fast"; + if (serviceTier === "ultrafast") return "ultrafast"; + return "standard"; +} + /* -------------------------------------------------------------------------- */ /* Grok Build */ /* -------------------------------------------------------------------------- */ @@ -457,7 +473,7 @@ export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] { sessionId, totals: grokTotalsToUsage(topLevel), reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks), - fast: false, + speed: "standard", // No prompt id means we cannot tell two same-second updates apart. dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`, }, @@ -504,7 +520,7 @@ export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] { sessionId, totals, reportedCostUsd, - fast: false, + speed: "standard", dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`, }); } diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e280f0750cef..630d64c49b6c 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,15 +1,29 @@ import { assert, it } from "@effect/vitest"; -import { ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts"; +import { + ORCHESTRATION_PROTOCOL_VERSION, + type ServerConfig, + type ServerConfigStreamEvent, +} from "@t3tools/contracts"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as ConfigProvider from "effect/ConfigProvider"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import * as ExternalLauncher from "./process/externalLauncher.ts"; import { hasCompatibleOrchestrationProtocol, resolveAvailableEditorsForConfig, shouldUseBoundedThreadSnapshot, + withLateEditorConfig, } from "./ws.ts"; it("accepts only the current orchestration protocol before websocket RPC setup", () => { @@ -48,3 +62,175 @@ it.effect("does not block server config when editor discovery never resolves", ( assert.deepEqual(availableEditors, []); }), ); + +// Only the fields the late-editor fold reads or rewrites. +const snapshotConfig = (fields: Partial) => + ({ availableEditors: [], settings: {}, ...fields }) as unknown as ServerConfig; + +const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({ + version: 1, + type: "settingsUpdated", + payload: { settings: settings as ServerConfig["settings"] }, +}); + +it.effect("resends late editors without rolling back updates already sent", () => + Effect.gen(function* () { + const settingsSent = yield* Deferred.make(); + const events = yield* withLateEditorConfig( + snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }), + Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })), + { + resolveAvailableEditors: () => Effect.succeed(["file-manager"]), + // Holds the late snapshot until the settings change has gone out. + resolveFileManagerRevealKind: () => + Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)), + }, + ).pipe( + Stream.tap((event) => + event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void, + ), + Stream.runCollect, + ); + + const [first, second] = Array.from(events); + assert.equal(events.length, 2); + assert.equal(first?.type, "settingsUpdated"); + assert.equal(second?.type, "snapshot"); + if (second?.type === "snapshot") { + assert.deepEqual(second.config.availableEditors, ["file-manager"]); + assert.equal(second.config.shellRevealInFileManagerKind, "file-explorer"); + assert.deepEqual(second.config.settings, { enableProviderUpdateChecks: false } as never); + } + }), +); + +it.effect("sends no late snapshot when the scan matches the snapshot", () => + Effect.gen(function* () { + const events = yield* withLateEditorConfig( + snapshotConfig({ availableEditors: ["vscode"] }), + Stream.empty, + { + resolveAvailableEditors: () => Effect.succeed(["vscode"]), + resolveFileManagerRevealKind: () => Effect.succeed(undefined), + }, + ).pipe(Stream.runCollect); + + assert.equal(events.length, 0); + }), +); + +it.effect("resends a file manager reveal kind that missed the snapshot", () => + Effect.gen(function* () { + const events = yield* withLateEditorConfig( + snapshotConfig({ availableEditors: ["file-manager"] }), + Stream.empty, + { + resolveAvailableEditors: () => Effect.succeed(["file-manager"]), + resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"), + }, + ).pipe(Stream.runCollect); + + const [late] = Array.from(events); + assert.equal(events.length, 1); + assert.equal(late?.type, "snapshot"); + if (late?.type === "snapshot") { + assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer"); + } + }), +); + +// The real launcher on Windows over a filesystem whose probes park until +// released, like a host too busy to finish discovery inside the snapshot timeout. +const makeParkedWindowsLauncher = Effect.gen(function* () { + const parkedProbes = yield* Queue.unbounded(); + const release = yield* Deferred.make(); + const launcher = yield* ExternalLauncher.make.pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + stat: () => + Queue.offer(parkedProbes, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as({ type: "File" } as FileSystem.File.Info), + ), + }), + Path.layer, + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.die("unexpected spawn")), + ), + ), + ), + ); + const onWindows = (effect: Effect.Effect) => + effect.pipe( + Effect.provideService(HostProcessPlatform, "win32"), + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { PATH: "C:\\t3-late-editors-test", PATHEXT: ".EXE" }, + }), + ), + ), + ); + return { + editors: { + resolveAvailableEditors: () => onWindows(launcher.resolveAvailableEditors()), + resolveFileManagerRevealKind: () => onWindows(launcher.resolveFileManagerRevealKind()), + }, + probeParked: Queue.take(parkedProbes), + releaseProbes: Deferred.succeed(release, undefined), + }; +}); + +it.effect("recovers editors after a real scan outlasts the config timeout", () => + Effect.gen(function* () { + const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher; + + const snapshotFiber = yield* resolveAvailableEditorsForConfig( + editors.resolveAvailableEditors(), + ).pipe(Effect.forkChild); + yield* probeParked; + yield* TestClock.adjust(Duration.seconds(5)); + const snapshotEditors = yield* Fiber.join(snapshotFiber); + assert.deepEqual(snapshotEditors, []); + + const lateFiber = yield* withLateEditorConfig( + snapshotConfig({ availableEditors: snapshotEditors }), + Stream.empty, + editors, + ).pipe(Stream.runCollect, Effect.forkChild); + yield* releaseProbes; + + const [late] = Array.from(yield* Fiber.join(lateFiber)); + assert.equal(late?.type, "snapshot"); + if (late?.type === "snapshot") { + assert.equal(late.config.availableEditors.includes("vscode"), true); + } + }).pipe(Effect.scoped), +); + +it.effect("recovers a reveal kind whose real probe outlasts the config timeout", () => + Effect.gen(function* () { + const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher; + + // The snapshot's bounded probe timed out: file manager, but no reveal kind. + const lateFiber = yield* withLateEditorConfig( + snapshotConfig({ availableEditors: ["file-manager"] }), + Stream.empty, + { + resolveAvailableEditors: () => Effect.succeed(["file-manager"]), + resolveFileManagerRevealKind: editors.resolveFileManagerRevealKind, + }, + ).pipe(Stream.runCollect, Effect.forkChild); + yield* probeParked; + yield* TestClock.adjust(Duration.seconds(6)); + yield* releaseProbes; + + const [late] = Array.from(yield* Fiber.join(lateFiber)); + assert.equal(late?.type, "snapshot"); + if (late?.type === "snapshot") { + assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer"); + } + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 3ef4a983d7c5..8d850f8a67aa 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -76,6 +76,8 @@ import { type RelayClientInstallProgressEvent, type ServerSelfUpdateError, type ServerSelfUpdateProgressEvent, + type ServerConfig as ClientServerConfig, + type ServerConfigStreamEvent, type ServerLifecycleStreamEvent, type FilesystemBrowseFailure, FilesystemBrowseError, @@ -155,9 +157,9 @@ import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as OrchestrationEventStore from "./persistence/Services/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; import { - observeRpcEffect as instrumentRpcEffect, - observeRpcStream as instrumentRpcStream, - observeRpcStreamEffect as instrumentRpcStreamEffect, + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, } from "./observability/RpcInstrumentation.ts"; import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts"; import * as ProviderInstanceRegistry from "./provider/Services/ProviderInstanceRegistry.ts"; @@ -210,7 +212,11 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import { requiredScopeForRpcMethod, requiredScopeForDeviceList } from "./auth/RpcAuthorization.ts"; +import { + requiredScopeForDeviceList, + rpcAuthorizationError, + rpcScopeAuthorizationLayer, +} from "./auth/RpcAuthorization.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; @@ -266,6 +272,94 @@ const resolveFileManagerRevealKindForConfig = ( discovery: Effect.Effect, ) => resolveDiscoveryForConfig(discovery, () => undefined); +type EditorDiscovery = Pick< + ExternalLauncher.ExternalLauncher["Service"], + "resolveAvailableEditors" | "resolveFileManagerRevealKind" +>; + +// The config fields that follow from which editors are installed. +const resolveEditorConfig = ( + availableEditors: ReadonlyArray, + revealKind: Effect.Effect, +) => + Effect.gen(function* () { + const fileManagerRevealKind = availableEditors.includes("file-manager") + ? yield* revealKind + : undefined; + return { + availableEditors, + ...(fileManagerRevealKind === undefined + ? {} + : { + shellRevealInFileManager: true, + shellRevealInFileManagerKind: fileManagerRevealKind, + }), + }; + }); + +/** + * Live config updates that follow a snapshot of `config`. A busy host can + * outlast the snapshot's discovery timeouts, which send no editors, or no + * reveal kind for the file manager. The scan keeps running, so once it lands + * this resends the config: clients replace theirs on any snapshot. The resent + * config is folded from the live updates already sent, so it cannot roll back + * a change that landed while the scan ran. + */ +export const withLateEditorConfig = ( + config: ClientServerConfig, + liveUpdates: Stream.Stream, + launcher: EditorDiscovery, +) => { + const lateEditorConfig = Stream.fromEffect(launcher.resolveAvailableEditors()).pipe( + Stream.filter( + (editors) => + editors.join() !== config.availableEditors.join() || + (editors.includes("file-manager") && config.shellRevealInFileManagerKind === undefined), + ), + // Unbounded, unlike the snapshot: the reveal-kind probe is not shared, so + // a timeout here would cancel a probe that outlasts it every time. + Stream.mapEffect((editors) => + resolveEditorConfig(editors, launcher.resolveFileManagerRevealKind()), + ), + Stream.filter( + (editorConfig) => + editorConfig.availableEditors.join() !== config.availableEditors.join() || + editorConfig.shellRevealInFileManagerKind !== config.shellRevealInFileManagerKind, + ), + Stream.map((editorConfig) => ({ type: "editorsResolved" as const, editorConfig })), + ); + + return Stream.merge(liveUpdates, lateEditorConfig).pipe( + Stream.mapAccum( + (): ClientServerConfig => config, + (current, event): readonly [ClientServerConfig, ReadonlyArray] => { + switch (event.type) { + case "editorsResolved": { + const { + availableEditors: _editors, + shellRevealInFileManager: _reveal, + shellRevealInFileManagerKind: _revealKind, + ...rest + } = current; + const next = { ...rest, ...event.editorConfig }; + return [next, [{ version: 1, type: "snapshot", config: next }]]; + } + case "keybindingsUpdated": + return [{ ...current, ...event.payload }, [event]]; + case "providerStatuses": + return [{ ...current, providers: event.payload.providers }, [event]]; + case "settingsUpdated": + return [{ ...current, settings: event.payload.settings }, [event]]; + // Themes and usage-limit sources never ride in a snapshot; clients + // carry their projected values across one. + default: + return [current, [event]]; + } + }, + ), + ); +}; + function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } @@ -1225,25 +1319,15 @@ const makeWsRpcLayer = ( const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; const relayClient = yield* RelayClient.RelayClient; - const authorizationError = (requiredScope: AuthEnvironmentScope) => - new EnvironmentAuthorizationError({ - message: `The authenticated token is missing required scope: ${requiredScope}.`, - requiredScope, - }); + // RpcScopeAuthorization checks each RPC's declared scope before its handler + // runs. This covers the one RPC whose scope depends on its input. const authorizeEffect = ( requiredScope: AuthEnvironmentScope, effect: Effect.Effect, ): Effect.Effect => currentSession.scopes.includes(requiredScope) ? effect - : Effect.fail(authorizationError(requiredScope)); - const authorizeStream = ( - requiredScope: AuthEnvironmentScope, - stream: Stream.Stream, - ): Stream.Stream => - currentSession.scopes.includes(requiredScope) - ? stream - : Stream.fail(authorizationError(requiredScope)); + : Effect.fail(rpcAuthorizationError(requiredScope)); const acpRegistryProject = Effect.fn("ws.acpRegistry.project")(function* ( projectId: ProjectId, @@ -1566,40 +1650,6 @@ const makeWsRpcLayer = ( yield* providerRegistry.refreshInstance(input.instanceId); return { disabled: true } as const; }); - const observeRpcEffect = ( - method: string, - effect: Effect.Effect, - traceAttributes?: Readonly>, - ) => - instrumentRpcEffect( - method, - authorizeEffect(requiredScopeForRpcMethod(method), effect), - traceAttributes, - ); - const observeRpcStream = ( - method: string, - stream: Stream.Stream, - traceAttributes?: Readonly>, - ) => - instrumentRpcStream( - method, - authorizeStream(requiredScopeForRpcMethod(method), stream), - traceAttributes, - ); - const observeRpcStreamEffect = ( - method: string, - effect: Effect.Effect< - Stream.Stream, - EffectError, - EffectContext - >, - traceAttributes?: Readonly>, - ) => - instrumentRpcStreamEffect( - method, - authorizeEffect(requiredScopeForRpcMethod(method), effect), - traceAttributes, - ); const loadAuthAccessSnapshot = () => Effect.all({ pairingLinks: serverAuth.listPairingLinks(), @@ -1629,14 +1679,10 @@ const makeWsRpcLayer = ( const scratchWorkspaceRoot = config.localAgentRuns ? yield* managedFolders.scratchRoot : Option.none(); - const availableEditors: ReadonlyArray = yield* resolveAvailableEditorsForConfig( - externalLauncher.resolveAvailableEditors(), + const editorConfig = yield* resolveEditorConfig( + yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()), + resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()), ); - const fileManagerRevealKind = availableEditors.includes("file-manager") - ? yield* resolveFileManagerRevealKindForConfig( - externalLauncher.resolveFileManagerRevealKind(), - ) - : undefined; return { environment, @@ -1647,7 +1693,7 @@ const makeWsRpcLayer = ( keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, providers, - availableEditors, + ...editorConfig, // Same discovery-with-timeout treatment as editors: a slow probe // must not stall server.getConfig, so it degrades to no targets. remoteOpenTargets: yield* resolveAvailableEditorsForConfig( @@ -1669,12 +1715,6 @@ const makeWsRpcLayer = ( }, settings, shellResumeCompletionMarker: true, - ...(fileManagerRevealKind === undefined - ? {} - : { - shellRevealInFileManager: true, - shellRevealInFileManagerKind: fileManagerRevealKind, - }), threadResumeCompletionMarker: true, threadSnapshotPagination: true, ...Option.match(scratchWorkspaceRoot, { @@ -3643,7 +3683,7 @@ const makeWsRpcLayer = ( return Stream.concat( rpcInitialItems([{ version: 1 as const, type: "snapshot" as const, config }]), - liveUpdates, + withLateEditorConfig(config, liveUpdates, externalLauncher), ); }), { "rpc.aggregate": "server" }, @@ -3773,6 +3813,7 @@ export const websocketRpcRouteLayer = Layer.unwrap( const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; yield* RpcServer.make(ServerWsRpcGroup, { disableTracing: true }).pipe( Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)), + Effect.provide(rpcScopeAuthorizationLayer(session.scopes)), Effect.forkScoped, ); // @effect-diagnostics-next-line returnEffectInGen:off diff --git a/apps/web/package.json b/apps/web/package.json index b90b9740fc53..ffccf206f910 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -40,6 +40,7 @@ "@tiptap/starter-kit": "^3.31.3", "class-variance-authority": "^0.7.1", "culori": "^4.0.2", + "dompurify": "^3.4.16", "effect": "catalog:", "hast-util-to-html": "^9.0.5", "hast-util-to-jsx-runtime": "^2.3.6", @@ -47,8 +48,10 @@ "jose": "catalog:", "jsonc-parser": "3.3.1", "jszip": "3.10.1", + "lucide": "^0.564.0", "lucide-react": "^0.564.0", - "mermaid": "^12.0.0", + "mermaid": "^11.17.2", + "morphicons": "^1.7.1", "react": "19.2.6", "react-dom": "19.2.6", "react-markdown": "^10.1.0", diff --git a/apps/web/src/cloud/useCloudChat.tsx b/apps/web/src/cloud/useCloudChat.tsx index e826c4d69508..c67e5b832844 100644 --- a/apps/web/src/cloud/useCloudChat.tsx +++ b/apps/web/src/cloud/useCloudChat.tsx @@ -505,7 +505,14 @@ export function useCloudChat(input: { }); }, [draftId, projectOffAnotherChatsBox, sendInFlightRef]); useEffect(() => { - if (!draftId || !redirectEnvironment || sendInFlightRef.current) return; + // A machine whose "No project" folder does not exist yet has no project to move to. + if ( + !draftId || + !redirectEnvironment || + redirectEnvironment.projectId === null || + sendInFlightRef.current + ) + return; useComposerDraftStore.getState().setDraftThreadContext(draftId, { projectRef: scopeProjectRef(redirectEnvironment.environmentId, redirectEnvironment.projectId), environmentSelection: "manual", @@ -985,7 +992,7 @@ export function useCloudChat(input: { environments: input.projectEnvironments, runTargets: runTargets.environments, }); - return next + return next?.projectId ? scopeProjectRef(next.environmentId, next.projectId) : scopeProjectRef(project.environmentId, project.id); }; diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index cfa62ad7fe92..d018802a590a 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -16,7 +16,8 @@ export { export interface EnvironmentOption { environmentId: EnvironmentId; - projectId: ProjectId; + /** Null when the machine's "No project" folder is not created yet. */ + projectId: ProjectId | null; label: string; isPrimary: boolean; machine: EnvironmentMachineKind; diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx index 465be828364b..3afa31e2acee 100644 --- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -59,7 +59,11 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe }: BranchToolbarEnvModeSelectorProps) { const workspacePath = displayMode === "panel" ? (activeWorktreePath ?? workspaceRoot) : null; const workspaceDisplayName = resolveWorkspaceDisplayName(workspacePath); - const workspaceKind = activeWorktreePath ? "Worktree" : "Project folder"; + // The panel names the workspace kind only when it is not the project folder. + const workspaceKind = activeWorktreePath ? "Worktree" : null; + const lockedWorkspaceKind = forceNewWorktree ? "Worktree" : workspaceKind; + const selectWorkspaceKind = + effectiveEnvMode === "worktree" && !activeWorktreePath ? "Create" : workspaceKind; const composerFloatingLayerProps = useComposerMenuProps(); const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree); const envModeItems = useMemo( @@ -147,9 +151,9 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe : (workspaceDisplayName ?? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode))} - {displayMode === "panel" ? ( + {displayMode === "panel" && lockedWorkspaceKind ? ( - {forceNewWorktree ? "Worktree" : workspaceKind} + {lockedWorkspaceKind} ) : null} @@ -210,9 +214,9 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe - {displayMode === "panel" ? ( + {displayMode === "panel" && selectWorkspaceKind ? ( - {effectiveEnvMode === "worktree" && !activeWorktreePath ? "Create" : workspaceKind} + {selectWorkspaceKind} ) : null} diff --git a/apps/web/src/components/ChatMarkdown.mermaid.test.tsx b/apps/web/src/components/ChatMarkdown.mermaid.test.tsx deleted file mode 100644 index 19b8bd867d5a..000000000000 --- a/apps/web/src/components/ChatMarkdown.mermaid.test.tsx +++ /dev/null @@ -1,222 +0,0 @@ -import { act, type ComponentProps, type ReactNode } from "react"; -import { create, type ReactTestRenderer } from "react-test-renderer"; -import { describe, expect, it, vi } from "vite-plus/test"; - -import { renderMermaidImage } from "../lib/mermaidRendering"; -import { Button } from "./ui/button"; - -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null })); -vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) })); -vi.mock("../hooks/useSettings", async (importOriginal) => { - const actual = await importOriginal(); - const settings = actual.getClientSettings(); - return { - ...actual, - useClientSettings: (select?: (value: typeof settings) => unknown) => - select ? select(settings) : settings, - }; -}); -vi.mock("./ui/tooltip", async () => { - const { cloneElement, isValidElement } = await import("react"); - return { - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger({ - render, - children, - }: ComponentProps) { - if (!isValidElement(render)) return <>{children}; - return children === undefined ? render : cloneElement(render, undefined, children); - }, - TooltipPopup: () => null, - }; -}); -vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() })); -vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() })); -vi.mock("../state/session", async (importOriginal) => ({ - ...(await importOriginal()), - usePreparedConnection: () => ({ _tag: "Loading" }), -})); -vi.mock("../state/entities", () => ({ - readThreadShell: () => null, - useProjects: () => [], - useServerConfigs: () => new Map(), -})); -vi.mock("../remoteOpen", () => ({ - useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }), -})); -vi.mock("../editorPreferences", () => ({ - useOpenInPreferredEditor: () => vi.fn(), - usePreferredEditor: () => [null, vi.fn()], -})); -vi.mock("../lib/mermaidRendering", async (importOriginal) => ({ - ...(await importOriginal()), - readCachedMermaidImage: () => null, - renderMermaidImage: vi.fn(), -})); -vi.mock("~/lib/openPullRequestLink", () => ({ - findProjectOnChangeRequestHost: () => undefined, - parseChangeRequestUrl: () => null, - resolvePullRequestPreviewTarget: () => null, - useOpenChangeRequestLink: () => vi.fn(), -})); - -import ChatMarkdown from "./ChatMarkdown"; - -function codeButton(renderer: ReactTestRenderer, label: string) { - const button = renderer.root - .findAllByType(Button) - .find((instance) => instance.props["aria-label"] === label); - if (!button) throw new Error(`Missing code button: ${label}`); - return button.props as ComponentProps; -} - -describe("ChatMarkdown Mermaid diagrams", () => { - const diagram = "```mermaid\nflowchart TD\n A --> B\n```"; - const src = "data:image/svg+xml;charset=utf-8,%3Csvg%2F%3E"; - const imageSources = (renderer: ReactTestRenderer) => - renderer.root.findAllByType("img").map((image) => image.props.src as string); - const showsSource = (renderer: ReactTestRenderer) => - renderer.root.findAll( - (node) => node.type === "pre" || node.props.className === "chat-markdown-shiki", - ).length === 1; - - it("keeps a streaming fence as code and renders it once, after the message completes", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.mocked(renderMermaidImage).mockReset().mockResolvedValue({ ok: true, src }); - let renderer: ReactTestRenderer | undefined; - try { - await act(async () => { - renderer = create(); - }); - expect(imageSources(renderer!)).toEqual([]); - - await act(async () => { - renderer!.update(); - }); - expect(imageSources(renderer!)).toEqual([src]); - - await act(async () => { - renderer!.update(); - }); - expect(imageSources(renderer!)).toEqual([src]); - expect(vi.mocked(renderMermaidImage).mock.calls).toEqual([ - ["flowchart TD\n A --> B\n", "dark"], - ]); - } finally { - await act(async () => renderer?.unmount()); - vi.unstubAllGlobals(); - } - }); - - it("leaves unclosed and non-Mermaid fences as code in a completed message", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.mocked(renderMermaidImage).mockReset().mockResolvedValue({ ok: true, src }); - let renderer: ReactTestRenderer | undefined; - try { - for (const text of [ - "```mermaid\nflowchart TD\n A --> B", - "````mermaid\nflowchart TD\n```", - "```text\nflowchart TD\n A --> B\n```", - ]) { - await act(async () => { - renderer = create(); - }); - expect([text, imageSources(renderer!)]).toEqual([text, []]); - await act(async () => renderer?.unmount()); - } - expect(renderMermaidImage).not.toHaveBeenCalled(); - - await act(async () => { - renderer = create(); - }); - expect(imageSources(renderer!)).toEqual([src]); - } finally { - await act(async () => renderer?.unmount()); - vi.unstubAllGlobals(); - } - }); - - it("toggles between diagram and source, and copy always copies the source", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - const writeText = vi.fn(async (_text: string) => {}); - vi.stubGlobal("navigator", { clipboard: { writeText } }); - vi.mocked(renderMermaidImage).mockReset().mockResolvedValue({ ok: true, src }); - let renderer: ReactTestRenderer | undefined; - try { - await act(async () => { - renderer = create(); - }); - await act(async () => { - codeButton(renderer!, "Copy code").onClick?.({} as never); - }); - await act(async () => { - codeButton(renderer!, "Show source").onClick?.({} as never); - }); - expect([imageSources(renderer!), showsSource(renderer!)]).toEqual([[], true]); - - await act(async () => { - codeButton(renderer!, "Show diagram").onClick?.({} as never); - }); - expect(imageSources(renderer!)).toEqual([src]); - expect(writeText.mock.calls).toEqual([["flowchart TD\n A --> B\n"]]); - expect(renderer!.root.findByType("img").props["data-markdown-copy"]).toBe( - "```mermaid\nflowchart TD\n A --> B\n```\n\n", - ); - } finally { - await act(async () => renderer?.unmount()); - vi.unstubAllGlobals(); - } - }); - - it("waits to render a diagram until it scrolls into view", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - let reportIntersection = (_isIntersecting: boolean) => {}; - vi.stubGlobal( - "IntersectionObserver", - class { - constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) { - reportIntersection = (isIntersecting) => callback([{ isIntersecting }]); - } - observe() {} - disconnect() {} - }, - ); - vi.mocked(renderMermaidImage).mockReset().mockResolvedValue({ ok: true, src }); - let renderer: ReactTestRenderer | undefined; - try { - await act(async () => { - renderer = create(, { - createNodeMock: () => ({}), - }); - }); - await act(async () => reportIntersection(false)); - expect(imageSources(renderer!)).toEqual([]); - - await act(async () => reportIntersection(true)); - expect(imageSources(renderer!)).toEqual([src]); - expect(renderMermaidImage).toHaveBeenCalledTimes(1); - } finally { - await act(async () => renderer?.unmount()); - vi.unstubAllGlobals(); - } - }); - - it("falls back to the source with a note when a diagram fails to render", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.mocked(renderMermaidImage).mockReset().mockResolvedValue({ ok: false }); - let renderer: ReactTestRenderer | undefined; - try { - await act(async () => { - renderer = create(); - }); - expect(imageSources(renderer!)).toEqual([]); - expect(renderer!.root.findByProps({ role: "status" }).props.children).toBe( - "This diagram could not be rendered. Showing its source.", - ); - expect(showsSource(renderer!)).toBe(true); - } finally { - await act(async () => renderer?.unmount()); - vi.unstubAllGlobals(); - } - }); -}); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index dac6d331028a..5358e253af4f 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -5,9 +5,8 @@ import { encodeComposerContextClipboardHtml, } from "@t3tools/shared/composerContextClipboard"; import { - CheckIcon, ChevronRightIcon, - CopyIcon, + CodeIcon, FileSpreadsheetIcon, FileTextIcon, GlobeIcon, @@ -15,18 +14,18 @@ import { InfoIcon, LightbulbIcon, MailIcon, - Maximize2Icon, MessageSquareIcon, MessageSquareWarningIcon, - Minimize2Icon, OctagonAlertIcon, PlayIcon, PresentationIcon, SparklesIcon, TriangleAlertIcon, + WorkflowIcon, WrapTextIcon, type LucideIcon, } from "lucide-react"; +import { Check, Copy, Maximize2, Minimize2 } from "lucide"; import type { AssetResource, EnvironmentId, @@ -121,6 +120,7 @@ import { import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; +import { MorphIcon } from "~/components/MorphIcon"; import { ContextChip } from "./ContextChip"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible"; import { ScrollArea } from "./ui/scroll-area"; @@ -141,7 +141,7 @@ import { GitHubIcon } from "./Icons"; import { createIncrementalHighlightedDocument } from "../lib/incrementalHighlighting"; import { HighlightedCodeLines } from "./chat/HighlightedCodeLines"; import { RenderErrorBoundary } from "./RenderErrorBoundary"; -import { mermaidPreview } from "./MarkdownMermaidBlock"; +import { MermaidDiagram } from "./chat/MermaidDiagram"; import { useTheme } from "../hooks/useTheme"; import { getClientSettings, useClientSettings } from "../hooks/useSettings"; import { @@ -847,7 +847,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) { /> } > - {expanded ? : } + {expandLabel} @@ -867,7 +867,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) { /> } > - {copied ? : } + {copyLabel} @@ -976,7 +976,9 @@ function MarkdownCodeBlock({ theme, onRunShellCommand, isStreaming, - renderPreview, + leadingActions, + canWrap = true, + diagram = false, children, }: { code: string; @@ -985,7 +987,10 @@ function MarkdownCodeBlock({ theme: "light" | "dark"; onRunShellCommand?: ((command: string) => void) | undefined; isStreaming: boolean; - renderPreview?: ((source: ReactNode) => ReactNode) | undefined; + leadingActions?: ReactNode; + canWrap?: boolean; + /** Renders content instead of code, with actions below it like tables. */ + diagram?: boolean; children: ReactNode; }) { const [copied, setCopied] = useState(false); @@ -1043,6 +1048,37 @@ function MarkdownCodeBlock({ [], ); + const copyButton = ( + + + } + > + + + {copyLabel} + + ); + + if (diagram) { + return ( +
+ {children} +
+ {leadingActions} + {copyButton} +
+
+ ); + } + return (
- - setWrapped((value) => !value)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + {leadingActions} + {canWrap ? ( + + setWrapped((value) => !value)} + aria-label={wrapLabel} + /> + } + > + + + {wrapLabel} + + ) : null} {canRun ? ( Run in terminal ) : null} + {copyButton} + +
+ {children} + + ); +} + +/** + * Mermaid fences render as a diagram once the response settles; streaming and + * the code toggle keep the highlighted source. + */ +function MarkdownMermaidCodeBlock({ + code, + fenceTitle, + theme, + isStreaming, + onExpand, + children, +}: { + code: string; + fenceTitle: string | null; + theme: "light" | "dark"; + isStreaming: boolean; + onExpand: (imageUrl: string) => void; + children: ReactNode; +}) { + const [showCode, setShowCode] = useState(false); + const showDiagram = !showCode && !isStreaming && code.trim().length > 0; + const toggleLabel = showCode ? "Show diagram" : "Show code"; + return ( + setShowCode((value) => !value)} + aria-label={toggleLabel} /> } > - {copied ? : } + {showCode ? : } - {copyLabel} + {toggleLabel} - - - {renderPreview ? renderPreview(children) : children} - + ) + } + > + {showDiagram ? ( + + + Rendering diagram + + } + > + + + + ) : ( + children + )} + ); } @@ -3303,7 +3398,7 @@ const CHAT_MARKDOWN_COMPONENTS = { return {children}; }, pre: function MarkdownPre({ node, children, ...props }) { - const { resolvedTheme, diffThemeName, isStreaming, onRunShellCommand, text } = use( + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand, text } = use( ChatMarkdownRendererContext, ); const codeBlock = extractCodeBlock(children); @@ -3313,6 +3408,42 @@ const CHAT_MARKDOWN_COMPONENTS = { const language = extractFenceLanguage(codeBlock.className); const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); + const highlightedCode = ( + {children}} + > + {/* Reserve the block's height but stay hidden until Shiki has colored + it, so plain text never flashes before the highlighted version. */} + + {children} + + } + > + + + + ); + if (language === "mermaid") { + return ( + expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })} + > + {highlightedCode} + + ); + } return ( - {children}} - > - {/* Reserve the block's height but stay hidden until Shiki has colored - it, so plain text never flashes before the highlighted version. */} - - {children} - - } - > - - - + {highlightedCode} ); }, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e64f5b085fcf..9452855a3acf 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -23,6 +23,8 @@ import { } from "./ChatView.logic"; import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment"; import * as Cloud from "../cloud/useCloudChat"; +import { useScratchProject } from "../hooks/useScratchProject"; +import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { latestExecutedRun, @@ -293,7 +295,10 @@ import { import { cn, randomUUID } from "~/lib/utils"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; -import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; +import { + decodeProjectScriptKeybindingRule, + keybindingValueForCommand, +} from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { buildProjectScript, @@ -1533,6 +1538,9 @@ export default function ChatView(props: ChatViewProps) { const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, { reportFailure: false, }); + const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, { + reportFailure: false, + }); const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); @@ -2649,26 +2657,56 @@ export default function ChatView(props: ChatViewProps) { }, [navigate, setEnvironmentEnabled], ); + const { scratchWorkspaceRootFor, openScratchProject } = useScratchProject(); + const activeProjectIsScratch = + activeProject !== null && + isScratchProject( + activeProject, + environmentById.get(activeProject.environmentId)?.serverConfig?.scratchWorkspaceRoot ?? null, + ); const projectEnvironments = useMemo(() => { if (!activeProject) return []; - const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings); - const memberProjects = allProjects.filter( - (p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey, - ); - const seen = new Set(); const envs: EnvironmentOption[] = []; - for (const p of memberProjects) { - if (seen.has(p.environmentId)) continue; - seen.add(p.environmentId); - const isPrimary = p.environmentId === primaryEnvironmentId; - const environment = environmentById.get(p.environmentId) ?? null; + const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => { + const environment = environmentById.get(environmentId) ?? null; envs.push({ - environmentId: p.environmentId, - projectId: p.id, - label: environment?.label ?? p.environmentId, - isPrimary, + environmentId, + projectId, + label: environment?.label ?? environmentId, + isPrimary: environmentId === primaryEnvironmentId, machine: resolveEnvironmentMachineKind(environment?.serverConfig ?? null), }); + }; + if (activeProjectIsScratch && draftId) { + // Each machine keeps its own "No project" folder at its own path, so they + // never group as one logical project. Offer every machine that has one. + for (const environment of environments) { + const scratchRoot = scratchWorkspaceRootFor(environment.environmentId); + // Keep the current machine visible so an offline source can still switch away. + if (scratchRoot === null && environment.environmentId !== activeProject.environmentId) + continue; + const scratchProject = + environment.environmentId === activeProject.environmentId + ? activeProject + : allProjects.find( + (p) => + p.environmentId === environment.environmentId && isScratchProject(p, scratchRoot), + ); + pushEnvironment(environment.environmentId, scratchProject?.id ?? null); + } + } else { + const logicalKey = deriveLogicalProjectKeyFromSettings( + activeProject, + projectGroupingSettings, + ); + const seen = new Set(); + for (const p of allProjects) { + if (seen.has(p.environmentId)) continue; + if (deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) !== logicalKey) + continue; + seen.add(p.environmentId); + pushEnvironment(p.environmentId, p.id); + } } // Sort: primary first, then alphabetical envs.sort((a, b) => { @@ -2676,7 +2714,17 @@ export default function ChatView(props: ChatViewProps) { return a.label.localeCompare(b.label); }); return envs; - }, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]); + }, [ + activeProject, + activeProjectIsScratch, + allProjects, + draftId, + environments, + projectGroupingSettings, + primaryEnvironmentId, + environmentById, + scratchWorkspaceRootFor, + ]); const { runTargets, logicalProjectEnvironments } = Cloud.useNewChatRunTargets({ projectEnvironments, environmentById, @@ -2685,6 +2733,9 @@ export default function ChatView(props: ChatViewProps) { managerConfig: primaryEnvironment?.serverConfig, }); const hasMultipleEnvironments = logicalProjectEnvironments.length > 1; + // Auto balance retargets to an existing project; a machine's "No project" + // folder may not exist until it is picked. + const canAutoBalanceEnvironments = hasMultipleEnvironments && !activeProjectIsScratch; const activeEnvironmentOption = logicalProjectEnvironments.find( (environment) => environment.environmentId === activeThread?.environmentId, @@ -2903,7 +2954,7 @@ export default function ChatView(props: ChatViewProps) { clientSettingsHydrated && draftId && !envLocked && - hasMultipleEnvironments && + canAutoBalanceEnvironments && loadBalancingSettings.loadBalancingEnabled && draftThread?.environmentSelection !== "manual" && (!composerHasAttachments || Boolean(draftThread?.loadBalancedEnvironmentId)) && @@ -4239,7 +4290,7 @@ export default function ChatView(props: ChatViewProps) { const target = logicalProjectEnvironments.find( (environment) => environment.environmentId === loadBalancing.environmentId, ); - if (!target) return; + if (!target?.projectId) return; setDraftThreadContext(draftId, { projectRef: scopeProjectRef(target.environmentId, target.projectId), environmentSelection: "auto", @@ -4294,28 +4345,91 @@ export default function ChatView(props: ChatViewProps) { : "Auto balance" : undefined; - // Handle environment change for draft threads. When the user picks a - // different environment we update the draft context to point at the physical - // project in that environment while keeping the same logical project. + const environmentChangeRef = useRef(null); + const [isEnvironmentChanging, setIsEnvironmentChanging] = useState(false); + useLayoutEffect(() => { + return () => { + environmentChangeRef.current = null; + setIsEnvironmentChanging(false); + }; + }, [draftId, activeProjectKey]); + const onEnvironmentChange = useCallback( (nextEnvironmentId: EnvironmentId) => { - if (envLocked || !draftId) return; + if (envLocked || !draftId || sendInFlightRef.current) return; + const originalDraft = getDraftSession(draftId); + if (!originalDraft || originalDraft.promotedTo) return; const target = logicalProjectEnvironments.find( (env) => env.environmentId === nextEnvironmentId, ); if (!target) return; cloud.onEnvironmentPicked(nextEnvironmentId); - setDraftThreadContext(draftId, { - projectRef: scopeProjectRef(target.environmentId, target.projectId), - environmentSelection: "manual", - loadBalancedEnvironmentId: null, - }); + const request = Symbol(); + environmentChangeRef.current = request; + setIsEnvironmentChanging(false); + const retarget = (project: (typeof allProjects)[number]) => { + const currentDraft = getDraftSession(draftId); + if ( + environmentChangeRef.current !== request || + sendInFlightRef.current || + !currentDraft || + currentDraft.promotedTo || + currentDraft.environmentId !== originalDraft.environmentId || + currentDraft.projectId !== originalDraft.projectId + ) + return; + const projectRef = scopeProjectRef(target.environmentId, project.id); + if (activeProjectIsScratch) { + // Scratch projects are machine-local, so move their logical mapping too. + setLogicalProjectDraftThreadId( + deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings), + projectRef, + draftId, + { environmentSelection: "manual", loadBalancedEnvironmentId: null }, + ); + } else { + setDraftThreadContext(draftId, { + projectRef, + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); + } + }; + const finish = () => { + if (environmentChangeRef.current === request) { + environmentChangeRef.current = null; + setIsEnvironmentChanging(false); + } + }; + if (target.projectId !== null) { + const project = allProjects.find( + (project) => + project.environmentId === target.environmentId && project.id === target.projectId, + ); + if (project) retarget(project); + finish(); + return; + } + // Keep send disabled until the destination Scratch project is ready. + setIsEnvironmentChanging(true); + void openScratchProject(target.environmentId) + .then((project) => { + if (project) retarget(project); + }) + .finally(finish); }, [ + activeProjectIsScratch, + allProjects, draftId, envLocked, + getDraftSession, logicalProjectEnvironments, + openScratchProject, + projectGroupingSettings, + sendInFlightRef, setDraftThreadContext, + setLogicalProjectDraftThreadId, cloud.onEnvironmentPicked, ], ); @@ -4884,20 +4998,64 @@ export default function ChatView(props: ChatViewProps) { command: input.keybindingCommand, }); - if (isElectron && keybindingRule) { - return mapAtomCommandResult( - await upsertKeybinding({ - environmentId, - input: keybindingRule, - }), - () => undefined, - ); + if (!isElectron) return updateResult; + + const scriptId = input.keybindingCommand + ? projectScriptIdFromCommand(input.keybindingCommand) + : null; + if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) { + return updateResult; } - return updateResult; + const retainedElsewhere = + !input.nextScripts.some((script) => script.id === scriptId) && + (settings.defaultProjectScripts.some((script) => script.id === scriptId) || + Object.entries(settings.projectSettingsOverrides).some( + ([projectId, entry]) => + projectId !== input.projectId && + entry.defaultProjectScripts?.some((script) => script.id === scriptId), + ) || + allProjects.some( + (other) => + other.environmentId === environmentId && + other.id !== input.projectId && + resolveProjectScripts(settings, other).some((script) => script.id === scriptId), + )); + if (!keybindingRule && retainedElsewhere) return updateResult; + + const previousRules = ( + environmentById.get(environmentId)?.serverConfig?.keybindings ?? [] + ).flatMap((binding) => { + if (binding.command !== input.keybindingCommand || binding.whenAst) return []; + const previous = decodeProjectScriptKeybindingRule({ + keybinding: keybindingValueForCommand([binding], input.keybindingCommand), + command: input.keybindingCommand, + }); + return previous ? [previous] : []; + }); + const previous = previousRules.at(-1); + for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) { + const result = await removeKeybinding({ environmentId, input: rule }); + if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined); + } + return keybindingRule + ? mapAtomCommandResult( + await upsertKeybinding({ + environmentId, + input: + previous && previous.key !== keybindingRule.key + ? { ...keybindingRule, replace: previous } + : keybindingRule, + }), + () => undefined, + ) + : updateResult; }, [ + allProjects, + environmentById, environmentId, - settings.projectSettingsOverrides, + removeKeybinding, + settings, supportsProjectSettingsOverrides, updateProjectScriptSettings, upsertKeybinding, @@ -6916,7 +7074,7 @@ export default function ChatView(props: ChatViewProps) { // The stack renders items[0] front-most and tucks the rest behind hover, so // ordering is priority: system banners, then the branch-mismatch notice, // and the informational parked-thread banner last — it must never cover another. - // Background work (subagent fleets, workflow runs, watch loops) can outlive + // Background work (subagent fleets, workflow runs, watch loops, dev servers) can outlive // the turn; once it settles, the composer stop button is gone, so this // banner is the only visible stop affordance. The interrupt path also // accepts a completed run while its provider still has background work. @@ -6964,9 +7122,14 @@ export default function ChatView(props: ChatViewProps) { id: `background-work:${activeThread.id}`, variant: "default", priority: "activity", + // A dev server can run for hours after the agent is done, so only work + // that will wake the agent pulses. icon: (