diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6d053cb4f..b48b93cffb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,16 +80,6 @@ jobs: sudo apt-get install -y --no-install-recommends build-essential command -v cc - # Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present), - # but ACP process-tree live tests compile a small pthread fixture with `cc` - # and soft-skip when it is missing. Install build-essential so that path - # always runs in CI instead of silently no-oping. - - name: Install C toolchain for process-tree fixtures - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends build-essential - command -v cc - - name: Setup Vite+ uses: voidzero-dev/setup-vp@v1 with: diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index d5b5194bfc..c684689fb2 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -11,23 +11,62 @@ Object.assign(process.env, repoEnv); const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT); const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1"; -const VARIANT_CONFIG: Record< - AppVariant, - { - readonly appName: string; - readonly scheme: string; - readonly iosIcon: string; - readonly iosBundleIdentifier: string; - readonly androidPackage: string; - readonly relyingParty?: string; - } -> = { +const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim(); +const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/; + +const fromRepoRoot = (relativePath: string) => `../../${relativePath}`; + +if ( + isIosPersonalTeamBuild && + (!personalTeamBundleIdentifier || + !IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier)) +) { + throw new Error( + "T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.", + ); +} + +const DEVELOPMENT_ASSETS = { + appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng), + iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject), + splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng), + androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng), + androidAdaptiveBackgroundColor: "#00639B", + androidMonochromeIcon: "./assets/android-icon-mark.png", + androidNotificationIcon: "./assets/android-notification-icon.png", + androidNotificationColor: "#00639B", +} as const; + +const PREVIEW_ASSETS = { + appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng), + iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject), + splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng), + androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng), + androidAdaptiveBackgroundColor: "#111533", + androidMonochromeIcon: "./assets/android-icon-mark.png", + androidNotificationIcon: "./assets/android-notification-icon.png", + androidNotificationColor: "#7565C7", +} as const; + +const RELEASE_ASSETS = { + appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng), + iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject), + splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng), + androidAdaptiveForeground: "./assets/android-icon-mark.png", + androidAdaptiveBackgroundColor: "#000000", + androidMonochromeIcon: "./assets/android-icon-mark.png", + androidNotificationIcon: "./assets/android-notification-icon.png", + androidNotificationColor: "#FFFFFF", +} as const; + +const VARIANT_CONFIG = { development: { appName: "T3 Code Dev", scheme: "t3code-dev", iosBundleIdentifier: "com.t3tools.t3code.dev", androidPackage: "com.t3tools.t3code.dev", relyingParty: "clerk.t3.codes", + assets: DEVELOPMENT_ASSETS, }, preview: { appName: "T3 Code Preview", @@ -35,6 +74,7 @@ const VARIANT_CONFIG: Record< iosBundleIdentifier: "com.t3tools.t3code.preview", androidPackage: "com.t3tools.t3code.preview", relyingParty: "clerk.t3.codes", + assets: PREVIEW_ASSETS, }, production: { appName: "T3 Code", @@ -42,6 +82,7 @@ const VARIANT_CONFIG: Record< iosBundleIdentifier: "com.t3tools.t3code", androidPackage: "com.t3tools.t3code", relyingParty: "clerk.t3.codes", + assets: RELEASE_ASSETS, }, } as const; @@ -140,7 +181,14 @@ const config: ExpoConfig = { ios: { icon: variant.assets.iosIcon, supportsTablet: true, - bundleIdentifier: variant.iosBundleIdentifier, + // Multitasking-capable iPad apps cannot rotate programmatically, so the + // showcase capture build requires full screen (see infoPlist below). + requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1", + bundleIdentifier: iosBundleIdentifier, + // Pin code signing to the T3 Tools team so non-interactive `expo run:ios` + // does not fall back to a personal team (which cannot sign app groups, + // Sign in with Apple, or push notification entitlements). + appleTeamId: "ARK85ZXQ4Z", associatedDomains: [ `applinks:${variant.relyingParty}`, `webcredentials:${variant.relyingParty}`, diff --git a/apps/mobile/src/connection/environment-cache-store.ts b/apps/mobile/src/connection/environment-cache-store.ts index b7036530af..1942cb7cc3 100644 --- a/apps/mobile/src/connection/environment-cache-store.ts +++ b/apps/mobile/src/connection/environment-cache-store.ts @@ -138,7 +138,7 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () { }), ), saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) { - const threadId = snapshot.thread.id; + const threadId = snapshot.projection.thread.id; const payload = yield* encodeStoredThreadSnapshot({ schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, environmentId, diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts index a6ccd4eadb..b043a3b414 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -2,11 +2,6 @@ import { ConnectionPersistenceError, ConnectionRegistrationStore, ConnectionTargetStore, - EnvironmentCacheStore, - ORCHESTRATION_CACHE_SCHEMA_VERSION, - StoredOrchestrationShellSnapshot, - StoredOrchestrationThreadSnapshot, - decodeOrDiscardOrchestrationCache, registerConnectionInCatalog, removeConnectionFromCatalog, removeCatalogValue, @@ -18,88 +13,12 @@ import { CredentialStore, ProfileStore, } from "@t3tools/client-runtime/connection"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as SecureStore from "expo-secure-store"; -import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store"; - -const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots"; -const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots"; -const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots"; - -const StoredShellSnapshot = StoredOrchestrationShellSnapshot; -const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot; -const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot); -const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot); -const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot); -const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot); - -function catalogError(operation: string, cause: unknown) { - return new ConnectionTransientError({ - reason: "remote-unavailable", - detail: `Could not ${operation} the local connection catalog: ${String(cause)}`, - }); -} - -function shellPersistenceError( - operation: - | "load-shell" - | "save-shell" - | "load-thread" - | "save-thread" - | "remove-thread" - | "clear-environment", - cause: unknown, -) { - return new ConnectionPersistenceError({ - operation, - message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`, - }); -} - -function threadSnapshotFileName(threadId: ThreadId): string { - return `${encodeURIComponent(threadId)}.json`; -} - -const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")( - function* ( - environmentId: EnvironmentId, - operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment", - ) { - return yield* Effect.tryPromise({ - try: async () => { - const { Directory, Paths } = await import("expo-file-system"); - const directory = new Directory( - Paths.document, - THREAD_SNAPSHOT_CACHE_DIRECTORY, - encodeURIComponent(environmentId), - ); - if (operation !== "clear-environment") { - directory.create({ idempotent: true, intermediates: true }); - } - return directory; - }, - catch: (cause) => shellPersistenceError(operation, cause), - }); - }, -); - -const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* ( - environmentId: EnvironmentId, - threadId: ThreadId, - operation: "load-thread" | "save-thread" | "remove-thread", -) { - const { File } = yield* Effect.promise(() => import("expo-file-system")); - return new File( - yield* threadSnapshotDirectory(environmentId, operation), - threadSnapshotFileName(threadId), - ); -}); +import * as CatalogStore from "./catalog-store"; function targetPersistenceError( operation: "list-targets" | "register-connection" | "remove-connection", @@ -210,172 +129,6 @@ export const connectionStorageLayer = Layer.effectContext( ), })), }); - const cacheStore = EnvironmentCacheStore.of({ - loadShell: (environmentId) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "load-shell"); - if (file.exists) { - const raw = yield* Effect.tryPromise({ - try: () => file.text(), - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - const parsed = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe( - Effect.mapError((cause) => shellPersistenceError("load-shell", cause)), - ); - return stored.environmentId === environmentId - ? Option.some(stored.snapshot) - : Option.none(); - } - - const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell"); - if (legacyFile.exists) { - yield* Effect.try({ - try: () => legacyFile.delete(), - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - } - - return Option.none(); - }).pipe((decode) => - decodeOrDiscardOrchestrationCache( - decode, - shellSnapshotFile(environmentId, "load-shell").pipe( - Effect.flatMap((file) => - Effect.try({ - try: () => { - if (file.exists) file.delete(); - }, - catch: (cause) => shellPersistenceError("load-shell", cause), - }), - ), - Effect.catch(() => Effect.void), - ), - ), - ), - saveShell: (environmentId, snapshot) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "save-shell"); - const stored = { - schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, - environmentId, - snapshot, - } as const; - const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe( - Effect.mapError((cause) => shellPersistenceError("save-shell", cause)), - ); - yield* Effect.try({ - try: () => { - if (!file.exists) { - file.create({ intermediates: true, overwrite: true }); - } - file.write(JSON.stringify(encoded)); - }, - catch: (cause) => shellPersistenceError("save-shell", cause), - }); - }), - loadThread: (environmentId, threadId) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread"); - if (!file.exists) { - return Option.none(); - } - const raw = yield* Effect.tryPromise({ - try: () => file.text(), - catch: (cause) => shellPersistenceError("load-thread", cause), - }); - const parsed = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => shellPersistenceError("load-thread", cause), - }); - const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe( - Effect.mapError((cause) => shellPersistenceError("load-thread", cause)), - ); - return stored.environmentId === environmentId && stored.threadId === threadId - ? Option.some(stored.thread) - : Option.none(); - }).pipe((decode) => - decodeOrDiscardOrchestrationCache( - decode, - threadSnapshotFile(environmentId, threadId, "load-thread").pipe( - Effect.flatMap((file) => - Effect.try({ - try: () => { - if (file.exists) file.delete(); - }, - catch: (cause) => shellPersistenceError("load-thread", cause), - }), - ), - Effect.catch(() => Effect.void), - ), - ), - ), - saveThread: (environmentId, thread) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, thread.thread.id, "save-thread"); - const encoded = yield* Effect.fromResult( - encodeStoredThreadSnapshot({ - schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, - environmentId, - threadId: thread.thread.id, - thread, - }), - ).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause))); - yield* Effect.try({ - try: () => { - if (!file.exists) { - file.create({ intermediates: true, overwrite: true }); - } - file.write(JSON.stringify(encoded)); - }, - catch: (cause) => shellPersistenceError("save-thread", cause), - }); - }), - removeThread: (environmentId, threadId) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread"); - if (file.exists) { - file.delete(); - } - }).pipe( - Effect.mapError((cause) => - cause._tag === "ConnectionPersistenceError" - ? cause - : shellPersistenceError("remove-thread", cause), - ), - ), - clear: (environmentId) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "clear-environment"); - if (file.exists) { - yield* Effect.try({ - try: () => file.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment"); - if (legacyFile.exists) { - yield* Effect.try({ - try: () => legacyFile.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - const threadDirectory = yield* threadSnapshotDirectory( - environmentId, - "clear-environment", - ); - if (threadDirectory.exists) { - yield* Effect.try({ - try: () => threadDirectory.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - }), - }); - return Context.make(ConnectionTargetStore, targetStore).pipe( Context.add(ConnectionRegistrationStore, registrationStore), Context.add(ProfileStore.ConnectionProfileStore, profileStore), diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 868c60b3fa..f303c407e2 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -120,51 +120,14 @@ interface HomeScreenProps { /* ─── Layout constants ───────────────────────────────────────────────── */ -function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } { - switch (thread.runtime?.status) { - case "running": - case "waiting": - return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" }; - case "completed": - return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" }; - case "queued": - case "starting": - return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" }; - case "failed": - return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" }; - default: - return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" }; - } -} - -const COLLAPSED_THREAD_LIMIT = 6; -const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic)); - -function threadRowExit(values: ExitAnimationsValues) { - "worklet"; - - return { - initialValues: { - height: values.currentHeight, - opacity: 1, - originX: values.currentOriginX, - }, - animations: { - height: withDelay( - 90, - withTiming(0, { - duration: 170, - easing: Easing.inOut(Easing.cubic), - }), - ), - opacity: withDelay(80, withTiming(0, { duration: 100 })), - originX: withTiming(values.currentOriginX - values.windowWidth, { - duration: 190, - easing: Easing.out(Easing.cubic), - }), - }, - }; -} +const ESTIMATED_THREAD_ROW_HEIGHT = 72; +const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44; +/** + * Top spacing between the list and the Android custom header. The Android + * header (AndroidHomeHeader) is rendered in-flow above this screen and + * already consumes the top safe-area inset, so the list only needs breathing + * room here. + */ function deriveEmptyState(props: { readonly catalogState: WorkspaceState; @@ -799,7 +762,7 @@ export function HomeScreen(props: HomeScreenProps) { ?.providers.find( (provider) => provider.instanceId === - (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId), + (thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId), )?.driver ?? null } environmentLabel={ @@ -1045,17 +1008,25 @@ export function HomeScreen(props: HomeScreenProps) { onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined} variant="plain" /> - ) : !hasResults ? ( - - ) : ( - projectGroups.map((group) => { - const isExpanded = expandedProjects.has(group.key); - const visibleThreads = isExpanded - ? group.threads - : group.threads.slice(0, COLLAPSED_THREAD_LIMIT); + {emptyState.loading && !shouldShowConnectionStatus ? ( + + + + ) : null} + {shouldShowConnectionStatus && Platform.OS === "ios" ? ( + + + + ) : null} + + {connectionStatus} + + ); + } const listHeader = ( <> @@ -1091,7 +1062,7 @@ export function HomeScreen(props: HomeScreenProps) { detail="Choose another environment or create a new task." /> ) : ( - + ) ) : null; // Self-contained: v1's listEmpty keys off projectGroups, which ignores the diff --git a/apps/mobile/src/features/home/homeListItems.test.ts b/apps/mobile/src/features/home/homeListItems.test.ts index c5a9f2c6bb..89727851a9 100644 --- a/apps/mobile/src/features/home/homeListItems.test.ts +++ b/apps/mobile/src/features/home/homeListItems.test.ts @@ -1,8 +1,10 @@ -import type { - EnvironmentProject, - EnvironmentThreadShell, +import { + presentThreadShell, + type EnvironmentProject, + type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { @@ -32,29 +34,41 @@ function makeProject(id: string, title: string): EnvironmentProject { }; } +const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z"); + function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell { - return { - environmentId, - id: ThreadId.make(id), + const threadId = ThreadId.make(id); + return presentThreadShell(environmentId, { + id: threadId, projectId, title: `Thread ${id}`, + providerInstanceId: ProviderInstanceId.make("codex"), modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null, - latestTurn: null, - createdAt: "2026-06-01T00:00:00.000Z", - updatedAt: "2026-06-01T00:00:00.000Z", - archivedAt: null, + activeProviderThreadId: null, + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "mobile", + latestRunId: null, + activeRunId: null, + status: "idle", + pendingRuntimeRequest: null, + latestVisibleMessage: null, settledOverride: null, settledAt: null, - session: null, latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, hasActionableProposedPlan: false, - }; + itemCount: 0, + visibleItemCount: 0, + createdAt: threadTimestamp, + updatedAt: threadTimestamp, + archivedAt: null, + deletedAt: null, + }); } function makeGroup(key: string, threadCount: number): HomeThreadGroup { diff --git a/apps/mobile/src/features/home/homeThreadList.test.ts b/apps/mobile/src/features/home/homeThreadList.test.ts index c5caa35a21..6ed8f01982 100644 --- a/apps/mobile/src/features/home/homeThreadList.test.ts +++ b/apps/mobile/src/features/home/homeThreadList.test.ts @@ -6,7 +6,11 @@ import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-searc import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildHomeThreadGroups } from "./homeThreadList"; +import { + buildHomeProjectScopes, + buildHomeThreadGroups, + sortHomeProjectScopes, +} from "./homeThreadList"; import { makeThreadShellFixture } from "../../test-fixtures"; function makeProject( diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 7bfc231d75..21422d0194 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -1,5 +1,5 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { canSettle } from "@t3tools/client-runtime/state/thread-settled"; +import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled"; import * as Cause from "effect/Cause"; import * as Haptics from "expo-haptics"; import { useCallback, useRef } from "react"; diff --git a/apps/mobile/src/features/threads/ThreadActivityInspector.tsx b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx index 66d5c199fb..97d38e9ee3 100644 --- a/apps/mobile/src/features/threads/ThreadActivityInspector.tsx +++ b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx @@ -1,14 +1,13 @@ import * as Haptics from "expo-haptics"; import { SymbolView } from "expo-symbols"; -import type { EnvironmentId } from "@t3tools/contracts"; -import { useRouter } from "expo-router"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; import { buildThreadActivityInspector } from "../../lib/threadActivityInspector"; -import { buildThreadFilesNavigation } from "../../lib/routes"; import { resolveWorkspaceRelativeFilePath } from "../files/filePath"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -22,7 +21,7 @@ export function ThreadActivityInspector(props: { readonly iconColor: ColorValue; readonly workspaceRoot?: string | null; }) { - const router = useRouter(); + const navigation = useNavigation(); const row = props.activity.projectedItem; const support = useV2ItemSupport({ environmentId: props.environmentId, diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 58d61588d9..e92b0613d3 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -92,6 +92,12 @@ export interface ThreadComposerProps { readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; readonly environmentLabel: string | null; + /** + * Message sync phase for the selected thread (drives the status pill): + * "loading" = first fetch, nothing to show yet; "syncing" = cached messages + * are on screen while they reconcile with the server. + */ + readonly threadSyncPhase?: "loading" | "syncing" | null; readonly selectedThread: EnvironmentThreadShell; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index eaf19745bd..eb25473466 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1,5 +1,6 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard"; import type { LegendListRef } from "@legendapp/list/react-native"; import type { @@ -423,6 +424,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread )} + {/* Floating composer — sticks to keyboard via KeyboardStickyView */} + {showContent ? ( + + {/* No paddingTop here: the overlay's measured height becomes the + list's bottom inset, so any padding above the pill/composer + pushes the resting content floor up by the same amount. */} + + ; readonly freeze: SharedValue; readonly anchorMessageId: MessageId | null; @@ -157,6 +163,7 @@ export interface ThreadFeedProps { readonly contentTopInset?: number; readonly contentBottomInset?: number; readonly topAccessory?: ReactNode; + readonly contentMaxWidth?: number; readonly layoutVariant?: LayoutVariant; readonly usesAutomaticContentInsets?: boolean; readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void; @@ -190,7 +197,7 @@ function AssistantForkButton(props: { sourceItemId: props.projectedItem.sourceItemId, }); const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response"); - const router = useRouter(); + const navigation = useNavigation(); const [busy, setBusy] = useState(false); const canFork = canForkProjectedAssistantItem({ projectedItem: props.projectedItem, @@ -907,12 +914,13 @@ function renderFeedEntry( info: { item: ThreadFeedEntry; index: number }, props: Pick & { readonly copiedRowId: string | null; + readonly expandedWorkGroups: Record; readonly expandedWorkRows: Record; readonly terminalAssistantMessageIds: ReadonlySet; readonly unsettledTurnId: RunId | null; readonly onCopyWorkRow: (rowId: string, value: string) => void; readonly onToggleWorkGroup: (groupId: string) => void; - readonly onToggleWorkRow: (rowId: string) => void; + readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void; readonly onToggleTurnFold: (runId: RunId) => void; readonly onPressImage: (uri: string, headers?: Record) => void; readonly onMarkdownLinkPress: (href: string) => void; @@ -928,6 +936,10 @@ function renderFeedEntry( const entry = info.item; const { markdownStyles, iconSubtleColor, userBubbleColor } = props; + if (entry.type === "working") { + return ; + } + if (entry.type === "run-fold") { return ( + {message.createdBy === "agent" ? ( Sent by another agent @@ -1136,7 +1151,8 @@ function renderFeedEntry( expandedRows={props.expandedWorkRows} iconSubtleColor={iconSubtleColor} onCopyRow={props.onCopyWorkRow} - onToggleRow={props.onToggleWorkRow} + onToggleGroup={() => props.onToggleWorkGroup(entry.id)} + onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)} workspaceRoot={props.workspaceRoot} /> ); @@ -1441,8 +1457,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const foldSettleFrameRef = useRef(null); const foldSettleSecondFrameRef = useRef(null); const previousLatestTurnRef = useRef(props.latestRun); - const { width: viewportWidth } = useWindowDimensions(); - const [foldToggleSettling, setFoldToggleSettling] = useState(false); + const disclosureAnchorKeyRef = useRef(null); + const headerMaterialVisibleRef = useRef(false); + const { width: windowWidth } = useWindowDimensions(); + const { appearance } = useAppearancePreferences(); + const [viewportWidth, setViewportWidth] = useState(() => + props.layoutVariant === "split" ? 0 : windowWidth, + ); + const [viewportHeight, setViewportHeight] = useState(0); + const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false); const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; readonly expandedWorkGroups: Record; @@ -1520,6 +1543,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const listAppearanceData = useMemo( () => ({ copiedRowId, + expandedWorkGroups, expandedWorkRows, iconSubtleColor, markdownStyles, @@ -1529,6 +1553,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }), [ copiedRowId, + expandedWorkGroups, expandedWorkRows, iconSubtleColor, markdownStyles, @@ -1537,9 +1562,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { viewportWidth, ], ); - const presentedFeed = useMemo( - () => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds), - [expandedTurnIds, props.feed, props.latestRun], + const reportHeaderMaterialVisibility = useCallback( + (visible: boolean) => { + if (headerMaterialVisibleRef.current === visible) { + return; + } + headerMaterialVisibleRef.current = visible; + props.onHeaderMaterialVisibilityChange?.(visible); + }, + [props.onHeaderMaterialVisibilityChange], ); const handleScroll = useCallback( (event: NativeSyntheticEvent) => { @@ -1594,6 +1625,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { reportHeaderMaterialVisibility(false); }, [props.threadId, reportHeaderMaterialVisibility]); +<<<<<<< HEAD // A thread switch opens pinned to the end; a send explicitly returns to the // live edge (ThreadDetailScreen scrolls the new message into place). Both // re-arm follow regardless of where the user had scrolled before. @@ -1617,22 +1649,22 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } return ids; }, [expandedWorkGroups]); +======= +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) const presentedFeed = useMemo( () => deriveThreadFeedPresentation( props.feed, - props.latestTurn, + props.latestRun, expandedTurnIds, - expandedWorkGroupIds, + new Set( + Object.entries(expandedWorkGroups) + .filter(([, expanded]) => expanded) + .map(([groupId]) => groupId), + ), props.activeWorkStartedAt, ), - [ - expandedTurnIds, - expandedWorkGroupIds, - props.activeWorkStartedAt, - props.feed, - props.latestTurn, - ], + [expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun], ); // The empty↔filled key below remounts the list, which resets its imperative @@ -1776,8 +1808,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ); const onToggleWorkRow = useCallback( - (rowId: string) => { - suspendEndScrollMaintenanceForDisclosure(rowId); + (rowId: string, anchorKey?: string) => { + suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null); setInteractionState((current) => ({ ...current, expandedWorkRows: { @@ -1789,28 +1821,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [suspendEndScrollMaintenanceForDisclosure], ); - const onToggleTurnFold = useCallback((runId: RunId) => { - setFoldToggleSettling(true); - if (foldSettleFrameRef.current !== null) { - cancelAnimationFrame(foldSettleFrameRef.current); - } - if (foldSettleSecondFrameRef.current !== null) { - cancelAnimationFrame(foldSettleSecondFrameRef.current); - } - setInteractionState((current) => { - const next = new Set(current.expandedTurnIds); - if (next.has(runId)) { - next.delete(runId); - } else { - next.add(runId); - } - return { ...current, expandedTurnIds: next }; - }); - foldSettleFrameRef.current = requestAnimationFrame(() => { - foldSettleSecondFrameRef.current = requestAnimationFrame(() => { - setFoldToggleSettling(false); - foldSettleFrameRef.current = null; - foldSettleSecondFrameRef.current = null; + const onToggleTurnFold = useCallback( + (runId: RunId) => { + suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`); + setInteractionState((current) => { + const next = new Set(current.expandedTurnIds); + if (next.has(runId)) { + next.delete(runId); + } else { + next.add(runId); + } + return { ...current, expandedTurnIds: next }; }); }, [suspendEndScrollMaintenanceForDisclosure], @@ -1833,7 +1854,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const getFixedItemSize = useCallback( (entry: ThreadFeedEntry) => { switch (entry.type) { - case "turn-fold": + case "run-fold": return TURN_FOLD_HEIGHT; case "work-toggle": return WORK_GROUP_TOGGLE_HEIGHT; @@ -1858,6 +1879,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { environmentId: props.environmentId, threadId: props.threadId, copiedRowId, + expandedWorkGroups, expandedWorkRows, terminalAssistantMessageIds, unsettledTurnId, @@ -1879,6 +1901,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }), [ copiedRowId, + expandedWorkGroups, expandedWorkRows, terminalAssistantMessageIds, unsettledTurnId, @@ -1945,32 +1968,98 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // render into — which is why the header blur was missing on threads. scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 }, } - } - maintainVisibleContentPosition - data={presentedFeed} - extraData={listAppearanceData} - renderItem={renderItem} - keyExtractor={(entry) => entry.id} - getItemType={(entry) => - entry.type === "message" ? `message:${entry.message.role}` : entry.type - } - keyboardShouldPersistTaps="always" - keyboardDismissMode="none" - keyboardLiftBehavior="whenAtEnd" - estimatedItemSize={180} - initialScrollAtEnd - ListHeaderComponent={ - <> - - {props.topAccessory} - - } - contentContainerStyle={{ - paddingTop: 12, - paddingHorizontal: horizontalPadding, - }} - /> - {props.feed.length === 0 ? ( + : { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })} + {...(anchoredEndSpace ? { anchoredEndSpace } : {})} + itemLayoutAnimation={feedItemLayoutTransition} + // Patched LegendList prop (patches/@legendapp__list@3.2.0.patch): + // lets its scroll math clamp programmatic scrolls to -headerInset + // instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short + // content rest below the transparent header rather than at frame top. + contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0} + contentInsetEndAdjustment={props.contentInsetEndAdjustment} + // UIKit's automatic behavior adds the safe-area bottom on top of the + // raw contentInset the keyboard integration writes. The detail screen + // under-reports the composer inset by this amount (see + // ThreadDetailScreen); this tells LegendList's scroll math about the + // extra so programmatic end scrolls land at the true resting offset. + contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0} + // The keyboard integration's offset math (end pinning, max scroll) + // must add the same UIKit-added extra, or its keyboard-open end + // targets land one safe-area short of the true resting offset. + adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0} + freeze={props.freeze} + // Animated: on send, the optimistic message's dataChange fires + // maintainScrollAtEnd before any render-cycle suppression could + // engage — an instant snap there teleports the feed to the anchor + // instead of scrolling to it. Keeping it enabled (animated) during + // anchor scrolls also lets it correct a scroll that landed on a + // stale end target once the anchor row finishes measuring. + maintainScrollAtEnd={ + disclosureToggleSettling + ? false + : { + animated: true, + on: { + dataChange: true, + itemLayout: true, + layout: true, + }, + } + } + maintainVisibleContentPosition={maintainVisibleContentPosition} + data={presentedFeed} + extraData={listAppearanceData} + renderItem={renderItem} + keyExtractor={(entry) => entry.id} + getItemType={(entry) => + entry.type === "message" ? `message:${entry.message.role}` : entry.type + } + getFixedItemSize={getFixedItemSize} + // Measure rows well before they scroll into view so estimate→actual + // corrections land offscreen instead of under the user's finger. + drawDistance={500} + keyboardShouldPersistTaps="always" + keyboardDismissMode="none" + keyboardLiftBehavior="whenAtEnd" + // Seed the list's scroll math with the real viewport before its own + // onLayout: the empty→filled remount can then tell at mount that + // short content underflows the viewport and skip programmatic + // positioning entirely (any offset write during screen attach races + // UIKit's adjustedContentInset application and lands high or low). + {...(viewportHeight > 0 && viewportWidth > 0 + ? { estimatedListSize: { height: viewportHeight, width: viewportWidth } } + : {})} + // RN's native scrollTo command clamps targets to a floor of + // -contentInset.top using the RAW inset — under automatic insets the + // header inset only exists in adjustedContentInset, so scrolls to + // negative offsets (content top below the transparent header) get + // clamped to 0. This prop disables that clamp; UIKit still bounces + // user overscroll back to the adjusted rest position. + scrollToOverflowEnabled + estimatedItemSize={180} + // Chat-style bottom alignment: when a thread is shorter than the + // viewport, pad above the content so messages rest just above the + // composer instead of under the header. No effect on threads that + // overflow the viewport (the padding clamps to zero). + alignItemsAtEnd + initialScrollAtEnd + onScroll={handleScroll} + scrollEventThrottle={16} + ListHeaderComponent={ + <> + {usesNativeAutomaticInsets ? null : } + {props.topAccessory} + + } + contentContainerStyle={{ + paddingTop: 12, + paddingHorizontal: contentHorizontalPadding, + }} + /> + + {props.feed.length === 0 && + props.activeWorkStartedAt === null && + props.contentPresentation.kind === "ready" ? ( provider.instanceId === - (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId), + (thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId), )?.driver ?? null } environmentLabel={ diff --git a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx index b8565336ec..569093d3c4 100644 --- a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx +++ b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx @@ -18,7 +18,6 @@ import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-nat import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; -import { buildThreadRoutePath } from "../../lib/routes"; import { useThemeColor } from "../../lib/useThemeColor"; import { useThreadShells } from "../../state/entities"; import { threadEnvironment } from "../../state/threads"; @@ -96,7 +95,7 @@ export function ThreadRelationshipsBanner(props: { const canDetach = projection ? canDetachThreadProviderSession(projection) : false; const [visible, setVisible] = useState(false); const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null); - const router = useRouter(); + const navigation = useNavigation(); const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back"); const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop"); const insets = useSafeAreaInsets(); @@ -115,11 +114,14 @@ export function ThreadRelationshipsBanner(props: { const openThread = (threadId: ThreadId, archivedThread: boolean) => { setVisible(false); void Haptics.selectionAsync(); - router.push( - archivedThread - ? "/settings/archive" - : buildThreadRoutePath({ environmentId: props.environmentId, threadId }), - ); + if (archivedThread) { + navigation.navigate("SettingsSheet", { screen: "SettingsArchive" }); + return; + } + navigation.navigate("Thread", { + environmentId: props.environmentId, + threadId, + }); }; const merge = async () => { diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 75b1c88c2f..5bf6c8518c 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -516,7 +516,7 @@ function ThreadRouteContent( terminalDebugLog("terminal-menu:open-new", { hasThread: Boolean(selectedThread), hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), - listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), }); if (!selectedThread || !selectedThreadProject?.workspaceRoot) { @@ -524,7 +524,7 @@ function ThreadRouteContent( } const nextId = nextOpenTerminalId({ - listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), }); void navigation.navigate("ThreadTerminal", { environmentId: String(selectedThread.environmentId), @@ -551,9 +551,9 @@ function ThreadRouteContent( } const targetTerminalId = resolveProjectScriptTerminalId({ - existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId), hasRunningTerminal: terminalMenuSessions.some( - (runtime) => runtime.status === "running" || runtime.status === "starting", + (session) => session.status === "running" || session.status === "starting", ), }); const preferredWorktreePath = resolvePreferredThreadWorktreePath({ 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 0dbc5f3dc8..6998177548 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -28,10 +28,14 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { useThreadPr } from "../../state/use-thread-pr"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { + resolveThreadListV2SnoozeGateExpiryMs, + resolveThreadListV2SnoozeMenuSelection, resolveThreadListV2Status, + resolveThreadListV2SwipeActions, threadHasUnseenCompletion, type ThreadListV2Status, } from "./threadListV2"; +import { ThreadSearchMatchExcerpt } from "./thread-search-match"; /** * Thread List v2 renders one flat native list: rich edge-to-edge rows for @@ -635,7 +639,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { ) : null} - {status === "failed" && thread.session?.lastError ? ( + {status === "failed" && thread.runtime?.lastError ? ( - {thread.session.lastError} + {thread.runtime.lastError} ) : thread.branch || props.environmentLabel ? ( /* "branch · machine" share one truncating line. The machine sits diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index a2e6749574..1b759d5183 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -2,18 +2,21 @@ import * as Haptics from "expo-haptics"; import { Image } from "expo-image"; import { type AppSymbolName, SymbolView } from "../../components/AppSymbol"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { useRouter } from "expo-router"; +import { useNavigation } from "@react-navigation/native"; import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets"; +import { scaledTypographyLineHeight } from "../../lib/appearancePreferences"; import { cn } from "../../lib/cn"; -import { buildThreadRoutePath } from "../../lib/routes"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; +import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import Animated, { FadeIn } from "react-native-reanimated"; import { useV2ItemSupport } from "../../state/v2-item-support"; import { ThreadActivityInspector } from "./ThreadActivityInspector"; import { threadWorkLogOverflowNoun } from "./thread-work-log-labels"; +const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; const WORK_LOG_LAYOUT_ANIMATION = { duration: 180, create: { @@ -117,7 +120,7 @@ function ThreadActivityThreadLink(props: { sourceThreadId: row.sourceThreadId, sourceItemId: row.sourceItemId, }); - const router = useRouter(); + const navigation = useNavigation(); const item = row.item; let targetThreadId: ThreadId | null = null; let label = "Open related thread"; @@ -144,12 +147,10 @@ function ThreadActivityThreadLink(props: { accessibilityLabel={label} onPress={() => { void Haptics.selectionAsync(); - router.push( - buildThreadRoutePath({ - environmentId: props.environmentId, - threadId: targetThreadId, - }), - ); + navigation.navigate("Thread", { + environmentId: props.environmentId, + threadId: targetThreadId, + }); }} className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]" > @@ -159,6 +160,54 @@ function ThreadActivityThreadLink(props: { ); } +// Entering fades only for rows created moments ago: rows remount whenever the +// list scrolls them back into view, and old rows must not replay an entrance. +const FRESH_ROW_WINDOW_MS = 3_000; +function isFreshRow(createdAt: string): boolean { + const timestamp = Date.parse(createdAt); + return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS; +} + +// Tool-like activities with a neutral status carry no signal worth a row. +export function visibleWorkLogActivities( + activities: ReadonlyArray, +): ReadonlyArray { + return activities.filter((activity) => !(activity.toolLike && activity.status === "neutral")); +} + +// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log +// rows are single-line (numberOfLines={1}) inside a min-height that stays +// taller than the text at every supported base font size (text-xs reaches +// 23px at the 22pt maximum, under the 32px min-h-8), so row height is +// deterministic. The "work log" label has no such clamp — its height follows +// the scaled text-2xs line height. Values mirror the classNames below — keep +// them in sync; a mismatch only costs a one-time correction on measure. +const WORK_ROW_HEIGHT = 32; // min-h-8 +const WORK_ROW_GAP = 1; // gap-px +const WORK_LOG_HEADER_PADDING = 2; // pb-0.5 under the "work log" label +const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1 + +export const WORK_GROUP_TOGGLE_HEIGHT = 36; // min-h-8 (32) + mb-1 (4) + +export function collapsedWorkLogHeight( + activities: ReadonlyArray, + baseFontSize: number, +): number { + const rows = visibleWorkLogActivities(activities); + if (rows.length === 0) { + return 0; + } + const onlyToolRows = rows.every((row) => row.toolLike); + const headerHeight = + scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING; + return ( + WORK_LOG_BOTTOM_MARGIN + + (onlyToolRows ? 0 : headerHeight) + + rows.length * WORK_ROW_HEIGHT + + (rows.length - 1) * WORK_ROW_GAP + ); +} + export function ThreadWorkLog(props: { readonly activities: ReadonlyArray; readonly copiedRowId: string | null; @@ -168,22 +217,30 @@ export function ThreadWorkLog(props: { readonly expandedRows: Readonly>; readonly iconSubtleColor: import("react-native").ColorValue; readonly onCopyRow: (rowId: string, value: string) => void; + readonly onToggleGroup: () => void; readonly onToggleRow: (rowId: string) => void; readonly workspaceRoot?: string | null; }) { const colorScheme = useColorScheme(); const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)"; - const rows = props.activities; + const rows = visibleWorkLogActivities(props.activities).map((activity) => ({ + ...activity, + detail: compactActivityDetail(activity.detail), + })); if (rows.length === 0) { return null; } + const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleRows = + hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows; + const hiddenCount = rows.length - visibleRows.length; const onlyToolRows = rows.every((row) => row.toolLike); const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount); return ( - + {!onlyToolRows ? ( work log @@ -191,16 +248,17 @@ export function ThreadWorkLog(props: { ) : null} - {rows.map((row) => { + {visibleRows.map((row) => { const expanded = props.expandedRows[row.id] ?? false; - const canExpand = row.fullDetail !== null; + const canExpand = row.canExpand; const detail = compactActivityDetail(row.detail); const displayText = detail ? `${row.summary} ${detail}` : row.summary; const textIsDestructive = row.icon === "alert" || row.icon === "warning"; return ( - ({ backgroundColor: pressed ? pressedBackground : "transparent", })} - className="rounded-md px-0.5 py-0" + className="rounded-md px-0.5 py-0.5" > @@ -287,7 +345,7 @@ export function ThreadWorkLog(props: { - {expanded && row.fullDetail ? ( + {expanded && canExpand ? ( ) : null} - + ); })} @@ -360,35 +418,33 @@ export function ThreadWorkGroupToggle(props: { const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount); return ( - + { - void Haptics.selectionAsync(); + triggerDisclosureFeedback(); props.onToggle(); }} style={({ pressed }) => ({ backgroundColor: pressed ? pressedBackground : "transparent", })} - className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0" + className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5" > - {props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`} + {props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`} diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 7a04562f18..98a6f92e44 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -7,12 +7,13 @@ import { MessageId, ProjectId, ProviderInstanceId, + RunId, ThreadId, - TurnId, } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; +import { makeThreadShellFixture } from "../../test-fixtures"; import { buildThreadListV2Items, buildThreadListV2ListItems, @@ -29,27 +30,10 @@ const environmentId = EnvironmentId.make("environment-1"); function makeThread( input: Partial & Pick, ): EnvironmentThreadShell { - return { + return makeThreadShellFixture({ environmentId, - projectId: ProjectId.make("project-1"), - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: "2026-06-01T00:00:00.000Z", - updatedAt: "2026-06-01T00:00:00.000Z", - archivedAt: null, - settledOverride: null, - settledAt: null, - session: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, ...input, - }; + }); } const NOW = "2026-06-02T00:00:00.000Z"; @@ -122,18 +106,16 @@ describe("resolveThreadListV2Enabled", () => { }); describe("resolveThreadListV2Status", () => { - it("prioritizes approval over a running session", () => { + it("prioritizes approval over a running runtime", () => { const thread = makeThread({ id: ThreadId.make("t"), title: "t", hasPendingApprovals: true, - session: { - threadId: ThreadId.make("t"), + runtime: { status: "running", + activeRunId: RunId.make("run-t"), providerName: "Codex", providerInstanceId: ProviderInstanceId.make("codex"), - runtimeMode: "full-access", - activeTurnId: null, lastError: null, updatedAt: NOW, }, @@ -688,10 +670,11 @@ describe("buildThreadListV2Items", () => { }); it("scopes the flat list to one project", () => { + const projectId = ProjectId.make("project-1"); const otherProjectId = ProjectId.make("project-2"); const { items } = buildThreadListV2Items({ threads: [ - makeThread({ id: ThreadId.make("included"), title: "Included" }), + makeThread({ id: ThreadId.make("included"), projectId, title: "Included" }), makeThread({ id: ThreadId.make("excluded"), projectId: otherProjectId, @@ -699,7 +682,7 @@ describe("buildThreadListV2Items", () => { }), ], environmentId: null, - projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }], + projectRefs: [{ environmentId, projectId }], searchQuery: "", now: NOW, }); @@ -709,19 +692,21 @@ describe("buildThreadListV2Items", () => { it("scopes the flat list to every environment member of a logical project", () => { const remoteEnvironmentId = EnvironmentId.make("environment-remote"); + const projectId = ProjectId.make("project-1"); const { items } = buildThreadListV2Items({ threads: [ - makeThread({ id: ThreadId.make("local"), title: "Local" }), + makeThread({ id: ThreadId.make("local"), projectId, title: "Local" }), makeThread({ environmentId: remoteEnvironmentId, id: ThreadId.make("remote"), + projectId, title: "Remote", }), ], environmentId: null, projectRefs: [ - { environmentId, projectId: ProjectId.make("project-1") }, - { environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") }, + { environmentId, projectId }, + { environmentId: remoteEnvironmentId, projectId }, ], searchQuery: "", now: NOW, @@ -744,9 +729,9 @@ describe("buildThreadListV2Items settled paging", () => { latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`, // A turn adopted the message (same requestedAt): without it the // thread reads as a queued turn start, which never settles. - latestTurn: { - turnId: TurnId.make(`turn-${index}`), - state: "completed", + latestRun: { + runId: RunId.make(`run-${index}`), + status: "completed", requestedAt: `2026-06-01T0${index}:00:00.000Z`, startedAt: `2026-06-01T0${index}:00:00.000Z`, completedAt: `2026-06-01T0${index}:10:00.000Z`, diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index b963c5ee61..6ab7df66a9 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -84,7 +84,7 @@ export function resolveThreadListV2SwipeActions(input: { export function resolveThreadListV2SnoozeGateExpiryMs( thread: Pick< EnvironmentThreadShell, - "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session" + "hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime" >, options: { readonly now: string }, ): number | null { @@ -143,7 +143,7 @@ export function threadHasUnseenCompletion( } export function resolveThreadListV2Status( - thread: Pick, + thread: Pick, ): ThreadListV2Status { if (thread.hasPendingApprovals) { return "approval"; @@ -151,10 +151,13 @@ export function resolveThreadListV2Status( if (thread.hasPendingUserInput) { return "input"; } - if (thread.session?.status === "running" || thread.session?.status === "starting") { + if ( + thread.runtime !== null && + ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status) + ) { return "working"; } - if (thread.session?.status === "error") { + if (thread.runtime?.status === "failed") { return "failed"; } return "ready"; diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 79222f0add..531b9bd7fa 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -1,15 +1,53 @@ import type { StatusTone } from "../../components/StatusPill"; -import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts"; -import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; export function threadSortValue(thread: EnvironmentThreadShell): number { const candidate = Date.parse(thread.updatedAt ?? thread.createdAt); return Number.isNaN(candidate) ? 0 : candidate; } -export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { - const status = thread.runtime?.status; - if (status === "running" || status === "waiting") { +export type ThreadStatusKind = + | "pending-approval" + | "awaiting-input" + | "working" + | "connecting" + | "error" + | "plan-ready"; + +export interface ThreadStatusPresentation extends StatusTone { + readonly kind: ThreadStatusKind; + /** Foreground color for the leading status icon. */ + readonly iconColor: string; + /** Background color for the leading status icon circle. */ + readonly iconBackground: string; + /** Whether the indicator represents in-flight activity. */ + readonly pulse: boolean; +} + +/** Neutral icon colors for threads with no actionable status. */ +export const THREAD_STATUS_NEUTRAL_ICON = { + iconColor: "#8e8e93", + iconBackground: "rgba(142,142,147,0.22)", +} as const; + +function isLatestRunSettled(thread: EnvironmentThreadShell): boolean { + if (!thread.latestRun?.startedAt) return false; + if (!thread.latestRun.completedAt) return false; + return !threadRuntimeIsActive(thread.runtime); +} + +/** + * Resolves the user-facing status of a thread, in priority order. Returns + * `null` for quiescent threads so rows stay free of "Idle"-style noise. + * Mirrors `resolveThreadStatusPill` in apps/web/src/components/Sidebar.logic.ts. + */ +export function resolveThreadStatus( + thread: EnvironmentThreadShell, +): ThreadStatusPresentation | null { + if (thread.hasPendingApprovals) { return { kind: "pending-approval", label: "Needs Approval", @@ -20,7 +58,8 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { pulse: false, }; } - if (status === "completed") { + + if (thread.hasPendingUserInput) { return { kind: "awaiting-input", label: "Awaiting Input", @@ -31,7 +70,10 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { pulse: false, }; } - if (status === "preparing" || status === "queued" || status === "starting") { + + const runtimeStatus = thread.runtime?.status; + + if (runtimeStatus === "running" || runtimeStatus === "waiting") { return { kind: "working", label: "Working", @@ -42,7 +84,8 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { pulse: true, }; } - if (status === "failed") { + + if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") { return { kind: "connecting", label: "Connecting", @@ -54,7 +97,7 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { }; } - if (thread.session?.status === "error" || thread.latestTurn?.state === "error") { + if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") { return { kind: "error", label: "Error", @@ -68,7 +111,7 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { const hasPlanReadyPrompt = thread.interactionMode === "plan" && - isLatestTurnSettled(thread.latestTurn, thread.session) && + isLatestRunSettled(thread) && thread.hasActionableProposedPlan; if (hasPlanReadyPrompt) { return { diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 184ee3c4d7..9d03dde59a 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -58,16 +58,15 @@ export function useCreateProjectThread() { const result = await startTurn({ environmentId: input.project.environmentId, - input: { - commandId: CommandId.make(metadata.commandId), - creationSource: "mobile", - threadId, - message: { - messageId: MessageId.make(metadata.messageId), - role: "user", - text: initialMessageText, - attachments: input.initialAttachments, - }, + input: buildProjectThreadStartTurnInput({ + projectId: input.project.id, + projectCwd: input.project.workspaceRoot, + threadId: metadata.threadId, + commandId: metadata.commandId, + messageId: metadata.messageId, + createdAt: metadata.createdAt, + text: initialMessageText, + attachments: input.initialAttachments, modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts index 85523175a2..310f181859 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -50,6 +50,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe const isWorktree = spec.workspaceMode === "worktree"; return { commandId: CommandId.make(spec.commandId), + creationSource: "mobile" as const, threadId: ThreadId.make(spec.threadId), message: { messageId: MessageId.make(spec.messageId), diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index bc88064969..c77480b8f7 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -147,7 +147,7 @@ describe("buildThreadFeed", () => { ]); const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0]; expect(activity?.projectedItem).toBe(rows[1]); - expect(activity?.fullDetail).toContain('"input": "vp check"'); + expect(activity?.getFullDetail()).toContain('"input": "vp check"'); }); it("retains inherited and synthetic rows with their original projected identity", () => { @@ -301,7 +301,7 @@ describe("buildThreadFeed", () => { ): ThreadFeedActivity => ({ id, createdAt, - turnId: null, + runId: null, summary: `Tool ${id}`, detail: null, canExpand: false, @@ -310,14 +310,16 @@ describe("buildThreadFeed", () => { icon: "command", logo: null, toolLike: true, + prominent: false, status, + projectedItem: projected(command(createdAt), 0), }); const feed: ThreadFeedEntry[] = [ { type: "activity-group", id: "work-group-1", createdAt: "2026-04-01T00:00:01.000Z", - turnId: null, + runId: null, activities: [ activity("activity-1", "2026-04-01T00:00:01.000Z"), activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"), @@ -363,7 +365,7 @@ describe("buildThreadFeed", () => { expect(activity?.summary).toBe("Read a T3 thread"); expect(activity?.logo).toBe("t3-code"); - expect(activity?.copyText.split("\n")[0]).toBe("Read a T3 thread"); + expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread"); }); }); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index d374107daf..29ee45798c 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -26,6 +26,8 @@ import * as DateTime from "effect/DateTime"; export type PendingApproval = ThreadPendingApproval; export type PendingUserInput = ThreadPendingUserInput; +const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; + export interface PendingUserInputDraftAnswer { readonly selectedOptionLabel?: string; readonly customAnswer?: string; @@ -137,6 +139,16 @@ export type ThreadFeedEntry = readonly runId: RunId | null; readonly activities: ReadonlyArray; } + | { + readonly type: "work-toggle"; + readonly id: string; + readonly createdAt: string; + readonly runId: RunId | null; + readonly groupId: string; + readonly hiddenCount: number; + readonly expanded: boolean; + readonly onlyToolActivities: boolean; + } | { readonly type: "run-fold"; readonly id: string; @@ -489,6 +501,18 @@ function capitalizePhrase(value: string): string { return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`; } +function memoizeValue(build: () => T): () => T { + let value: T; + let initialized = false; + return () => { + if (!initialized) { + value = build(); + initialized = true; + } + return value; + }; +} + function itemIsToolLike(item: OrchestrationV2TurnItem): boolean { return ( item.type === "reasoning" || @@ -661,15 +685,25 @@ function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivi const toolPresentation = itemToolPresentation(item); const summary = itemSummary(item, toolPresentation); const detail = itemPreview(item); - const fullDetail = JSON.stringify( - { - visibility: row.visibility, - sourceThreadId: row.sourceThreadId, - sourceItemId: row.sourceItemId, - item, - }, - null, - 2, + const getFullDetail = memoizeValue(() => + JSON.stringify( + { + visibility: row.visibility, + sourceThreadId: row.sourceThreadId, + sourceItemId: row.sourceItemId, + item, + }, + null, + 2, + ), + ); + const getCopyText = memoizeValue(() => + [summary, detail, getFullDetail()] + .filter( + (value, index, values): value is string => + Boolean(value) && values.indexOf(value) === index, + ) + .join("\n"), ); return { id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`, @@ -677,15 +711,11 @@ function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivi runId: item.runId, summary, detail, - fullDetail, + canExpand: true, + getFullDetail, + getCopyText, icon: itemIcon(item), logo: toolPresentation?.logo ?? null, - copyText: [summary, detail, fullDetail] - .filter( - (value, index, values): value is string => - Boolean(value) && values.indexOf(value) === index, - ) - .join("\n"), toolLike: itemIsToolLike(item), prominent: itemIsProminent(item), status: itemStatus(item), @@ -703,6 +733,13 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean { function groupAdjacentActivities(entries: ReadonlyArray): ThreadFeedEntry[] { const grouped: ThreadFeedEntry[] = []; + // Mutable backing array for the trailing group so appending an activity is + // O(1) instead of re-copying the group (which made this loop quadratic on + // long tool runs). The array is only mutated while it is the trailing group. + let openGroupActivities: ThreadFeedActivity[] | null = null; + let openGroupRunId: string | null = null; + let openGroupHasProminent = false; + for (const entry of entries) { if (isEmptyMessage(entry)) continue; if (entry.type !== "activity") { @@ -710,25 +747,26 @@ function groupAdjacentActivities(entries: ReadonlyArray): Th openGroupActivities = null; continue; } - const previous = grouped.at(-1); + if ( - previous?.type === "activity-group" && - previous.runId === entry.runId && + openGroupActivities !== null && + openGroupRunId === entry.runId && !entry.activity.prominent && - !previous.activities.some((activity) => activity.prominent) + !openGroupHasProminent ) { - grouped[grouped.length - 1] = { - ...previous, - activities: [...previous.activities, entry.activity], - }; + openGroupActivities.push(entry.activity); continue; } + + openGroupActivities = [entry.activity]; + openGroupRunId = entry.runId; + openGroupHasProminent = entry.activity.prominent === true; grouped.push({ type: "activity-group", id: entry.id, createdAt: entry.createdAt, runId: entry.runId, - activities: [entry.activity], + activities: openGroupActivities, }); } return grouped; @@ -870,8 +908,13 @@ export function deriveThreadFeedPresentation( feed: ReadonlyArray, latestRun: ThreadFeedLatestRun | null, expandedRunIds: ReadonlySet, + expandedWorkGroupIds: ReadonlySet = new Set(), + activeWorkStartedAt: string | null = null, ): ThreadFeedEntry[] { - const sourceFeed = feed.filter((entry) => entry.type !== "run-fold"); + const sourceFeed = feed.filter( + (entry) => + entry.type !== "run-fold" && entry.type !== "work-toggle" && entry.type !== "working", + ); const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun); const collapsedEntryIds = new Set(); for (const fold of foldsByAnchorId.values()) { @@ -892,7 +935,9 @@ export function deriveThreadFeedPresentation( expanded: expandedRunIds.has(fold.runId), }); } - if (!collapsedEntryIds.has(entry.id)) result.push(entry); + if (!collapsedEntryIds.has(entry.id)) { + appendPresentedFeedEntry(result, entry, expandedWorkGroupIds); + } } if (activeWorkStartedAt !== null) { result.push({ @@ -904,6 +949,55 @@ export function deriveThreadFeedPresentation( return result; } +function appendPresentedFeedEntry( + result: ThreadFeedEntry[], + entry: Exclude, + expandedWorkGroupIds: ReadonlySet, +): void { + if (entry.type !== "activity-group") { + result.push(entry); + return; + } + + const activities = entry.activities.filter( + (activity) => !(activity.toolLike && activity.status === "neutral"), + ); + if (activities.length === 0) { + return; + } + if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) { + result.push({ + ...entry, + activities, + }); + return; + } + + const groupId = entry.id; + const expanded = expandedWorkGroupIds.has(groupId); + const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES); + + for (const activity of visibleActivities) { + result.push({ + type: "activity-group", + id: activity.id, + createdAt: activity.createdAt, + runId: activity.runId, + activities: [activity], + }); + } + result.push({ + type: "work-toggle", + id: `work-toggle:${groupId}`, + createdAt: entry.createdAt, + runId: entry.runId, + groupId, + hiddenCount, + expanded, + onlyToolActivities: activities.every((activity) => activity.toolLike), + }); +} export function setPendingUserInputCustomAnswer( draft: PendingUserInputDraftAnswer | undefined, customAnswer: string, diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index 65478d9a93..8aa7151c93 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -1,4 +1,12 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts"; +import { + createThreadSearchResultsAtomFamily, + makeThreadSearchKey, + type EnvironmentThreadSearchMatch, +} from "@t3tools/client-runtime/state/thread-search"; +import { useAtomValue } from "@effect/atom-react"; +import * as Option from "effect/Option"; +import { Atom } from "effect/unstable/reactivity"; import { useEffect, useMemo, useState } from "react"; import { orchestrationEnvironment } from "./orchestration"; @@ -51,6 +59,31 @@ function useDebouncedValue(value: A, delayMs: number): A { return debounced; } +export function useThreadSearch( + environmentIds: ReadonlyArray, + query: string, +): { + readonly matches: ReadonlyArray; + readonly isPending: boolean; +} { + const normalizedQuery = query.trim(); + const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS); + const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2; + const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null; + const searchKey = useMemo( + () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)), + [environmentIds, settledQuery], + ); + const result = useAtomValue( + searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey), + ); + const isDebouncing = canSearch && normalizedQuery !== debouncedQuery; + return { + matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches, + isPending: canSearch && (isDebouncing || result.isLoading), + }; +} + export function useBranches(input: { readonly environmentId: EnvironmentId | null; readonly cwd: string | null; diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index 3e7354e12d..d15646a24f 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -10,7 +10,6 @@ import { scopedRequestKey } from "../lib/scopedEntities"; import { buildPendingUserInputAnswers, setPendingUserInputCustomAnswer, - sortThreadActivities, type PendingUserInputDraftAnswer, } from "../lib/threadActivity"; import { appAtomRegistry } from "./atom-registry"; diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 656cbdcae4..4b199fbb6f 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -196,8 +196,8 @@ export function useThreadComposerState() { setPendingConnectionError( error instanceof Error ? error.message : "Failed to save the queued message.", ); - return null; - } + }); + return messageId; }, [selectedThreadShell]); const onChangeDraftMessage = useCallback( diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index c49579c3a1..4936731101 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { threadRuntimeIsActive, + type EnvironmentProject, type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; @@ -374,8 +375,7 @@ export function useThreadOutboxDrain(): void { appAtomRegistry.get(environmentThreadShells.threadShellsAtom), nextQueuedMessage, ); - const freshThreadBusy = - freshThread?.session?.status === "running" || freshThread?.session?.status === "starting"; + const freshThreadBusy = threadRuntimeIsActive(freshThread?.runtime); if (deliveryAction === "send" && creation === undefined && freshThreadBusy) { return true; } diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts index c1fa82b3c3..890c0f3008 100644 --- a/apps/mobile/src/state/use-thread-selection.ts +++ b/apps/mobile/src/state/use-thread-selection.ts @@ -2,8 +2,9 @@ import { useRoute, type RouteProp } from "@react-navigation/native"; import { useMemo, useRef } from "react"; import { EnvironmentId, - type OrchestrationThread, ThreadId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, type ScopedProjectRef, type ScopedThreadRef, } from "@t3tools/contracts"; @@ -36,9 +37,11 @@ function firstRouteParam(value: string | string[] | undefined): string | null { return value ?? null; } -function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null { - for (let index = thread.messages.length - 1; index >= 0; index -= 1) { - const message = thread.messages[index]; +function latestUserMessageAt( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadShell["latestUserMessageAt"] { + for (let index = projection.messages.length - 1; index >= 0; index -= 1) { + const message = projection.messages[index]; if (message?.role === "user") { return message.createdAt; } @@ -47,9 +50,14 @@ function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread[" return null; } +/** + * Builds an optimistic thread shell from the detail projection for the window + * where the shell list has not materialized the thread yet (e.g. a thread that + * was just created from this device). + */ function threadDetailToShell( environmentId: EnvironmentId, - thread: OrchestrationThread, + projection: OrchestrationV2ThreadProjection, ): EnvironmentThreadShell { const thread = projection.thread; const latestRun = deriveLatestThreadRun(projection); @@ -60,6 +68,7 @@ function threadDetailToShell( id: thread.id, projectId: thread.projectId, title: thread.title, + providerInstanceId: thread.providerInstanceId, modelSelection: thread.modelSelection, runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode, @@ -89,12 +98,8 @@ function threadDetailToShell( settledAt: thread.settledAt, snoozedUntil: thread.snoozedUntil ?? null, snoozedAt: thread.snoozedAt ?? null, - session: thread.session, - latestUserMessageAt: latestUserMessageAt(thread), - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - }; + deletedAt: thread.deletedAt, + }); } function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) { diff --git a/apps/mobile/src/test-fixtures.ts b/apps/mobile/src/test-fixtures.ts index 10aab98b40..cc5128d83f 100644 --- a/apps/mobile/src/test-fixtures.ts +++ b/apps/mobile/src/test-fixtures.ts @@ -46,6 +46,8 @@ export function makeRawThreadShell( createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, deletedAt: null, ...input, }; diff --git a/apps/server/package.json b/apps/server/package.json index ad186321a2..4613053aec 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -16,8 +16,6 @@ "type": "module", "scripts": { "dev": "node --watch src/bin.ts", - "build": "node scripts/cli.ts build", - "build:bundle": "tsdown", "record:codex-replay": "bun scripts/record-codex-app-server-replay-fixture.ts", "record:claude-replay": "bun scripts/record-claude-agent-sdk-replay-fixture.ts", "record:cursor-replay": "node --env-file-if-exists=../../.env --experimental-strip-types scripts/record-cursor-agent-sdk-replay-fixture.ts", @@ -52,9 +50,7 @@ "@types/node": "catalog:", "effect-acp": "workspace:*", "effect-codex-app-server": "workspace:*", - "tsdown": "catalog:", - "typescript": "catalog:", - "vitest": "catalog:" + "vite-plus": "catalog:" }, "engines": { "node": "^22.16 || ^23.11 || >=24.10" diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 3906ec0cec..f15dc01975 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -83,18 +83,30 @@ let currentReasoning = "medium"; let currentContext = "272k"; let currentFast = false; let authenticated = !requiresAuthentication; +let promptCount = 0; +let overlappingFirstPromptId: string | undefined; const cancelledSessions = new Set(); +function promptIdFromRequestMeta( + request: Pick, +): string | undefined { + const meta = request._meta; + if (meta === null || typeof meta !== "object") { + return undefined; + } + const promptId = meta.promptId ?? meta.requestId; + return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined; +} + function logExit(reason: string): void { if (!exitLogPath) { return; } - appendFileSync(exitLogPath, `${reason}\n`, "utf8"); + NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8"); } -function logResidualCallbackResponse(kind: string): void { - if (!residualCallbackResponseLogPath) return; - NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8"); +function writeJsonRpcNotification(method: string, params: unknown): void { + process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`); } function logResidualCallbackResponse(kind: string): void { diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 2aa057ee0c..9512c3cb96 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -6,7 +6,7 @@ import { AuthRelayWriteScope, AuthReviewWriteScope, AuthTerminalOperateScope, - ORCHESTRATION_WS_METHODS, + ORCHESTRATION_V2_WS_METHODS, type AuthEnvironmentScope, WS_METHODS, WsRpcGroup, @@ -21,6 +21,7 @@ type WsRpcMethod = RpcGroup.Rpcs["_tag"]; * runtime failure. */ export const RPC_REQUIRED_SCOPES = { +<<<<<<< HEAD [ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope, [ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope, [ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope, @@ -29,6 +30,19 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope, [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope, [ORCHESTRATION_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope, +======= + [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope, + [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope, + [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope, +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) [WS_METHODS.serverProbe]: AuthOrchestrationReadScope, [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope, [WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope, @@ -49,6 +63,12 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, [WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope, [WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope, + [WS_METHODS.scheduledTasksList]: AuthOrchestrationReadScope, + [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope, + [WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope, + [WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope, + [WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope, + [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope, [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope, [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope, @@ -62,6 +82,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope, [WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope, [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope, + [WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope, [WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope, [WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope, [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope, diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 4dd76be1c2..def63b61fa 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -356,6 +356,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServePort: 443, }); assert.equal(join(baseDir, "userdata"), resolved.stateDir); + assert.equal(resolved.desktopTelemetryFd, 4); + assert.equal(resolved.desktopTelemetryControlFd, 5); }), ); diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 82e8d420db..a027e7c232 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -20,6 +20,7 @@ import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.t import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { ProjectLiveServerDeclaredResponseError, @@ -53,6 +54,7 @@ const makeConfig = (baseDir: string) => ...derivedPaths, staticDir: undefined, devUrl: undefined, + devAllowedOrigins: [], noBrowser: true, startupPresentation: "browser", desktopBootstrapToken: undefined, @@ -70,6 +72,7 @@ const readProjects = (baseDir: string) => Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(RepositoryIdentityResolver.layer), Layer.provideMerge(ProjectFaviconResolver.layer), + Layer.provideMerge(T3ProjectFileLoader.layer), Layer.provideMerge(WorkspacePaths.layer), Layer.provideMerge(SqlitePersistenceLayerLive), Layer.provideMerge(NodeServices.layer), diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index b9a3a3511e..611159b55f 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -30,6 +30,7 @@ import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.t import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts"; import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; import { clearPersistedServerRuntimeState, @@ -198,7 +199,12 @@ const projectCommandUuid = Crypto.Crypto.pipe( const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe( Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(RepositoryIdentityResolver.layer), - Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))), + Layer.provideMerge( + ProjectFaviconResolver.layer.pipe( + Layer.provide(WorkspacePaths.layer), + Layer.provide(T3ProjectFileLoader.layer), + ), + ), Layer.provideMerge(WorkspacePaths.layer), Layer.provideMerge(SqlitePersistenceLayerLive), ); diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index dd2637491f..695c7b76f6 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1214,6 +1214,37 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("status hides merged PRs on the default branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + // @effect-diagnostics-next-line preferSchemaOverJson:off + JSON.stringify([ + { + number: 23, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/23", + baseRefName: "feature/status-default-branch-target", + headRefName: "main", + state: "MERGED", + mergedAt: "2026-01-30T10:00:00Z", + updatedAt: "2026-01-30T10:00:00Z", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.refName).toBe("main"); + expect(status.pr).toBeNull(); + }), + ); + it.effect("status prefers open PR when merged PR has newer updatedAt", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1287,6 +1318,230 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("status keeps the last known PR when a later lookup fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky"]); + + const existingPr = { + number: 214, + title: "Sticky PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/214", + baseRefName: "main", + headRefName: "feature/pr-sticky", + }; + const { manager } = yield* makeManager({ + ghScenario: { + // @effect-diagnostics-next-line preferSchemaOverJson:off + prListSequence: [JSON.stringify([existingPr])], + failWith: new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: repoDir, + cause: new Error("rate limited"), + }), + failAfterCalls: 1, + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + expect(first.pr?.number).toBe(214); + + // An explicit invalidation (user refresh, git action) bypasses the PR + // cache and forces a live lookup — which now fails. The badge must keep + // the last known PR instead of blanking out. + yield* manager.invalidateStatus(repoDir); + const second = yield* manager.status({ cwd: repoDir }); + expect(second.pr?.number).toBe(214); + }), + ); + + it.effect( + "status does not reuse a stale PR after the branch is retargeted to a different upstream", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]); + + const originRemote = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originRemote]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]); + + const existingPr = { + number: 214, + title: "Sticky PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/214", + baseRefName: "main", + headRefName: "feature/pr-retarget", + }; + const { manager } = yield* makeManager({ + ghScenario: { + // @effect-diagnostics-next-line preferSchemaOverJson:off + prListSequence: [JSON.stringify([existingPr])], + failWith: new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: repoDir, + cause: new Error("rate limited"), + }), + failAfterCalls: 1, + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + expect(first.pr?.number).toBe(214); + + // Retarget the branch to a different remote/upstream (e.g. the PR was + // reopened against a fork). The previously cached PR belonged to the + // old upstream and must not be shown against the new one. + const forkRemote = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]); + yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]); + yield* runGit(repoDir, [ + "branch", + "--set-upstream-to=fork/feature/pr-retarget", + "feature/pr-retarget", + ]); + + yield* manager.invalidateStatus(repoDir); + const second = yield* manager.status({ cwd: repoDir }); + expect(second.pr).toBeNull(); + }), + ); + + it.effect("status keeps the last known PR when the branch gains its first upstream", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + + const existingPr = { + number: 215, + title: "Sticky first-push PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/215", + baseRefName: "main", + headRefName: "feature/pr-sticky-first-push", + }; + const { manager } = yield* makeManager({ + ghScenario: { + // @effect-diagnostics-next-line preferSchemaOverJson:off + prListSequence: [JSON.stringify([existingPr])], + failWith: new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: repoDir, + cause: new Error("rate limited"), + }), + failAfterCalls: 1, + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + expect(first.pr?.number).toBe(215); + + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]); + yield* manager.invalidateStatus(repoDir); + + const second = yield* manager.status({ cwd: repoDir }); + expect(second.pr?.number).toBe(215); + }), + ); + + it.effect("status drops the last known PR when the tracked remote is repointed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]); + const originalRemoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]); + + const existingPr = { + number: 216, + title: "Old remote PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/216", + baseRefName: "main", + headRefName: "feature/pr-repointed", + }; + const { manager } = yield* makeManager({ + ghScenario: { + // @effect-diagnostics-next-line preferSchemaOverJson:off + prListSequence: [JSON.stringify([existingPr])], + failWith: new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: repoDir, + cause: new Error("rate limited"), + }), + failAfterCalls: 1, + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + expect(first.pr?.number).toBe(216); + + const replacementRemoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]); + yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]); + yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]); + yield* manager.invalidateStatus(repoDir); + + const second = yield* manager.status({ cwd: repoDir }); + expect(second.pr).toBeNull(); + }), + ); + + it.effect("status keeps the last known PR when the current remote URL can't be resolved", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-config-hiccup"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-config-hiccup"]); + + const existingPr = { + number: 217, + title: "Config hiccup PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/217", + baseRefName: "main", + headRefName: "feature/pr-config-hiccup", + }; + const { manager } = yield* makeManager({ + ghScenario: { + // @effect-diagnostics-next-line preferSchemaOverJson:off + prListSequence: [JSON.stringify([existingPr])], + failWith: new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: repoDir, + cause: new Error("rate limited"), + }), + failAfterCalls: 1, + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + expect(first.pr?.number).toBe(217); + + // `remote.origin.url` reads go through readConfigValueNullable, which + // maps ANY failed read (a real "no remote configured" state or a + // transient git-config hiccup) to null the same way. Unsetting the + // key here reproduces that ambiguity without touching branch + // tracking (refs/remotes/origin/* and branch..remote are + // untouched) — the remote identity has not actually changed, so the + // sticky PR must survive even though the current lookup can no + // longer resolve a remote URL to compare against. + yield* runGit(repoDir, ["config", "--unset", "remote.origin.url"]); + yield* manager.invalidateStatus(repoDir); + + const second = yield* manager.status({ cwd: repoDir }); + expect(second.pr?.number).toBe(217); + }), + ); + it.effect("creates a commit when working tree is dirty", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1337,6 +1592,118 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("preserves custom style when instructions are empty", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n"); + let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined; + + const { manager } = yield* makeManager({ + serverSettings: { + sourceControlWritingStyle: { + mode: "custom" as const, + customInstructions: "", + }, + }, + textGeneration: { + generateCommitMessage: (input) => { + generatedPolicy = input.policy; + return Effect.succeed({ subject: "Preserve custom style", body: "" }); + }, + }, + }); + yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + }); + + expect(generatedPolicy).toEqual({ + kind: "custom", + inferRepositoryConventions: false, + }); + }), + ); + + it.effect("falls back when the dedicated source control writer is unavailable", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n"); + const missingInstanceId = ProviderInstanceId.make("missing_writer"); + let generatedModelSelection: + | TextGeneration.CommitMessageGenerationInput["modelSelection"] + | undefined; + + const { manager } = yield* makeManager({ + serverSettings: { + providerInstances: { + [missingInstanceId]: { + driver: ProviderDriverKind.make("missing-driver"), + config: {}, + }, + }, + sourceControlWriterModelSelection: { + instanceId: missingInstanceId, + model: "missing-model", + }, + }, + textGeneration: { + generateCommitMessage: (input) => { + generatedModelSelection = input.modelSelection; + return Effect.succeed({ subject: "Use the available writer", body: "" }); + }, + }, + }); + + yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + }); + + expect(generatedModelSelection).toEqual(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection); + }), + ); + + it.effect("preserves repository conventions style when recent history is empty", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* runGit(repoDir, ["init", "--initial-branch=main"]); + yield* runGit(repoDir, ["config", "user.email", "test@example.com"]); + yield* runGit(repoDir, ["config", "user.name", "Test User"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\n"); + yield* runGit(repoDir, ["add", "README.md"]); + let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined; + + const { manager } = yield* makeManager({ + serverSettings: { + sourceControlWritingStyle: { + mode: "repo_conventions" as const, + }, + }, + textGeneration: { + generateCommitMessage: (input) => { + generatedPolicy = input.policy; + return Effect.succeed({ subject: "Create initial commit", body: "" }); + }, + }, + }); + yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + }); + + expect(generatedPolicy).toEqual({ + kind: "repo_conventions", + commitInstructions: + "Follow the repository's established commit message style when examples are available.", + changeRequestInstructions: + "Follow the repository's established change request title and body style when examples are available.", + inferRepositoryConventions: true, + }); + }), + ); + it.effect("uses custom commit message when provided", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1678,6 +2045,41 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("pushes existing commits without committing dirty worktree changes", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + NodeFS.writeFileSync(NodePath.join(repoDir, "push-dirty.txt"), "push dirty\n"); + yield* runGit(repoDir, ["add", "push-dirty.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]); + NodeFS.mkdirSync(NodePath.join(repoDir, ".vercel")); + NodeFS.writeFileSync(NodePath.join(repoDir, ".vercel", "project.json"), "{}\n"); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "push", + }); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("pushed"); + expect(result.pr.status).toBe("skipped_not_requested"); + expect( + yield* runGit(repoDir, ["status", "--porcelain"]).pipe( + Effect.map((output) => output.stdout.trim()), + ), + ).toContain("?? .vercel/"); + expect( + yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe( + Effect.map((output) => output.stdout.trim()), + ), + ).toBe("Push dirty branch"); + }), + ); + it.effect("create_pr pushes a clean branch before creating the PR when needed", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1725,6 +2127,50 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("create_pr falls back to main when source control provider detection fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "provider-fallback.txt"), "fallback\n"); + yield* runGit(repoDir, ["add", "provider-fallback.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + "[]", + // @effect-diagnostics-next-line preferSchemaOverJson:off + JSON.stringify([ + { + number: 404, + title: "Provider fallback", + url: "https://github.com/pingdotgg/codething-mvp/pull/404", + baseRefName: "main", + headRefName: "feature/provider-fallback", + }, + ]), + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "create_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(404); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/provider-fallback"), + ), + ).toBe(true); + }), + ); + it.effect("returns existing PR metadata for commit/push/pr action", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -2074,6 +2520,123 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { 12_000, ); + it.effect( + "does not reuse a cross-repo PR when GitHub omits head identity metadata", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:octocat/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequenceByHeadSelector: { + "octocat:statemachine": [ + `[{"number":41,"title":"Ambiguous fork PR","url":"https://github.com/pingdotgg/codething-mvp/pull/41","baseRefName":"main","headRefName":"statemachine","state":"OPEN"}]`, + `[{"number":142,"title":"Add stacked git actions","url":"https://github.com/pingdotgg/codething-mvp/pull/142","baseRefName":"main","headRefName":"statemachine","state":"OPEN","isCrossRepository":true,"headRepository":{"nameWithOwner":"octocat/codething-mvp"},"headRepositoryOwner":{"login":"octocat"}}]`, + ], + "fork-seed:statemachine": ["[]"], + statemachine: ["[]"], + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(142); + expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(true); + }), + 20_000, + ); + + it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () => + Effect.sync(() => { + const headContext = { + headBranch: "statemachine", + headRepositoryNameWithOwner: "pingdotgg/codething-mvp", + headRepositoryOwnerLogin: "pingdotgg", + isCrossRepository: true, + }; + + expect( + GitManager.matchesBranchHeadContext( + { + number: 41, + title: "Same-repo PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/41", + baseRefName: "main", + headRefName: "statemachine", + state: "open", + updatedAt: Option.none(), + isCrossRepository: false, + headRepositoryNameWithOwner: "pingdotgg/codething-mvp", + headRepositoryOwnerLogin: "pingdotgg", + }, + headContext, + ), + ).toBe(false); + + expect( + GitManager.matchesBranchHeadContext( + { + number: 142, + title: "Fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/142", + baseRefName: "main", + headRefName: "statemachine", + state: "open", + updatedAt: Option.none(), + isCrossRepository: true, + headRepositoryNameWithOwner: "pingdotgg/codething-mvp", + headRepositoryOwnerLogin: "pingdotgg", + }, + headContext, + ), + ).toBe(true); + }), + ); + + it.effect("accepts fork PR metadata when origin is the fork checkout remote", () => + Effect.sync(() => { + const headContext = { + headBranch: "t3code/git-audit-stability", + headRepositoryNameWithOwner: "justsomelegs/t3code", + headRepositoryOwnerLogin: "justsomelegs", + isCrossRepository: false, + }; + + expect( + GitManager.matchesBranchHeadContext( + { + number: 2284, + title: "Improve branch mismatch warnings", + url: "https://github.com/pingdotgg/t3code/pull/2284", + baseRefName: "main", + headRefName: "t3code/git-audit-stability", + state: "open", + updatedAt: Option.none(), + isCrossRepository: true, + headRepositoryNameWithOwner: "justsomelegs/t3code", + headRepositoryOwnerLogin: "justsomelegs", + }, + headContext, + ), + ).toBe(true); + }), + ); + it.effect("creates PR when one does not already exist", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -2149,6 +2712,62 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("generates PR content against the remote base when the local base is stale", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(remoteDir, ["symbolic-ref", "HEAD", "refs/heads/main"]); + + const peerDir = yield* makeTempDir("t3code-git-peer-"); + yield* runGit(peerDir, ["clone", remoteDir, "."]); + yield* runGit(peerDir, ["config", "user.email", "peer@example.com"]); + yield* runGit(peerDir, ["config", "user.name", "Peer User"]); + NodeFS.writeFileSync(NodePath.join(peerDir, "remote.txt"), "remote\n"); + yield* runGit(peerDir, ["add", "remote.txt"]); + yield* runGit(peerDir, ["commit", "-m", "Remote base commit"]); + yield* runGit(peerDir, ["push", "origin", "main"]); + + yield* runGit(repoDir, ["fetch", "origin"]); + yield* runGit(repoDir, [ + "checkout", + "--no-track", + "-b", + "feature/remote-base", + "origin/main", + ]); + NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n"); + yield* runGit(repoDir, ["add", "feature.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/remote-base"]); + yield* runGit(repoDir, ["config", "branch.feature/remote-base.gh-merge-base", "main"]); + + let generatedCommitSummary = ""; + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: ["[]", "[]"], + }, + textGeneration: { + generatePrContent: (input) => { + generatedCommitSummary = input.commitSummary; + return Effect.succeed({ title: "Feature PR", body: "Feature body" }); + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "create_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(generatedCommitSummary).toContain("Feature commit"); + expect(generatedCommitSummary).not.toContain("Remote base commit"); + }), + ); + it.effect( "creates a new PR instead of reusing an unrelated fork PR with the same head branch", () => @@ -2158,7 +2777,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]); const remoteDir = yield* createBareRemote(); yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); - fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + NodeFS.writeFileSync(NodePath.join(repoDir, "changes.txt"), "change\n"); yield* runGit(repoDir, ["add", "changes.txt"]); yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]); @@ -2166,6 +2785,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { const { manager, ghCalls } = yield* makeManager({ ghScenario: { prListSequence: [ + // @effect-diagnostics-next-line preferSchemaOverJson:off JSON.stringify([ { number: 1661, @@ -2183,6 +2803,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }, }, ]), + // @effect-diagnostics-next-line preferSchemaOverJson:off JSON.stringify([ { number: 188, @@ -2441,6 +3062,113 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect( + "restores same-repository upstream tracking after local PR checkout without a remote ref", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "upstream.txt"), "upstream\n"); + yield* runGit(repoDir, ["add", "upstream.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]); + yield* runGit(repoDir, [ + "update-ref", + "-d", + "refs/remotes/origin/feature/pr-local-upstream", + ]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 65, + title: "Local upstream PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/65", + baseRefName: "main", + headRefName: "feature/pr-local-upstream", + state: "open", + isCrossRepository: false, + headRepositoryNameWithOwner: "pingdotgg/codething-mvp", + headRepositoryOwnerLogin: "pingdotgg", + }, + repositoryCloneUrls: { + "pingdotgg/codething-mvp": { + url: remoteDir, + sshUrl: remoteDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "65", + mode: "local", + }); + + expect(result.worktreePath).toBeNull(); + expect(result.branch).toBe("feature/pr-local-upstream"); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("origin/feature/pr-local-upstream"); + }), + ); + + it.effect( + "restores same-repository upstream tracking when provider omits head repository metadata", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "no-head-repo.txt"), "upstream\n"); + yield* runGit(repoDir, ["add", "no-head-repo.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]); + yield* runGit(repoDir, [ + "update-ref", + "-d", + "refs/remotes/origin/feature/pr-local-no-head-repo", + ]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 66, + title: "Local upstream PR without repo metadata", + url: "https://github.com/pingdotgg/codething-mvp/pull/66", + baseRefName: "main", + headRefName: "feature/pr-local-no-head-repo", + state: "open", + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "66", + mode: "local", + }); + + expect(result.worktreePath).toBeNull(); + expect(result.branch).toBe("feature/pr-local-no-head-repo"); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("origin/feature/pr-local-no-head-repo"); + }), + ); + it.effect("prepares pull request threads in worktree mode on the PR head branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -2894,7 +3622,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { yield* runGit(repoDir, ["push", "-u", "origin", "main"]); yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]); - fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n"); + NodeFS.writeFileSync(NodePath.join(repoDir, "fork-main-second.txt"), "fork main second\n"); yield* runGit(repoDir, ["add", "fork-main-second.txt"]); yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]); yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts deleted file mode 100644 index 24d7ae3140..0000000000 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ /dev/null @@ -1,411 +0,0 @@ -import { randomUUID } from "node:crypto"; - -import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; - -import { CodexModelSelection } from "@t3tools/contracts"; -import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; - -import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerConfig } from "../../config.ts"; -import { TextGenerationError } from "@t3tools/contracts"; -import { - type BranchNameGenerationInput, - type ThreadTitleGenerationResult, - type TextGenerationShape, - TextGeneration, -} from "../Services/TextGeneration.ts"; -import { - buildBranchNamePrompt, - buildCommitMessagePrompt, - buildPrContentPrompt, - buildThreadTitlePrompt, -} from "../Prompts.ts"; -import { - normalizeCliError, - sanitizeCommitSubject, - sanitizePrTitle, - sanitizeThreadTitle, - toJsonSchemaObject, -} from "../Utils.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; - -const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; -const CODEX_TIMEOUT_MS = 180_000; -const makeCodexTextGeneration = Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const serverConfig = yield* Effect.service(ServerConfig); - const serverSettingsService = yield* Effect.service(ServerSettingsService); - - type MaterializedImageAttachments = { - readonly imagePaths: ReadonlyArray; - }; - - const readStreamAsString = ( - operation: string, - stream: Stream.Stream, - ): Effect.Effect => - stream.pipe( - Stream.decodeText(), - Stream.runFold( - () => "", - (acc, chunk) => acc + chunk, - ), - Effect.mapError((cause) => - normalizeCliError("codex", operation, cause, "Failed to collect process output"), - ), - ); - - const writeTempFile = ( - operation: string, - prefix: string, - content: string, - ): Effect.Effect => { - return fileSystem - .makeTempFileScoped({ - prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`, - }) - .pipe( - Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)), - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: `Failed to write temp file`, - cause, - }), - ), - ); - }; - - const safeUnlink = (filePath: string): Effect.Effect => - fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void)); - - const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* ( - _operation: - | "generateCommitMessage" - | "generatePrContent" - | "generateBranchName" - | "generateThreadTitle", - attachments: BranchNameGenerationInput["attachments"], - ): Effect.fn.Return { - if (!attachments || attachments.length === 0) { - return { imagePaths: [] }; - } - - const imagePaths: string[] = []; - for (const attachment of attachments) { - if (attachment.type !== "image") { - continue; - } - - const resolvedPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!resolvedPath || !path.isAbsolute(resolvedPath)) { - continue; - } - const fileInfo = yield* fileSystem - .stat(resolvedPath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - continue; - } - imagePaths.push(resolvedPath); - } - return { imagePaths }; - }); - - const runCodexJson = Effect.fn("runCodexJson")(function* ({ - operation, - cwd, - prompt, - outputSchemaJson, - imagePaths = [], - cleanupPaths = [], - modelSelection, - }: { - operation: - | "generateCommitMessage" - | "generatePrContent" - | "generateBranchName" - | "generateThreadTitle"; - cwd: string; - prompt: string; - outputSchemaJson: S; - imagePaths?: ReadonlyArray; - cleanupPaths?: ReadonlyArray; - modelSelection: CodexModelSelection; - }): Effect.fn.Return { - const schemaPath = yield* writeTempFile( - operation, - "codex-schema", - JSON.stringify(toJsonSchemaObject(outputSchemaJson)), - ); - const outputPath = yield* writeTempFile(operation, "codex-output", ""); - - const codexSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.codex, - ).pipe(Effect.catch(() => Effect.undefined)); - - const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { - const reasoningEffort = - modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; - const command = ChildProcess.make( - codexSettings?.binaryPath || "codex", - [ - "exec", - "--ephemeral", - "--skip-git-repo-check", - "-s", - "read-only", - "--model", - modelSelection.model, - "--config", - `model_reasoning_effort="${reasoningEffort}"`, - ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []), - "--output-schema", - schemaPath, - "--output-last-message", - outputPath, - ...imagePaths.flatMap((imagePath) => ["--image", imagePath]), - "-", - ], - { - env: { - ...process.env, - ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), - }, - cwd, - shell: process.platform === "win32", - stdin: { - stream: Stream.encodeText(Stream.make(prompt)), - }, - }, - ); - - const child = yield* commandSpawner - .spawn(command) - .pipe( - Effect.mapError((cause) => - normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"), - ), - ); - - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - readStreamAsString(operation, child.stdout), - readStreamAsString(operation, child.stderr), - child.exitCode.pipe( - Effect.mapError((cause) => - normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"), - ), - ), - ], - { concurrency: "unbounded" }, - ); - - if (exitCode !== 0) { - const stderrDetail = stderr.trim(); - const stdoutDetail = stdout.trim(); - const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; - return yield* new TextGenerationError({ - operation, - detail: - detail.length > 0 - ? `Codex CLI command failed: ${detail}` - : `Codex CLI command failed with code ${exitCode}.`, - }); - } - }); - - const cleanup = Effect.all( - [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)), - { - concurrency: "unbounded", - }, - ).pipe(Effect.asVoid); - - return yield* Effect.gen(function* () { - yield* runCodexCommand().pipe( - Effect.scoped, - Effect.timeoutOption(CODEX_TIMEOUT_MS), - Effect.flatMap( - Option.match({ - onNone: () => - Effect.fail( - new TextGenerationError({ operation, detail: "Codex CLI request timed out." }), - ), - onSome: () => Effect.void, - }), - ), - ); - - return yield* fileSystem.readFileString(outputPath).pipe( - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: "Failed to read Codex output file.", - cause, - }), - ), - Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))), - Effect.catchTag("SchemaError", (cause) => - Effect.fail( - new TextGenerationError({ - operation, - detail: "Codex returned invalid structured output.", - cause, - }), - ), - ), - ); - }).pipe(Effect.ensuring(cleanup)); - }); - - const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( - "CodexTextGeneration.generateCommitMessage", - )(function* (input) { - const { prompt, outputSchema } = buildCommitMessagePrompt({ - branch: input.branch, - stagedSummary: input.stagedSummary, - stagedPatch: input.stagedPatch, - includeBranch: input.includeBranch === true, - }); - - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateCommitMessage", - detail: "Invalid model selection.", - }); - } - - const generated = yield* runCodexJson({ - operation: "generateCommitMessage", - cwd: input.cwd, - prompt, - outputSchemaJson: outputSchema, - modelSelection: input.modelSelection, - }); - - return { - subject: sanitizeCommitSubject(generated.subject), - body: generated.body.trim(), - ...("branch" in generated && typeof generated.branch === "string" - ? { branch: sanitizeFeatureBranchName(generated.branch) } - : {}), - }; - }); - - const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn( - "CodexTextGeneration.generatePrContent", - )(function* (input) { - const { prompt, outputSchema } = buildPrContentPrompt({ - baseBranch: input.baseBranch, - headBranch: input.headBranch, - commitSummary: input.commitSummary, - diffSummary: input.diffSummary, - diffPatch: input.diffPatch, - }); - - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generatePrContent", - detail: "Invalid model selection.", - }); - } - - const generated = yield* runCodexJson({ - operation: "generatePrContent", - cwd: input.cwd, - prompt, - outputSchemaJson: outputSchema, - modelSelection: input.modelSelection, - }); - - return { - title: sanitizePrTitle(generated.title), - body: generated.body.trim(), - }; - }); - - const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn( - "CodexTextGeneration.generateBranchName", - )(function* (input) { - const { imagePaths } = yield* materializeImageAttachments( - "generateBranchName", - input.attachments, - ); - const { prompt, outputSchema } = buildBranchNamePrompt({ - message: input.message, - attachments: input.attachments, - }); - - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateBranchName", - detail: "Invalid model selection.", - }); - } - - const generated = yield* runCodexJson({ - operation: "generateBranchName", - cwd: input.cwd, - prompt, - outputSchemaJson: outputSchema, - imagePaths, - modelSelection: input.modelSelection, - }); - - return { - branch: sanitizeBranchFragment(generated.branch), - }; - }); - - const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( - "CodexTextGeneration.generateThreadTitle", - )(function* (input) { - const { imagePaths } = yield* materializeImageAttachments( - "generateThreadTitle", - input.attachments, - ); - const { prompt, outputSchema } = buildThreadTitlePrompt({ - message: input.message, - attachments: input.attachments, - }); - - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateThreadTitle", - detail: "Invalid model selection.", - }); - } - - const generated = yield* runCodexJson({ - operation: "generateThreadTitle", - cwd: input.cwd, - prompt, - outputSchemaJson: outputSchema, - imagePaths, - modelSelection: input.modelSelection, - }); - - return { - title: sanitizeThreadTitle(generated.title), - } satisfies ThreadTitleGenerationResult; - }); - - return { - generateCommitMessage, - generatePrContent, - generateBranchName, - generateThreadTitle, - } satisfies TextGenerationShape; -}); - -export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration); diff --git a/apps/server/src/git/Layers/CursorTextGeneration.test.ts b/apps/server/src/git/Layers/CursorTextGeneration.test.ts deleted file mode 100644 index e7bce11347..0000000000 --- a/apps/server/src/git/Layers/CursorTextGeneration.test.ts +++ /dev/null @@ -1,298 +0,0 @@ -import * as path from "node:path"; -import * as os from "node:os"; -import { fileURLToPath } from "node:url"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; -import { Effect, Layer } from "effect"; -import { expect } from "vitest"; - -import { ServerSettingsError } from "@t3tools/contracts"; - -import { ServerConfig } from "../../config.ts"; -import { TextGeneration } from "../Services/TextGeneration.ts"; -import { CursorTextGenerationLive } from "./CursorTextGeneration.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts"); - -function shellSingleQuote(value: string): string { - return `'${value.replaceAll("'", `'"'"'`)}'`; -} - -const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-text-generation-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), -); - -function makeAcpAgentWrapper(dir: string, env: Record): string { - const binDir = path.join(dir, "bin"); - const agentPath = path.join(binDir, "agent"); - mkdirSync(binDir, { recursive: true }); - writeFileSync( - agentPath, - [ - "#!/bin/sh", - ...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`), - 'if [ "$1" != "acp" ]; then', - ' printf "%s\\n" "unexpected args: $*" >&2', - " exit 11", - "fi", - `exec bun ${JSON.stringify(mockAgentPath)}`, - "", - ].join("\n"), - "utf8", - ); - chmodSync(agentPath, 0o755); - return agentPath; -} - -function withFakeAcpAgent( - env: Record, - effect: Effect.Effect, -): Effect.Effect { - return Effect.gen(function* () { - const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-")); - const agentPath = makeAcpAgentWrapper(tempDir, env); - const serverSettings = yield* ServerSettingsService; - const previousSettings = yield* serverSettings.getSettings; - - yield* serverSettings.updateSettings({ - providers: { - cursor: { - binaryPath: agentPath, - }, - }, - }); - - return yield* effect.pipe( - Effect.ensuring( - serverSettings - .updateSettings({ - providers: { - cursor: { - binaryPath: previousSettings.providers.cursor.binaryPath, - }, - }, - }) - .pipe( - Effect.catch(() => Effect.void), - Effect.ensuring( - Effect.sync(() => { - rmSync(tempDir, { recursive: true, force: true }); - }), - ), - Effect.asVoid, - ), - ), - ); - }); -} - -function waitForFileContent(path: string): Effect.Effect { - return Effect.promise(async () => { - const deadline = Date.now() + 5_000; - for (;;) { - try { - return readFileSync(path, "utf8"); - } catch (error) { - if (Date.now() >= deadline) { - throw error instanceof Error ? error : new Error(String(error)); - } - } - await new Promise((resolve) => setTimeout(resolve, 25)); - } - }); -} - -it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { - it.effect("uses ACP model config options instead of raw CLI model ids", () => { - const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-")); - const requestLogPath = path.join(requestLogDir, "requests.ndjson"); - - return withFakeAcpAgent( - { - T3_ACP_REQUEST_LOG_PATH: requestLogPath, - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - subject: "Add generated commit message", - body: "- verify cursor acp model config path", - }), - }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-text-generation", - stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", - modelSelection: { - provider: "cursor", - model: "gpt-5.4", - options: { - reasoning: "xhigh", - fastMode: true, - contextWindow: "1m", - }, - }, - }); - - expect(generated.subject).toBe("Add generated commit message"); - expect(generated.body).toBe("- verify cursor acp model config path"); - - const requests = readFileSync(requestLogPath, "utf8") - .trim() - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as { method?: string; params?: Record }); - - expect( - requests.find((request) => request.method === "initialize")?.params?.clientCapabilities, - ).toMatchObject({ - _meta: { - parameterizedModelPicker: true, - }, - }); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "model" && - request.params?.value === "gpt-5.4", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "reasoning" && - request.params?.value === "extra-high", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "context" && - request.params?.value === "1m", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "fast" && - request.params?.value === "true", - ), - ).toBe(true); - expect( - requests.find((request) => request.method === "session/prompt")?.params?.prompt, - ).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "text", - text: expect.stringContaining("Staged patch:"), - }), - ]), - ); - - rmSync(requestLogDir, { recursive: true, force: true }); - }), - ); - }); - - it.effect("accepts json objects with extra assistant text around them", () => - withFakeAcpAgent( - { - T3_ACP_PROMPT_RESPONSE_TEXT: - 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.', - }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-noisy-json", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); - - expect(generated.subject).toBe("Update README dummy comment with attribution and date"); - expect(generated.body).toBe(""); - }), - ), - ); - - it.effect("generates thread titles through Cursor ACP text generation", () => - withFakeAcpAgent( - { - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - title: '"Trim reconnect spinner status after resume."', - }), - }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Fix the reconnect spinner after a resumed session.", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); - - expect(generated.title).toBe("Trim reconnect spinner status after resume."); - }), - ), - ); - - it.effect("closes the ACP child process after text generation completes", () => { - const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-")); - const exitLogPath = path.join(exitLogDir, "exit.log"); - - return withFakeAcpAgent( - { - T3_ACP_EXIT_LOG_PATH: exitLogPath, - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - subject: "Close runtime after generation", - body: "", - }), - }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-runtime-close", - stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); - - expect(generated.subject).toBe("Close runtime after generation"); - - const exitLog = yield* waitForFileContent(exitLogPath); - expect(exitLog).toContain("exit:0"); - - rmSync(exitLogDir, { recursive: true, force: true }); - }), - ); - }); -}); diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts deleted file mode 100644 index 665c4b138f..0000000000 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ /dev/null @@ -1,2333 +0,0 @@ -import { existsSync } from "node:fs"; -import path from "node:path"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; -import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; -import { describe, expect, vi } from "vitest"; - -import { GitCoreLive, makeGitCore } from "./GitCore.ts"; -import { GitCore, type GitCoreShape } from "../Services/GitCore.ts"; -import { GitCommandError } from "@t3tools/contracts"; -import { type ProcessRunResult, runProcess } from "../../processRunner.ts"; -import { ServerConfig } from "../../config.ts"; - -// ── Helpers ── - -const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-core-test-" }); -const GitCoreTestLayer = GitCoreLive.pipe( - Layer.provide(ServerConfigLayer), - Layer.provide(NodeServices.layer), -); -const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer); - -function makeTmpDir( - prefix = "git-test-", -): Effect.Effect { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - return yield* fileSystem.makeTempDirectoryScoped({ prefix }); - }); -} - -function writeTextFile( - filePath: string, - contents: string, -): Effect.Effect { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - yield* fileSystem.writeFileString(filePath, contents); - }); -} - -function removePath( - targetPath: string, -): Effect.Effect { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - yield* fileSystem.remove(targetPath, { recursive: true, force: true }); - }); -} - -function makeDirectory( - dirPath: string, -): Effect.Effect { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - yield* fileSystem.makeDirectory(dirPath, { recursive: true }); - }); -} - -/** Run a raw git command for test setup (not under test). */ -function git( - cwd: string, - args: ReadonlyArray, - env?: NodeJS.ProcessEnv, -): Effect.Effect { - return Effect.gen(function* () { - const gitCore = yield* GitCore; - const result = yield* gitCore.execute({ - operation: "GitCore.test.git", - cwd, - args, - ...(env ? { env } : {}), - timeoutMs: 10_000, - }); - return result.stdout.trim(); - }); -} - -function configureRemote( - cwd: string, - remoteName: string, - remotePath: string, - fetchNamespace: string, -): Effect.Effect { - return Effect.gen(function* () { - yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]); - return yield* git(cwd, [ - "config", - "--replace-all", - `remote.${remoteName}.fetch`, - `+refs/heads/*:refs/remotes/${fetchNamespace}/*`, - ]); - }); -} - -function runShellCommand(input: { - command: string; - cwd: string; - timeoutMs?: number; - maxOutputBytes?: number; -}): Effect.Effect { - return Effect.promise(() => { - const shellPath = - process.platform === "win32" - ? (process.env.ComSpec ?? "cmd.exe") - : (process.env.SHELL ?? "/bin/sh"); - - const args = - process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command]; - - return runProcess(shellPath, args, { - cwd: input.cwd, - timeoutMs: input.timeoutMs ?? 30_000, - allowNonZeroExit: true, - maxBufferBytes: input.maxOutputBytes ?? 1_000_000, - outputMode: "truncate", - }); - }); -} - -const makeIsolatedGitCore = (executeOverride: GitCoreShape["execute"]) => - makeGitCore({ executeOverride }).pipe( - Effect.provide(Layer.provideMerge(ServerConfigLayer, NodeServices.layer)), - ); - -/** Create a repo with an initial commit so branches work. */ -function initRepoWithCommit( - cwd: string, -): Effect.Effect< - { initialBranch: string }, - GitCommandError | PlatformError.PlatformError, - GitCore | FileSystem.FileSystem -> { - return Effect.gen(function* () { - const core = yield* GitCore; - yield* core.initRepo({ cwd }); - yield* git(cwd, ["config", "user.email", "test@test.com"]); - yield* git(cwd, ["config", "user.name", "Test"]); - yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); - yield* git(cwd, ["add", "."]); - yield* git(cwd, ["commit", "-m", "initial commit"]); - const initialBranch = yield* git(cwd, ["branch", "--show-current"]); - return { initialBranch }; - }); -} - -function commitWithDate( - cwd: string, - fileName: string, - fileContents: string, - dateIsoString: string, - message: string, -): Effect.Effect< - void, - GitCommandError | PlatformError.PlatformError, - GitCore | FileSystem.FileSystem -> { - return Effect.gen(function* () { - yield* writeTextFile(path.join(cwd, fileName), fileContents); - yield* git(cwd, ["add", fileName]); - yield* git(cwd, ["commit", "-m", message], { - ...process.env, - GIT_AUTHOR_DATE: dateIsoString, - GIT_COMMITTER_DATE: dateIsoString, - }); - }); -} - -function buildLargeText(lineCount = 20_000): string { - return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) - .join("\n") - .concat("\n"); -} - -function splitNullSeparatedPaths(input: string): string[] { - return input - .split("\0") - .map((value) => value.trim()) - .filter((value) => value.length > 0); -} - -// ── Tests ── - -it.layer(TestLayer)("git integration", (it) => { - describe("shell process execution", () => { - it.effect("caps captured output when maxOutputBytes is exceeded", () => - Effect.gen(function* () { - const result = yield* runShellCommand({ - command: `node -e "process.stdout.write('x'.repeat(2000))"`, - cwd: process.cwd(), - timeoutMs: 10_000, - maxOutputBytes: 128, - }); - - expect(result.code).toBe(0); - expect(result.stdout.length).toBeLessThanOrEqual(128); - expect(result.stdoutTruncated || result.stderrTruncated).toBe(true); - }), - ); - }); - - // ── initGitRepo ── - - describe("initGitRepo", () => { - it.effect("creates a valid git repo", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* (yield* GitCore).initRepo({ cwd: tmp }); - expect(existsSync(path.join(tmp, ".git"))).toBe(true); - }), - ); - - it.effect("listGitBranches reports isRepo: true after init + commit", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.isRepo).toBe(true); - expect(result.hasOriginRemote).toBe(false); - expect(result.branches.length).toBeGreaterThanOrEqual(1); - }), - ); - }); - - describe("workspace helpers", () => { - it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => - Effect.gen(function* () { - const cwd = "/virtual/repo"; - const relativePaths = Array.from({ length: 340 }, (_, index) => { - const prefix = index % 3 === 0 ? "ignored" : "kept"; - return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; - }); - const expectedPaths = relativePaths.filter( - (relativePath) => !relativePath.startsWith("ignored/"), - ); - - const seenChunks: string[][] = []; - const core = yield* makeIsolatedGitCore((input) => { - if ( - input.args.join(" ") !== - "-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin" - ) { - return Effect.fail( - new GitCommandError({ - operation: input.operation, - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "unexpected git command in chunking test", - }), - ); - } - - const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); - seenChunks.push(chunkPaths); - const ignoredPaths = chunkPaths.filter((relativePath) => - relativePath.startsWith("ignored/"), - ); - - return Effect.succeed({ - code: ignoredPaths.length > 0 ? 0 : 1, - stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - }); - - const result = yield* core.filterIgnoredPaths(cwd, relativePaths); - - expect(seenChunks.length).toBeGreaterThan(1); - expect(seenChunks.flat()).toEqual(relativePaths); - expect(result).toEqual(expectedPaths); - }), - ); - - it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () => - Effect.gen(function* () { - const core = yield* makeIsolatedGitCore((input) => { - expect(input.args).toEqual([ - "-c", - "core.fsmonitor=false", - "-c", - "core.untrackedCache=false", - "ls-files", - "--cached", - "--others", - "--exclude-standard", - "-z", - ]); - return Effect.succeed({ - code: 0, - stdout: "src/index.ts\0README.md\0", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - }); - - const result = yield* core.listWorkspaceFiles("/virtual/repo"); - expect(result.paths).toEqual(["src/index.ts", "README.md"]); - expect(result.truncated).toBe(false); - }), - ); - }); - - // ── listGitBranches ── - - describe("listGitBranches", () => { - it.effect("returns isRepo: false for non-git directory", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.isRepo).toBe(false); - expect(result.hasOriginRemote).toBe(false); - expect(result.branches).toEqual([]); - }), - ); - - it.effect("returns isRepo: false for deleted directories", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const deletedDir = path.join(tmp, "deleted-repo"); - yield* makeDirectory(deletedDir); - yield* removePath(deletedDir); - - const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir }); - - expect(result.isRepo).toBe(false); - expect(result.hasOriginRemote).toBe(false); - expect(result.branches).toEqual([]); - }), - ); - - it.effect("returns the current branch with current: true", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const current = result.branches.find((b) => b.current); - expect(current).toBeDefined(); - expect(current!.current).toBe(true); - }), - ); - - it.effect("does not include detached HEAD pseudo-refs as branches", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* git(tmp, ["checkout", "--detach", "HEAD"]); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false); - expect(result.branches.some((branch) => branch.current)).toBe(false); - }), - ); - - it.effect("keeps current branch first and sorts the remaining branches by recency", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "older-branch" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" }); - yield* commitWithDate( - tmp, - "older.txt", - "older branch change\n", - "Thu, 1 Jan 2037 00:00:00 +0000", - "older branch change", - ); - - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" }); - yield* commitWithDate( - tmp, - "newer.txt", - "newer branch change\n", - "Fri, 1 Jan 2038 00:00:00 +0000", - "newer branch change", - ); - - // Switch away to show current branch is pinned, then remaining branches are recency-sorted. - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches[0]!.name).toBe("older-branch"); - expect(result.branches[1]!.name).toBe("newer-branch"); - }), - ); - - it.effect("keeps default branch right after current branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - - yield* git(remote, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* git(tmp, ["push", "-u", "origin", defaultBranch]); - yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]); - - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "current-branch" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" }); - yield* commitWithDate( - tmp, - "current.txt", - "current change\n", - "Thu, 1 Jan 2037 00:00:00 +0000", - "current change", - ); - - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" }); - yield* commitWithDate( - tmp, - "newer.txt", - "newer change\n", - "Fri, 1 Jan 2038 00:00:00 +0000", - "newer change", - ); - - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches[0]!.name).toBe("current-branch"); - expect(result.branches[1]!.name).toBe(defaultBranch); - expect(result.branches[2]!.name).toBe("newer-branch"); - }), - ); - - it.effect("lists multiple branches after creating them", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const names = result.branches.map((b) => b.name); - expect(names).toContain("feature-a"); - expect(names).toContain("feature-b"); - }), - ); - - it.effect("paginates branch results and returns paging metadata", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" }); - - const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 }); - expect(firstPage.totalCount).toBe(4); - expect(firstPage.nextCursor).toBe(2); - expect(firstPage.branches.map((branch) => branch.name)).toEqual([ - initialBranch, - "feature-a", - ]); - - const secondPage = yield* (yield* GitCore).listBranches({ - cwd: tmp, - cursor: firstPage.nextCursor ?? 0, - limit: 2, - }); - expect(secondPage.totalCount).toBe(4); - expect(secondPage.nextCursor).toBeNull(); - expect(secondPage.branches.map((branch) => branch.name)).toEqual([ - "feature-b", - "feature-c", - ]); - }), - ); - - it.effect("parses separate branch names when column.ui is always enabled", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(tmp); - const createdBranchNames = [ - "go-bin", - "copilot/rewrite-cli-in-go", - "copilot/rewrite-cli-in-rust", - ] as const; - for (const branchName of createdBranchNames) { - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName }); - } - yield* git(tmp, ["config", "column.ui", "always"]); - - const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], { - ...process.env, - COLUMNS: "120", - }); - expect( - rawBranchOutput - .split("\n") - .some( - (line) => - createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2, - ), - ).toBe(true); - - const realGitCore = yield* GitCore; - const core = yield* makeIsolatedGitCore((input) => - realGitCore.execute( - input.args[0] === "branch" - ? { - ...input, - env: { ...input.env, COLUMNS: "120" }, - } - : input, - ), - ); - - const result = yield* core.listBranches({ cwd: tmp }); - const localBranchNames = result.branches - .filter((branch) => !branch.isRemote) - .map((branch) => branch.name); - - expect(localBranchNames).toHaveLength(4); - expect(localBranchNames).toEqual( - expect.arrayContaining([initialBranch, ...createdBranchNames]), - ); - expect( - localBranchNames.some( - (branchName) => - createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch)) - .length >= 2, - ), - ).toBe(false); - }), - ); - - it.effect("isDefault is false when no remote exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches.every((b) => b.isDefault === false)).toBe(true); - }), - ); - - it.effect("lists local branches first and remote branches last", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const tmp = yield* makeTmpDir(); - - yield* git(remote, ["init", "--bare"]); - yield* initRepoWithCommit(tmp); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* git(tmp, ["push", "-u", "origin", defaultBranch]); - - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/local-only" }); - - const remoteOnlyBranch = "feature/remote-only"; - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); - yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]); - yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]); - yield* git(tmp, ["checkout", defaultBranch]); - yield* git(tmp, ["branch", "-D", remoteOnlyBranch]); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote); - - expect(result.hasOriginRemote).toBe(true); - expect(firstRemoteIndex).toBeGreaterThan(0); - expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe( - true, - ); - expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe( - true, - ); - expect( - result.branches.some( - (branch) => branch.name === "feature/local-only" && !branch.isRemote, - ), - ).toBe(true); - expect( - result.branches.some( - (branch) => branch.name === "origin/feature/remote-only" && branch.isRemote, - ), - ).toBe(true); - }), - ); - - it.effect("includes remoteName metadata for remotes with slash in the name", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const tmp = yield* makeTmpDir(); - const remoteName = "my-org/upstream"; - - yield* git(remote, ["init", "--bare"]); - yield* initRepoWithCommit(tmp); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - - yield* git(tmp, ["remote", "add", remoteName, remote]); - yield* git(tmp, ["push", "-u", remoteName, defaultBranch]); - - const remoteOnlyBranch = "feature/remote-with-remote-name"; - yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]); - yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]); - yield* git(tmp, ["checkout", defaultBranch]); - yield* git(tmp, ["branch", "-D", remoteOnlyBranch]); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const remoteBranch = result.branches.find( - (branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`, - ); - - expect(remoteBranch).toBeDefined(); - expect(remoteBranch?.isRemote).toBe(true); - expect(remoteBranch?.remoteName).toBe(remoteName); - }), - ); - - it.effect( - "filters branch queries before pagination and dedupes origin refs with local matches", - () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const tmp = yield* makeTmpDir(); - - yield* git(remote, ["init", "--bare"]); - const { initialBranch } = yield* initRepoWithCommit(tmp); - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* git(tmp, ["push", "-u", "origin", initialBranch]); - - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" }); - yield* git(tmp, ["push", "-u", "origin", "feature/demo"]); - - yield* git(tmp, ["checkout", "-b", "feature/remote-only"]); - yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]); - yield* git(tmp, ["checkout", initialBranch]); - yield* git(tmp, ["branch", "-D", "feature/remote-only"]); - - const result = yield* (yield* GitCore).listBranches({ - cwd: tmp, - query: "feature/", - limit: 10, - }); - - expect(result.totalCount).toBe(2); - expect(result.nextCursor).toBeNull(); - expect(result.branches.map((branch) => branch.name)).toEqual([ - "feature/demo", - "origin/feature/remote-only", - ]); - }), - ); - }); - - // ── checkoutGitBranch ── - - describe("checkoutGitBranch", () => { - it.effect("checks out an existing branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature" }); - - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const current = result.branches.find((b) => b.current); - expect(current!.name).toBe("feature"); - }), - ); - - it.effect("refreshes upstream behind count after checkout when remote branch advanced", () => - Effect.gen(function* () { - const context = yield* Effect.context(); - const runPromise = Effect.runPromiseWith(context); - - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - const clone = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - const featureBranch = "feature-behind"; - yield* (yield* GitCore).createBranch({ cwd: source, branch: featureBranch }); - yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); - yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature base"]); - yield* git(source, ["push", "-u", "origin", featureBranch]); - yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: defaultBranch }); - - yield* git(clone, ["clone", remote, "."]); - yield* git(clone, ["config", "user.email", "test@test.com"]); - yield* git(clone, ["config", "user.name", "Test"]); - yield* git(clone, ["checkout", "-b", featureBranch, "--track", `origin/${featureBranch}`]); - yield* writeTextFile(path.join(clone, "feature.txt"), "feature from remote\n"); - yield* git(clone, ["add", "feature.txt"]); - yield* git(clone, ["commit", "-m", "remote feature update"]); - yield* git(clone, ["push", "origin", featureBranch]); - - yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); - const core = yield* GitCore; - yield* Effect.promise(() => - vi.waitFor( - async () => { - const details = await runPromise(core.statusDetails(source)); - expect(details.branch).toBe(featureBranch); - expect(details.aheadCount).toBe(0); - expect(details.behindCount).toBe(1); - }, - { - timeout: 10_000, - interval: 100, - }, - ), - ); - }), - ); - - it.effect("statusDetails remains successful when upstream refresh fails after checkout", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - const featureBranch = "feature-refresh-failure"; - yield* git(source, ["branch", featureBranch]); - yield* git(source, ["checkout", featureBranch]); - yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature base"]); - yield* git(source, ["push", "-u", "origin", featureBranch]); - yield* git(source, ["checkout", defaultBranch]); - - const realGitCore = yield* GitCore; - let refreshFetchAttempts = 0; - const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { - refreshFetchAttempts += 1; - return Effect.fail( - new GitCommandError({ - operation: "git.test.refreshFailure", - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "simulated fetch timeout", - }), - ); - } - return realGitCore.execute(input); - }); - yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); - const status = yield* core.statusDetails(source); - expect(refreshFetchAttempts).toBe(1); - expect(status.branch).toBe(featureBranch); - expect(status.upstreamRef).toBe(`origin/${featureBranch}`); - expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch); - }), - ); - - it.effect("defers upstream refresh until statusDetails is requested", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - const featureBranch = "feature/scoped-fetch"; - yield* git(source, ["checkout", "-b", featureBranch]); - yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature base"]); - yield* git(source, ["push", "-u", "origin", featureBranch]); - yield* git(source, ["checkout", defaultBranch]); - - const realGitCore = yield* GitCore; - let refreshFetchAttempts = 0; - const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { - refreshFetchAttempts += 1; - return Effect.succeed({ - code: 0, - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - } - return realGitCore.execute(input); - }); - yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50))); - expect(refreshFetchAttempts).toBe(0); - const status = yield* core.statusDetails(source); - expect(status.branch).toBe(featureBranch); - expect(refreshFetchAttempts).toBe(1); - }), - ); - - it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () => - Effect.gen(function* () { - const ok = (stdout = "") => - Effect.succeed({ - code: 0, - stdout, - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - - let fetchCount = 0; - const core = yield* makeIsolatedGitCore((input) => { - if ( - input.args[0] === "rev-parse" && - input.args[1] === "--abbrev-ref" && - input.args[2] === "--symbolic-full-name" && - input.args[3] === "@{upstream}" - ) { - return ok( - input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n", - ); - } - if (input.args[0] === "remote") { - return ok("origin\n"); - } - if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { - return ok("/repo/.git\n"); - } - if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { - fetchCount += 1; - expect(input.cwd).toBe("/repo"); - expect(input.args).toEqual([ - "--git-dir", - "/repo/.git", - "fetch", - "--quiet", - "--no-tags", - "origin", - ]); - return ok(); - } - if (input.operation === "GitCore.statusDetails.status") { - return ok( - input.cwd === "/repo/worktrees/pr-123" - ? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n" - : "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n", - ); - } - if ( - input.operation === "GitCore.statusDetails.unstagedNumstat" || - input.operation === "GitCore.statusDetails.stagedNumstat" - ) { - return ok(); - } - if (input.operation === "GitCore.statusDetails.defaultRef") { - return ok("refs/remotes/origin/main\n"); - } - return Effect.fail( - new GitCommandError({ - operation: input.operation, - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "Unexpected git command in shared refresh cache test.", - }), - ); - }); - - yield* core.statusDetails("/repo/worktrees/main"); - yield* core.statusDetails("/repo/worktrees/pr-123"); - expect(fetchCount).toBe(1); - }), - ); - - it.effect( - "briefly backs off failed upstream refreshes across sibling worktrees on one remote", - () => - Effect.gen(function* () { - const ok = (stdout = "") => - Effect.succeed({ - code: 0, - stdout, - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - - let fetchCount = 0; - const core = yield* makeIsolatedGitCore((input) => { - if ( - input.args[0] === "rev-parse" && - input.args[1] === "--abbrev-ref" && - input.args[2] === "--symbolic-full-name" && - input.args[3] === "@{upstream}" - ) { - return ok( - input.cwd === "/repo/worktrees/pr-123" - ? "origin/feature/pr-123\n" - : "origin/main\n", - ); - } - if (input.args[0] === "remote") { - return ok("origin\n"); - } - if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { - return ok("/repo/.git\n"); - } - if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { - fetchCount += 1; - return Effect.fail( - new GitCommandError({ - operation: input.operation, - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "simulated fetch timeout", - }), - ); - } - if (input.operation === "GitCore.statusDetails.status") { - return ok( - input.cwd === "/repo/worktrees/pr-123" - ? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n" - : "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n", - ); - } - if ( - input.operation === "GitCore.statusDetails.unstagedNumstat" || - input.operation === "GitCore.statusDetails.stagedNumstat" - ) { - return ok(); - } - if (input.operation === "GitCore.statusDetails.defaultRef") { - return ok("refs/remotes/origin/main\n"); - } - return Effect.fail( - new GitCommandError({ - operation: input.operation, - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "Unexpected git command in refresh failure cooldown test.", - }), - ); - }); - - yield* core.statusDetails("/repo/worktrees/main"); - yield* core.statusDetails("/repo/worktrees/pr-123"); - expect(fetchCount).toBe(1); - }), - ); - - it.effect("throws when branch does not exist", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const result = yield* Effect.result( - (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "nonexistent" }), - ); - expect(result._tag).toBe("Failure"); - }), - ); - - it.effect("does not silently checkout a local branch when a remote ref no longer exists", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - yield* (yield* GitCore).createBranch({ cwd: source, branch: "feature" }); - - const checkoutResult = yield* Effect.result( - (yield* GitCore).checkoutBranch({ cwd: source, branch: "origin/feature" }), - ); - expect(checkoutResult._tag).toBe("Failure"); - expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch); - }), - ); - - it.effect("checks out a remote tracking branch when remote name contains slashes", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const prefixRemote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - const prefixFetchNamespace = "prefix-my-org"; - const prefixRemoteName = "my-org"; - const remoteName = "my-org/upstream"; - const featureBranch = "feature"; - yield* git(remote, ["init", "--bare"]); - yield* git(prefixRemote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace); - yield* configureRemote(source, remoteName, remote, remoteName); - yield* git(source, ["push", "-u", remoteName, defaultBranch]); - - yield* git(source, ["checkout", "-b", featureBranch]); - yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n"); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature commit"]); - yield* git(source, ["push", "-u", remoteName, featureBranch]); - yield* git(source, ["checkout", defaultBranch]); - yield* git(source, ["branch", "-D", featureBranch]); - - const checkoutResult = yield* (yield* GitCore).checkoutBranch({ - cwd: source, - branch: `${remoteName}/${featureBranch}`, - }); - - expect(checkoutResult.branch).toBe("upstream/feature"); - expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature"); - const realGitCore = yield* GitCore; - let fetchArgs: readonly string[] | null = null; - const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { - fetchArgs = [...input.args]; - return Effect.succeed({ - code: 0, - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - } - return realGitCore.execute(input); - }); - - const status = yield* core.statusDetails(source); - expect(status.branch).toBe("upstream/feature"); - expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`); - expect(fetchArgs).toEqual([ - "--git-dir", - path.join(source, ".git"), - "fetch", - "--quiet", - "--no-tags", - remoteName, - ]); - }), - ); - - it.effect( - "falls back to detached checkout when --track would conflict with an existing local branch", - () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ - cwd: source, - })).branches.find((branch) => branch.current)!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - // Keep local branch but remove tracking so `--track origin/` - // would attempt to create an already-existing local branch. - yield* git(source, ["branch", "--unset-upstream"]); - - yield* (yield* GitCore).checkoutBranch({ - cwd: source, - branch: `origin/${defaultBranch}`, - }); - - const core = yield* GitCore; - const status = yield* core.statusDetails(source); - expect(status.branch).toBeNull(); - }), - ); - - it.effect("throws when checkout would overwrite uncommitted changes", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "other" }); - - // Create a conflicting change: modify README on current branch - yield* writeTextFile(path.join(tmp, "README.md"), "modified\n"); - yield* git(tmp, ["add", "README.md"]); - - // First, checkout other branch cleanly - yield* git(tmp, ["stash"]); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" }); - yield* writeTextFile(path.join(tmp, "README.md"), "other content\n"); - yield* git(tmp, ["add", "."]); - yield* git(tmp, ["commit", "-m", "other change"]); - - // Go back to default branch - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => !b.current, - )!.name; - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); - - // Make uncommitted changes to the same file - yield* writeTextFile(path.join(tmp, "README.md"), "conflicting local\n"); - - // Checkout should fail due to uncommitted changes - const result = yield* Effect.result( - (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" }), - ); - expect(result._tag).toBe("Failure"); - }), - ); - }); - - // ── createGitBranch ── - - describe("createGitBranch", () => { - it.effect("creates a new branch visible in listGitBranches", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "new-feature" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches.some((b) => b.name === "new-feature")).toBe(true); - }), - ); - - it.effect("throws when branch already exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" }); - const result = yield* Effect.result( - (yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" }), - ); - expect(result._tag).toBe("Failure"); - }), - ); - }); - - // ── renameGitBranch ── - - describe("renameGitBranch", () => { - it.effect("renames the current branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" }); - - const renamed = yield* (yield* GitCore).renameBranch({ - cwd: tmp, - oldBranch: "feature/old-name", - newBranch: "feature/new-name", - }); - - expect(renamed.branch).toBe("feature/new-name"); - - const branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false); - const current = branches.branches.find((branch) => branch.current); - expect(current?.name).toBe("feature/new-name"); - }), - ); - - it.effect("returns success without git invocation when old/new names match", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const current = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!; - - const renamed = yield* (yield* GitCore).renameBranch({ - cwd: tmp, - oldBranch: current.name, - newBranch: current.name, - }); - - expect(renamed.branch).toBe(current.name); - }), - ); - - it.effect("appends numeric suffix when target branch already exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/tmp-working" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "t3code/tmp-working" }); - - const renamed = yield* (yield* GitCore).renameBranch({ - cwd: tmp, - oldBranch: "t3code/tmp-working", - newBranch: "t3code/feat/session", - }); - - expect(renamed.branch).toBe("t3code/feat/session-1"); - const branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe( - true, - ); - expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe( - true, - ); - const current = branches.branches.find((branch) => branch.current); - expect(current?.name).toBe("t3code/feat/session-1"); - }), - ); - - it.effect("increments suffix until it finds an available branch name", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session-1" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/tmp-working" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "t3code/tmp-working" }); - - const renamed = yield* (yield* GitCore).renameBranch({ - cwd: tmp, - oldBranch: "t3code/tmp-working", - newBranch: "t3code/feat/session", - }); - - expect(renamed.branch).toBe("t3code/feat/session-2"); - }), - ); - - it.effect("uses '--' separator for branch rename arguments", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" }); - - const realGitCore = yield* GitCore; - let renameArgs: ReadonlyArray | null = null; - const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "branch" && input.args[1] === "-m") { - renameArgs = [...input.args]; - } - return realGitCore.execute(input); - }); - - const renamed = yield* core.renameBranch({ - cwd: tmp, - oldBranch: "feature/old-name", - newBranch: "feature/new-name", - }); - - expect(renamed.branch).toBe("feature/new-name"); - expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]); - }), - ); - }); - - // ── createGitWorktree + removeGitWorktree ── - - describe("createGitWorktree", () => { - it.effect("creates a worktree with a new branch from the base branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const wtPath = path.join(tmp, "worktree-out"); - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - const result = yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "wt-branch", - path: wtPath, - }); - - expect(result.worktree.path).toBe(wtPath); - expect(result.worktree.branch).toBe("wt-branch"); - expect(existsSync(wtPath)).toBe(true); - expect(existsSync(path.join(wtPath, "README.md"))).toBe(true); - - // Clean up worktree before tmp dir disposal - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - }), - ); - - it.effect("worktree has the new branch checked out", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const wtPath = path.join(tmp, "wt-check-dir"); - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "wt-check", - path: wtPath, - }); - - // Verify the worktree is on the new branch - const branchOutput = yield* git(wtPath, ["branch", "--show-current"]); - expect(branchOutput).toBe("wt-check"); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - }), - ); - - it.effect("creates a worktree for an existing branch when newBranch is omitted", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/existing-worktree" }); - - const wtPath = path.join(tmp, "wt-existing"); - const result = yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: "feature/existing-worktree", - path: wtPath, - }); - - expect(result.worktree.path).toBe(wtPath); - expect(result.worktree.branch).toBe("feature/existing-worktree"); - const branchOutput = yield* git(wtPath, ["branch", "--show-current"]); - expect(branchOutput).toBe("feature/existing-worktree"); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - }), - ); - - it.effect("throws when new branch name already exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "existing" }); - - const wtPath = path.join(tmp, "wt-conflict"); - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - const result = yield* Effect.result( - (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "existing", - path: wtPath, - }), - ); - expect(result._tag).toBe("Failure"); - }), - ); - - it.effect("listGitBranches from worktree cwd reports worktree branch as current", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const wtPath = path.join(tmp, "wt-list-dir"); - const mainBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: mainBranch, - newBranch: "wt-list", - path: wtPath, - }); - - // listGitBranches from the worktree should show wt-list as current - const wtBranches = yield* (yield* GitCore).listBranches({ cwd: wtPath }); - expect(wtBranches.isRepo).toBe(true); - const wtCurrent = wtBranches.branches.find((b) => b.current); - expect(wtCurrent!.name).toBe("wt-list"); - - // Main repo should still show the original branch as current - const mainBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const mainCurrent = mainBranches.branches.find((b) => b.current); - expect(mainCurrent!.name).toBe(mainBranch); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - }), - ); - - it.effect("removeGitWorktree cleans up the worktree", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const wtPath = path.join(tmp, "wt-remove-dir"); - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "wt-remove", - path: wtPath, - }); - expect(existsSync(wtPath)).toBe(true); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - expect(existsSync(wtPath)).toBe(false); - }), - ); - - it.effect("removeGitWorktree force removes a dirty worktree", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const wtPath = path.join(tmp, "wt-dirty-dir"); - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "wt-dirty", - path: wtPath, - }); - expect(existsSync(wtPath)).toBe(true); - - yield* writeTextFile(path.join(wtPath, "README.md"), "dirty change\n"); - - const failedRemove = yield* Effect.result( - (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }), - ); - expect(failedRemove._tag).toBe("Failure"); - expect(existsSync(wtPath)).toBe(true); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath, force: true }); - expect(existsSync(wtPath)).toBe(false); - }), - ); - }); - - // ── Full flow: local branch checkout ── - - describe("full flow: local branch checkout", () => { - it.effect("init → commit → create branch → checkout → verify current", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-login" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature-login" }); - - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const current = result.branches.find((b) => b.current); - expect(current!.name).toBe("feature-login"); - }), - ); - }); - - // ── Full flow: worktree creation from base branch ── - - describe("full flow: worktree creation", () => { - it.effect("creates worktree with new branch from current branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - - const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (b) => b.current, - )!.name; - - const wtPath = path.join(tmp, "my-worktree"); - const result = yield* (yield* GitCore).createWorktree({ - cwd: tmp, - branch: currentBranch, - newBranch: "feature-wt", - path: wtPath, - }); - - // Worktree exists - expect(existsSync(result.worktree.path)).toBe(true); - - // Main repo still on original branch - const mainBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const mainCurrent = mainBranches.branches.find((b) => b.current); - expect(mainCurrent!.name).toBe(currentBranch); - - // Worktree is on the new branch - const wtBranch = yield* git(wtPath, ["branch", "--show-current"]); - expect(wtBranch).toBe("feature-wt"); - - yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); - }), - ); - }); - - describe("fetchPullRequestBranch", () => { - it.effect("fetches a GitHub pull request ref into a local branch without checkout", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(tmp); - const remoteDir = yield* makeTmpDir("git-remote-"); - yield* git(remoteDir, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "origin", remoteDir]); - yield* git(tmp, ["push", "-u", "origin", initialBranch]); - yield* git(tmp, ["checkout", "-b", "feature/pr-fetch"]); - yield* writeTextFile(path.join(tmp, "pr-fetch.txt"), "fetch me\n"); - yield* git(tmp, ["add", "pr-fetch.txt"]); - yield* git(tmp, ["commit", "-m", "Add PR fetch branch"]); - yield* git(tmp, ["push", "-u", "origin", "feature/pr-fetch"]); - yield* git(tmp, ["push", "origin", "HEAD:refs/pull/55/head"]); - yield* git(tmp, ["checkout", initialBranch]); - - yield* (yield* GitCore).fetchPullRequestBranch({ - cwd: tmp, - prNumber: 55, - branch: "feature/pr-fetch", - }); - - const localBranches = yield* git(tmp, ["branch", "--list", "feature/pr-fetch"]); - expect(localBranches).toContain("feature/pr-fetch"); - const currentBranch = yield* git(tmp, ["branch", "--show-current"]); - expect(currentBranch).toBe(initialBranch); - }), - ); - }); - - // ── Full flow: thread switching simulation ── - - describe("full flow: thread switching (checkout toggling)", () => { - it.effect("checkout a → checkout b → checkout a → current matches", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "branch-a" }); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "branch-b" }); - - // Simulate switching to thread A's branch - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-a" }); - let branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); - - // Simulate switching to thread B's branch - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-b" }); - branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b"); - - // Switch back to thread A - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-a" }); - branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); - }), - ); - }); - - // ── Full flow: checkout conflict ── - - describe("full flow: checkout conflict", () => { - it.effect("uncommitted changes prevent checkout to a diverged branch", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "diverged" }); - - // Make diverged branch have different file content - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "diverged" }); - yield* writeTextFile(path.join(tmp, "README.md"), "diverged content\n"); - yield* git(tmp, ["add", "."]); - yield* git(tmp, ["commit", "-m", "diverge"]); - - // Actually, let's just get back to the initial branch explicitly - const allBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); - const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name; - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch }); - - // Make local uncommitted changes to the same file - yield* writeTextFile(path.join(tmp, "README.md"), "local uncommitted\n"); - - // Attempt checkout should fail - const failedCheckout = yield* Effect.result( - (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "diverged" }), - ); - expect(failedCheckout._tag).toBe("Failure"); - - // Current branch should still be the initial one - const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); - expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch); - }), - ); - }); - - describe("GitCore", () => { - it.effect("supports branch lifecycle operations through the service API", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const core = yield* GitCore; - - yield* core.initRepo({ cwd: tmp }); - yield* git(tmp, ["config", "user.email", "test@test.com"]); - yield* git(tmp, ["config", "user.name", "Test"]); - yield* writeTextFile(path.join(tmp, "README.md"), "# test\n"); - yield* git(tmp, ["add", "."]); - yield* git(tmp, ["commit", "-m", "initial commit"]); - - yield* core.createBranch({ cwd: tmp, branch: "feature/service-api" }); - yield* core.checkoutBranch({ cwd: tmp, branch: "feature/service-api" }); - const branches = yield* core.listBranches({ cwd: tmp }); - - expect(branches.isRepo).toBe(true); - expect( - branches.branches.find((branch: { current: boolean; name: string }) => branch.current) - ?.name, - ).toBe("feature/service-api"); - }), - ); - - it.effect( - "reuses an existing remote when the target URL only differs by a trailing slash after .git", - () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* git(tmp, ["remote", "add", "origin", "git@github.com:pingdotgg/t3code.git"]); - - const remoteName = yield* core.ensureRemote({ - cwd: tmp, - preferredName: "origin", - url: "git@github.com:pingdotgg/t3code.git/", - }); - - expect(remoteName).toBe("origin"); - expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]); - }), - ); - - it.effect("reports status details and dirty state", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - const clean = yield* core.status({ cwd: tmp }); - expect(clean.hasWorkingTreeChanges).toBe(false); - expect(clean.branch).toBeTruthy(); - - yield* writeTextFile(path.join(tmp, "README.md"), "updated\n"); - const dirty = yield* core.statusDetails(tmp); - expect(dirty.hasWorkingTreeChanges).toBe(true); - }), - ); - - it.effect("returns a non-repo status for deleted directories", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const deletedDir = path.join(tmp, "deleted-repo"); - yield* makeDirectory(deletedDir); - yield* removePath(deletedDir); - const core = yield* GitCore; - - const status = yield* core.statusDetails(deletedDir); - const localStatus = yield* core.statusDetailsLocal(deletedDir); - - expect(status).toEqual({ - isRepo: false, - hasOriginRemote: false, - isDefaultBranch: false, - branch: null, - upstreamRef: null, - hasWorkingTreeChanges: false, - workingTree: { - files: [], - insertions: 0, - deletions: 0, - }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - }); - expect(localStatus).toEqual(status); - }), - ); - - it.effect("computes ahead count against base branch when no upstream is configured", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" }); - yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" }); - yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n"); - yield* git(tmp, ["add", "feature.txt"]); - yield* git(tmp, ["commit", "-m", "feature commit"]); - - const details = yield* core.statusDetails(tmp); - expect(details.branch).toBe("feature/no-upstream-ahead"); - expect(details.hasUpstream).toBe(false); - expect(details.aheadCount).toBe(1); - expect(details.behindCount).toBe(0); - }), - ); - - it.effect( - "computes ahead count against origin/default when local default branch is missing", - () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const initialBranch = (yield* (yield* GitCore).listBranches({ - cwd: source, - })).branches.find((branch) => branch.current)!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", initialBranch]); - yield* git(source, ["checkout", "-b", "feature/remote-base-only"]); - yield* writeTextFile( - path.join(source, "feature.txt"), - `ahead of origin/${initialBranch}\n`, - ); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature commit"]); - yield* git(source, ["branch", "-D", initialBranch]); - - const core = yield* GitCore; - const details = yield* core.statusDetails(source); - expect(details.branch).toBe("feature/remote-base-only"); - expect(details.hasUpstream).toBe(false); - expect(details.aheadCount).toBe(1); - expect(details.behindCount).toBe(0); - }), - ); - - it.effect( - "computes ahead count against a non-origin remote-prefixed gh-merge-base candidate", - () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - const remoteName = "fork-seed"; - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const initialBranch = (yield* (yield* GitCore).listBranches({ - cwd: source, - })).branches.find((branch) => branch.current)!.name; - yield* git(source, ["remote", "add", remoteName, remote]); - yield* git(source, ["push", "-u", remoteName, initialBranch]); - yield* git(source, ["checkout", "-b", "feature/non-origin-merge-base"]); - yield* git(source, [ - "config", - "branch.feature/non-origin-merge-base.gh-merge-base", - `${remoteName}/${initialBranch}`, - ]); - yield* writeTextFile( - path.join(source, "feature.txt"), - `ahead of ${remoteName}/${initialBranch}\n`, - ); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature commit"]); - yield* git(source, ["branch", "-D", initialBranch]); - - const core = yield* GitCore; - const details = yield* core.statusDetails(source); - expect(details.branch).toBe("feature/non-origin-merge-base"); - expect(details.hasUpstream).toBe(false); - expect(details.aheadCount).toBe(1); - expect(details.behindCount).toBe(0); - }), - ); - - it.effect("skips push when no upstream is configured and branch is not ahead of base", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" }); - yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" }); - - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("skipped_up_to_date"); - expect(pushed.branch).toBe("feature/no-upstream-no-ahead"); - expect(pushed.setUpstream).toBeUndefined(); - }), - ); - - it.effect("pushes with upstream setup when no comparable base branch exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* git(tmp, ["init", "--initial-branch=trunk"]); - yield* git(tmp, ["config", "user.email", "test@test.com"]); - yield* git(tmp, ["config", "user.name", "Test"]); - yield* writeTextFile(path.join(tmp, "README.md"), "hello\n"); - yield* git(tmp, ["add", "README.md"]); - yield* git(tmp, ["commit", "-m", "initial"]); - yield* git(remote, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* git(tmp, ["checkout", "-b", "feature/no-base"]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(pushed.upstreamBranch).toBe("origin/feature/no-base"); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - "origin/feature/no-base", - ); - }), - ); - - it.effect("pushes with upstream setup to the only configured non-origin remote", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* git(tmp, ["init", "--initial-branch=main"]); - yield* git(tmp, ["config", "user.email", "test@test.com"]); - yield* git(tmp, ["config", "user.name", "Test"]); - yield* writeTextFile(path.join(tmp, "README.md"), "hello\n"); - yield* git(tmp, ["add", "README.md"]); - yield* git(tmp, ["commit", "-m", "initial"]); - yield* git(remote, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "fork", remote]); - yield* git(tmp, ["checkout", "-b", "feature/fork-only"]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(pushed.upstreamBranch).toBe("fork/feature/fork-only"); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - "fork/feature/fork-only", - ); - }), - ); - - it.effect( - "pushes with upstream setup when comparable base exists but remote branch is missing", - () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(tmp); - const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* git(tmp, ["push", "-u", "origin", initialBranch]); - - yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n"); - yield* git(tmp, ["add", "default-ahead.txt"]); - yield* git(tmp, ["commit", "-m", "default ahead"]); - - const featureBranch = "feature/publish-no-upstream"; - yield* git(tmp, ["checkout", "-b", featureBranch]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - `origin/${featureBranch}`, - ); - expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain( - featureBranch, - ); - }), - ); - - it.effect("prefers branch pushRemote over origin when setting upstream", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const origin = yield* makeTmpDir(); - const fork = yield* makeTmpDir(); - yield* git(origin, ["init", "--bare"]); - yield* git(fork, ["init", "--bare"]); - - yield* initRepoWithCommit(tmp); - const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(tmp, ["remote", "add", "origin", origin]); - yield* git(tmp, ["remote", "add", "fork", fork]); - yield* git(tmp, ["push", "-u", "origin", initialBranch]); - - const featureBranch = "feature/push-remote"; - yield* git(tmp, ["checkout", "-b", featureBranch]); - yield* git(tmp, ["config", `branch.${featureBranch}.pushRemote`, "fork"]); - yield* writeTextFile(path.join(tmp, "feature.txt"), "push to fork\n"); - yield* git(tmp, ["add", "feature.txt"]); - yield* git(tmp, ["commit", "-m", "feature commit"]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(pushed.upstreamBranch).toBe(`fork/${featureBranch}`); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - `fork/${featureBranch}`, - ); - expect(yield* git(tmp, ["ls-remote", "--heads", "fork", featureBranch])).toContain( - featureBranch, - ); - }), - ); - - it.effect( - "pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current", - () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const fork = yield* makeTmpDir(); - yield* git(fork, ["init", "--bare"]); - - const { initialBranch } = yield* initRepoWithCommit(tmp); - yield* git(tmp, ["remote", "add", "jasonLaster", fork]); - yield* git(tmp, ["checkout", "-b", "statemachine"]); - yield* writeTextFile(path.join(tmp, "fork.txt"), "fork branch\n"); - yield* git(tmp, ["add", "fork.txt"]); - yield* git(tmp, ["commit", "-m", "fork branch"]); - yield* git(tmp, ["push", "-u", "jasonLaster", "statemachine"]); - yield* git(tmp, ["checkout", initialBranch]); - yield* git(tmp, ["branch", "-D", "statemachine"]); - yield* git(tmp, [ - "checkout", - "-b", - "t3code/pr-488/statemachine", - "--track", - "jasonLaster/statemachine", - ]); - yield* git(tmp, ["config", "push.default", "current"]); - yield* writeTextFile(path.join(tmp, "fork.txt"), "updated fork branch\n"); - yield* git(tmp, ["add", "fork.txt"]); - yield* git(tmp, ["commit", "-m", "update reviewed PR branch"]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(false); - expect(pushed.upstreamBranch).toBe("jasonLaster/statemachine"); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - "jasonLaster/statemachine", - ); - expect( - yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "statemachine"]), - ).toContain("statemachine"); - expect( - yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "t3code/pr-488/statemachine"]), - ).toBe(""); - }), - ); - - it.effect("pushes to the tracked upstream when the remote name contains slashes", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - const prefixRemote = yield* makeTmpDir(); - const prefixFetchNamespace = "prefix-my-org"; - const prefixRemoteName = "my-org"; - const remoteName = "my-org/upstream"; - const featureBranch = "feature/slash-remote-push"; - yield* git(remote, ["init", "--bare"]); - yield* git(prefixRemote, ["init", "--bare"]); - - const { initialBranch } = yield* initRepoWithCommit(tmp); - yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace); - yield* configureRemote(tmp, remoteName, remote, remoteName); - yield* git(tmp, ["push", "-u", remoteName, initialBranch]); - - yield* git(tmp, ["checkout", "-b", featureBranch]); - yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n"); - yield* git(tmp, ["add", "feature.txt"]); - yield* git(tmp, ["commit", "-m", "feature base"]); - yield* git(tmp, ["push", "-u", remoteName, featureBranch]); - - yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n"); - yield* git(tmp, ["add", "feature.txt"]); - yield* git(tmp, ["commit", "-m", "feature update"]); - - const core = yield* GitCore; - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(false); - expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - `${remoteName}/${featureBranch}`, - ); - expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain( - featureBranch, - ); - }), - ); - - it.effect("includes command context when worktree removal fails", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - const missingWorktreePath = path.join(tmp, "missing-worktree"); - - const removeResult = yield* Effect.result( - core.removeWorktree({ cwd: tmp, path: missingWorktreePath }), - ); - expect(removeResult._tag).toBe("Failure"); - if (removeResult._tag !== "Failure") { - return; - } - const message = removeResult.failure.message; - expect(message).toContain("git worktree remove"); - expect(message).toContain(`cwd: ${tmp}`); - expect(message).toContain(missingWorktreePath); - }), - ); - - it.effect( - "refreshes upstream before statusDetails so behind count reflects remote updates", - () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - const clone = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const initialBranch = (yield* (yield* GitCore).listBranches({ - cwd: source, - })).branches.find((branch) => branch.current)!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", initialBranch]); - - yield* git(clone, ["clone", remote, "."]); - yield* git(clone, ["config", "user.email", "test@test.com"]); - yield* git(clone, ["config", "user.name", "Test"]); - yield* git(clone, [ - "checkout", - "-B", - initialBranch, - "--track", - `origin/${initialBranch}`, - ]); - yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n"); - yield* git(clone, ["add", "CHANGELOG.md"]); - yield* git(clone, ["commit", "-m", "remote update"]); - yield* git(clone, ["push", "origin", initialBranch]); - - const core = yield* GitCore; - const details = yield* core.statusDetails(source); - expect(details.branch).toBe(initialBranch); - expect(details.aheadCount).toBe(0); - expect(details.behindCount).toBe(1); - }), - ); - - it.effect("prepares commit context by auto-staging and creates commit", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* writeTextFile(path.join(tmp, "README.md"), "new content\n"); - const context = yield* core.prepareCommitContext(tmp); - expect(context).not.toBeNull(); - expect(context!.stagedSummary.length).toBeGreaterThan(0); - expect(context!.stagedPatch.length).toBeGreaterThan(0); - - const created = yield* core.commit(tmp, "Add README update", "- include updated content"); - expect(created.commitSha.length).toBeGreaterThan(0); - expect(yield* git(tmp, ["log", "-1", "--pretty=%s"])).toBe("Add README update"); - }), - ); - - it.effect("prepareCommitContext stages only selected files when filePaths provided", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n"); - yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n"); - - const context = yield* core.prepareCommitContext(tmp, ["a.txt"]); - expect(context).not.toBeNull(); - expect(context!.stagedSummary).toContain("a.txt"); - expect(context!.stagedSummary).not.toContain("b.txt"); - - yield* core.commit(tmp, "Add only a.txt", ""); - - // b.txt should still be untracked after commit - const statusAfter = yield* git(tmp, ["status", "--porcelain"]); - expect(statusAfter).toContain("b.txt"); - expect(statusAfter).not.toContain("a.txt"); - }), - ); - - it.effect("prepareCommitContext stages everything when filePaths is undefined", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n"); - yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n"); - - const context = yield* core.prepareCommitContext(tmp); - expect(context).not.toBeNull(); - expect(context!.stagedSummary).toContain("a.txt"); - expect(context!.stagedSummary).toContain("b.txt"); - }), - ); - - it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); - - const context = yield* core.prepareCommitContext(tmp); - expect(context).not.toBeNull(); - expect(context!.stagedSummary).toContain("README.md"); - expect(context!.stagedPatch).toContain("[truncated]"); - }), - ); - - it.effect("readRangeContext truncates oversized diff patches instead of failing", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(tmp); - const core = yield* GitCore; - - yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" }); - yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" }); - yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText()); - yield* git(tmp, ["add", "large.txt"]); - yield* git(tmp, ["commit", "-m", "Add large range context"]); - - const rangeContext = yield* core.readRangeContext(tmp, initialBranch); - expect(rangeContext.commitSummary).toContain("Add large range context"); - expect(rangeContext.diffSummary).toContain("large.txt"); - expect(rangeContext.diffPatch).toContain("[truncated]"); - }), - ); - - it.effect("pushes with upstream setup and then skips when up to date", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* git(remote, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "origin", remote]); - yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/core-push" }); - yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/core-push" }); - - yield* writeTextFile(path.join(tmp, "feature.txt"), "push me\n"); - const core = yield* GitCore; - const context = yield* core.prepareCommitContext(tmp); - expect(context).not.toBeNull(); - yield* core.commit(tmp, "Add feature file", ""); - - const pushed = yield* core.pushCurrentBranch(tmp, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - "origin/feature/core-push", - ); - - const skipped = yield* core.pushCurrentBranch(tmp, null); - expect(skipped.status).toBe("skipped_up_to_date"); - }), - ); - - it.effect("pulls behind branch and then reports up-to-date", () => - Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - const clone = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); - - yield* initRepoWithCommit(source); - const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", initialBranch]); - - yield* git(clone, ["clone", remote, "."]); - yield* git(clone, ["config", "user.email", "test@test.com"]); - yield* git(clone, ["config", "user.name", "Test"]); - yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n"); - yield* git(clone, ["add", "CHANGELOG.md"]); - yield* git(clone, ["commit", "-m", "remote update"]); - yield* git(clone, ["push", "origin", initialBranch]); - - const core = yield* GitCore; - const pulled = yield* core.pullCurrentBranch(source); - expect(pulled.status).toBe("pulled"); - expect((yield* core.statusDetails(source)).behindCount).toBe(0); - - const skipped = yield* core.pullCurrentBranch(source); - expect(skipped.status).toBe("skipped_up_to_date"); - }), - ); - - it.effect("top-level pullGitBranch rejects when no upstream exists", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const result = yield* Effect.result((yield* GitCore).pullCurrentBranch(tmp)); - expect(result._tag).toBe("Failure"); - if (result._tag === "Failure") { - expect(result.failure.message.toLowerCase()).toContain("no upstream"); - } - }), - ); - - it.effect("lists branches when recency lookup fails", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - const realGitCore = yield* GitCore; - let didFailRecency = false; - const core = yield* makeIsolatedGitCore((input) => { - if (!didFailRecency && input.args[0] === "for-each-ref") { - didFailRecency = true; - return Effect.fail( - new GitCommandError({ - operation: "git.test.listBranchesRecency", - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "timeout", - }), - ); - } - return realGitCore.execute(input); - }); - - const result = yield* core.listBranches({ cwd: tmp }); - - expect(result.isRepo).toBe(true); - expect(result.branches.length).toBeGreaterThan(0); - expect(result.branches[0]?.current).toBe(true); - expect(didFailRecency).toBe(true); - }), - ); - - it.effect("falls back to empty remote branch data when remote lookups fail", () => - Effect.gen(function* () { - const tmp = yield* makeTmpDir(); - const remote = yield* makeTmpDir(); - yield* initRepoWithCommit(tmp); - yield* git(remote, ["init", "--bare"]); - yield* git(tmp, ["remote", "add", "origin", remote]); - - const realGitCore = yield* GitCore; - let didFailRemoteBranches = false; - let didFailRemoteNames = false; - const core = yield* makeIsolatedGitCore((input) => { - if (input.args.join(" ") === "branch --no-color --no-column --remotes") { - didFailRemoteBranches = true; - return Effect.fail( - new GitCommandError({ - operation: "git.test.listBranchesRemoteBranches", - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "remote unavailable", - }), - ); - } - if (input.args.join(" ") === "remote") { - didFailRemoteNames = true; - return Effect.fail( - new GitCommandError({ - operation: "git.test.listBranchesRemoteNames", - command: `git ${input.args.join(" ")}`, - cwd: input.cwd, - detail: "remote unavailable", - }), - ); - } - return realGitCore.execute(input); - }); - - const result = yield* core.listBranches({ cwd: tmp }); - - expect(result.isRepo).toBe(true); - expect(result.branches.length).toBeGreaterThan(0); - expect(result.branches.every((branch) => !branch.isRemote)).toBe(true); - expect(didFailRemoteBranches).toBe(true); - expect(didFailRemoteNames).toBe(true); - }), - ); - }); -}); diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts deleted file mode 100644 index 8f5c166d81..0000000000 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * RoutingTextGeneration – Dispatches text generation requests to either the - * Codex CLI or Claude CLI implementation based on the provider in each - * request input. - * - * When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to - * the Claude layer; for any other value (including the default `undefined`) it - * falls through to the Codex layer. - * - * @module RoutingTextGeneration - */ -import { Effect, Layer, Context } from "effect"; - -import { - TextGeneration, - type TextGenerationProvider, - type TextGenerationShape, -} from "../Services/TextGeneration.ts"; -import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; -import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; -import { CursorTextGenerationLive } from "./CursorTextGeneration.ts"; -import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts"; - -// --------------------------------------------------------------------------- -// Internal service tags so both concrete layers can coexist. -// --------------------------------------------------------------------------- - -class CodexTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/CodexTextGen", -) {} - -class ClaudeTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen", -) {} - -class CursorTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/CursorTextGen", -) {} - -class OpenCodeTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen", -) {} - -// --------------------------------------------------------------------------- -// Routing implementation -// --------------------------------------------------------------------------- - -const makeRoutingTextGeneration = Effect.gen(function* () { - const codex = yield* CodexTextGen; - const claude = yield* ClaudeTextGen; - const cursor = yield* CursorTextGen; - const openCode = yield* OpenCodeTextGen; - - const route = (provider?: TextGenerationProvider): TextGenerationShape => - provider === "claudeAgent" - ? claude - : provider === "opencode" - ? openCode - : provider === "cursor" - ? cursor - : codex; - - return { - generateCommitMessage: (input) => - route(input.modelSelection.provider).generateCommitMessage(input), - generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input), - generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input), - generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input), - } satisfies TextGenerationShape; -}); - -const InternalCodexLayer = Layer.effect( - CodexTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(CodexTextGenerationLive)); - -const InternalClaudeLayer = Layer.effect( - ClaudeTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(ClaudeTextGenerationLive)); - -const InternalCursorLayer = Layer.effect( - CursorTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(CursorTextGenerationLive)); - -const InternalOpenCodeLayer = Layer.effect( - OpenCodeTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(OpenCodeTextGenerationLive)); - -export const RoutingTextGenerationLive = Layer.effect( - TextGeneration, - makeRoutingTextGeneration, -).pipe( - Layer.provide(InternalCodexLayer), - Layer.provide(InternalClaudeLayer), - Layer.provide(InternalCursorLayer), - Layer.provide(InternalOpenCodeLayer), -); diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/git/Services/TextGeneration.ts deleted file mode 100644 index 78d37a0108..0000000000 --- a/apps/server/src/git/Services/TextGeneration.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * TextGeneration - Effect service contract for AI-generated Git content. - * - * Generates commit messages and pull request titles/bodies from repository - * context prepared by Git services. - * - * @module TextGeneration - */ -import { Context } from "effect"; -import type { Effect } from "effect"; -import type { ChatAttachment, ModelSelection } from "@t3tools/contracts"; - -import type { TextGenerationError } from "@t3tools/contracts"; - -/** Providers that support git text generation (commit messages, PR content, branch names). */ -export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode"; - -export interface CommitMessageGenerationInput { - cwd: string; - branch: string | null; - stagedSummary: string; - stagedPatch: string; - /** When true, the model also returns a semantic branch name for the change. */ - includeBranch?: boolean; - /** What model and provider to use for generation. */ - modelSelection: ModelSelection; -} - -export interface CommitMessageGenerationResult { - subject: string; - body: string; - /** Only present when `includeBranch` was set on the input. */ - branch?: string | undefined; -} - -export interface PrContentGenerationInput { - cwd: string; - baseBranch: string; - headBranch: string; - commitSummary: string; - diffSummary: string; - diffPatch: string; - /** What model and provider to use for generation. */ - modelSelection: ModelSelection; -} - -export interface PrContentGenerationResult { - title: string; - body: string; -} - -export interface BranchNameGenerationInput { - cwd: string; - message: string; - attachments?: ReadonlyArray | undefined; - /** What model and provider to use for generation. */ - modelSelection: ModelSelection; -} - -export interface BranchNameGenerationResult { - branch: string; -} - -export interface ThreadTitleGenerationInput { - cwd: string; - message: string; - attachments?: ReadonlyArray | undefined; - /** What model and provider to use for generation. */ - modelSelection: ModelSelection; -} - -export interface ThreadTitleGenerationResult { - title: string; -} - -export interface TextGenerationService { - generateCommitMessage( - input: CommitMessageGenerationInput, - ): Promise; - generatePrContent(input: PrContentGenerationInput): Promise; - generateBranchName(input: BranchNameGenerationInput): Promise; - generateThreadTitle(input: ThreadTitleGenerationInput): Promise; -} - -/** - * TextGenerationShape - Service API for commit/PR text generation. - */ -export interface TextGenerationShape { - /** - * Generate a commit message from staged change context. - */ - readonly generateCommitMessage: ( - input: CommitMessageGenerationInput, - ) => Effect.Effect; - - /** - * Generate pull request title/body from branch and diff context. - */ - readonly generatePrContent: ( - input: PrContentGenerationInput, - ) => Effect.Effect; - - /** - * Generate a concise branch name from a user message. - */ - readonly generateBranchName: ( - input: BranchNameGenerationInput, - ) => Effect.Effect; - - /** - * Generate a concise thread title from a user's first message. - */ - readonly generateThreadTitle: ( - input: ThreadTitleGenerationInput, - ) => Effect.Effect; -} - -/** - * TextGeneration - Service tag for commit and PR text generation. - */ -export class TextGeneration extends Context.Service()( - "t3/git/Services/TextGeneration", -) {} diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index 19b39bcf07..d693ab18ae 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -21,7 +21,10 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({ const makeRegistry = (now: () => number, httpServer = fakeHttpServer) => McpSessionRegistry.__testing - .make({ now }) + .make({ + now, + livenessWindowMs: 100, + }) .pipe( Effect.provideService(HttpServer.HttpServer, httpServer), Effect.provideService(ServerEnvironment.ServerEnvironment, fakeEnvironment), @@ -72,7 +75,7 @@ it.effect("builds MCP endpoints from the bound server host", () => }), ); -it.effect("keeps credentials valid until they are explicitly revoked", () => +it.effect("expires credentials once their session stops showing signs of life", () => Effect.gen(function* () { let timestamp = 1_000; const registry = yield* makeRegistry(() => timestamp); @@ -81,12 +84,7 @@ it.effect("keeps credentials valid until they are explicitly revoked", () => providerInstanceId: ProviderInstanceId.make("claude"), }); const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); - const resolved = yield* registry.resolve(token); - expect(resolved?.providerSessionId).toBe(issued.config.providerSessionId); - timestamp += 365 * 24 * 60 * 60 * 1_000; - expect(yield* registry.resolve(token)).toEqual(resolved); - - yield* registry.revokeProviderSession(issued.config.providerSessionId); + timestamp += 101; expect(yield* registry.resolve(token)).toBeUndefined(); }), ); diff --git a/apps/server/src/mcp/McpSessionRegistry.testkit.ts b/apps/server/src/mcp/McpSessionRegistry.testkit.ts index a5dc099310..1edbaac717 100644 --- a/apps/server/src/mcp/McpSessionRegistry.testkit.ts +++ b/apps/server/src/mcp/McpSessionRegistry.testkit.ts @@ -19,6 +19,7 @@ export const layer = Layer.succeed( }, }), resolve: () => Effect.succeed(undefined), + touch: () => Effect.void, revokeProviderSession: () => Effect.void, revokeThread: () => Effect.void, revokeAll: Effect.void, diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 5044963e04..39e7c59aac 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -21,7 +21,6 @@ export interface McpIssuedCredential { } export interface McpSessionRegistryShape { - /** Credentials have no time-based expiry and must be explicitly revoked by their owner. */ readonly issue: (request: McpCredentialRequest) => Effect.Effect; readonly resolve: ( rawToken: string, @@ -43,7 +42,9 @@ export class McpSessionRegistry extends Context.Service< >()("t3/mcp/McpSessionRegistry") {} interface CredentialRecord { + readonly tokenHash: string; readonly scope: McpInvocationContext.McpInvocationScope; + readonly lastAliveAt: number; } interface RegistryState { @@ -51,9 +52,26 @@ interface RegistryState { } export interface McpSessionRegistryOptions { + readonly livenessWindowMs?: number; readonly now?: () => number; } +/** + * How long a credential outlives the last sign of life from its provider + * session. + * + * Liveness is refreshed both by MCP traffic and by `touch` on every provider + * turn, so a session that is still doing work never expires no matter how long + * it goes between browser tool calls. This window therefore only bounds + * credentials whose session died without a clean stop — the normal paths + * (`stopSession`, `stopAll`) revoke eagerly and do not wait for it. + * + * The bound matters because `/mcp` is mounted outside the environment auth + * stack and is reachable on whatever host the server binds to, so this token is + * the only thing guarding the preview toolkit on a remote-reachable server. + */ +const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000; + const bytesToHex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); @@ -79,6 +97,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const httpServer = yield* HttpServer.HttpServer; const state = yield* SynchronizedRef.make({ records: new Map() }); const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis; + const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS; const endpoint = httpServer.address._tag === "TcpAddress" ? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp` @@ -89,6 +108,15 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( .digest("SHA-256", new TextEncoder().encode(token)) .pipe(Effect.map(bytesToHex), Effect.orDie); + const pruneDead = (records: ReadonlyMap, timestamp: number) => { + const next = new Map( + Array.from(records).filter( + ([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs, + ), + ); + return next.size === records.size ? records : next; + }; + const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")( function* (request) { const issuedAt = yield* currentTimeMillis; @@ -104,8 +132,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( issuedAt, }; yield* SynchronizedRef.update(state, ({ records }) => { - const next = new Map(records); - next.set(tokenHash, { scope }); + const next = new Map(pruneDead(records, issuedAt)); + next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt }); return { records: next }; }); return { @@ -125,8 +153,15 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( function* (rawToken) { if (rawToken.length === 0) return undefined; const tokenHash = yield* hashToken(rawToken); - const record = (yield* SynchronizedRef.get(state)).records.get(tokenHash); - return record?.scope; + const timestamp = yield* currentTimeMillis; + return yield* SynchronizedRef.modify(state, ({ records }) => { + const current = pruneDead(records, timestamp); + const record = current.get(tokenHash); + if (!record) return [undefined, { records: current }] as const; + const next = new Map(current); + next.set(tokenHash, { ...record, lastAliveAt: timestamp }); + return [record.scope, { records: next }] as const; + }); }, ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 88255b7d55..0a2705fe6c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -334,8 +334,10 @@ function runtimeModeRank(mode: RuntimeMode): number { return 0; case "auto-accept-edits": return 1; - case "full-access": + case "auto": return 2; + case "full-access": + return 3; } } diff --git a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts index 0fedf0b7a3..7066ecb915 100644 --- a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts @@ -16,6 +16,8 @@ import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as HostPowerMonitor from "../background/HostPowerMonitor.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; @@ -64,6 +66,10 @@ const serverSettingsLayer = ServerSettingsService.layerTest({ }, }, }); +const backgroundPolicyLayer = BackgroundPolicy.layer.pipe( + Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())), + Layer.provide(serverSettingsLayer), +); const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( Layer.provide( Layer.mergeAll( @@ -84,6 +90,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(serverConfigLayer), Layer.provide(serverSettingsLayer), Layer.provide(providerInstanceRegistryLayer), + Layer.provide(backgroundPolicyLayer), Layer.provide(NodeServices.layer), ); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 220c064895..161b2a6b38 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -27,10 +27,6 @@ import * as Deferred from "effect/Deferred"; import type * as Duration from "effect/Duration"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; -import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; -import * as Deferred from "effect/Deferred"; -import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; @@ -553,6 +549,21 @@ function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string return undefined; } +function rawProtocolRequest( + event: EffectAcpProtocol.AcpProtocolLogEvent, +): { readonly method?: unknown; readonly params?: unknown } | undefined { + if (event.stage !== "raw" || typeof event.payload !== "string") return undefined; + for (const line of event.payload.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed)); + if (typeof decoded === "object" && decoded !== null && "method" in decoded) { + return decoded; + } + } + return undefined; +} + const pollProtocolMethods = (events: Queue.Queue) => Effect.gen(function* () { const methods: string[] = []; @@ -1062,6 +1073,7 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -1265,6 +1277,7 @@ describe("AcpAdapterV2", () => { ); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -1313,6 +1326,7 @@ describe("AcpAdapterV2", () => { const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -1561,149 +1575,6 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, - ownDetachedProcessGroup: true, - protocolEvents, - }), - normalizeToolCall: normalizeXAiAcpToolCallState, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-empty-successful-bash"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-empty-successful-bash"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - - const statuses: string[] = []; - let runningStartedAt: DateTime.Utc | null = null; - let completedStartedAt: DateTime.Utc | null = null; - let completedAt: DateTime.Utc | null = null; - let completedInput: string | null = null; - let completedOutput: string | null | undefined; - let completedExitCode: number | null | undefined; - let runningProjectedExitCode: number | undefined = undefined; - let terminal = false; - while (!terminal) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-empty-success-1" - ) { - statuses.push(event.turnItem.status); - if (event.turnItem.status === "running") { - runningStartedAt ??= event.turnItem.startedAt; - if (event.turnItem.type === "command_execution") { - runningProjectedExitCode = event.turnItem.exitCode; - } - } - if (event.turnItem.status === "completed") { - completedStartedAt = event.turnItem.startedAt; - completedAt = event.turnItem.completedAt; - if (event.turnItem.type === "command_execution") { - completedInput = event.turnItem.input; - completedOutput = event.turnItem.output; - completedExitCode = event.turnItem.exitCode; - } - } - } - if (event.type === "turn.terminal") terminal = true; - } - - assert.deepEqual(statuses, ["running", "running", "completed"]); - assert.deepEqual(completedStartedAt, runningStartedAt); - assert.isNotNull(completedAt); - assert.equal(completedInput, "true"); - assert.equal(completedOutput, undefined); - assert.equal( - runningProjectedExitCode, - undefined, - "mid-stream exit_code must not project until the tool is terminal", - ); - assert.equal(completedExitCode, 0); - - yield* Queue.takeAll(protocolEvents); - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: secondProviderTurnId, - requestRuntimeRestart: true, - }); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 3 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/load", - ), - Stream.runHead, - ); - assert.isTrue(Option.isSome(loadAfterRestart)); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect("cancels pending permission requests while interrupting an ACP turn", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const releaseCancel = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -2855,1072 +2726,6 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(testLayer), Effect.scoped), ); - it.live("keeps hard teardown excluded until a permission response is enqueued", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-response-wins-permission"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-response-wins-permission"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.forkScoped); - yield* Deferred.await(responseEnqueued); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(responseFiber.pollUnsafe()); - assert.isUndefined(interruptFiber.pollUnsafe()); - - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(responseFiber); - yield* Fiber.join(interruptFiber); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("correlates reordered elicitation schemas through the completed stdout write", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseWritten = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-reordered-elicitation"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_ELICITATION: "1" }, - wrapIncomingRequest: (onIncomingRequest) => (requestId, method, payload) => { - if (method !== "session/elicitation") { - return onIncomingRequest(requestId, method, payload); - } - const record = payload as Record; - return onIncomingRequest(requestId, method, { - ...record, - requestedSchema: { - properties: { - approved: { title: "Approved", type: "boolean" }, - }, - type: "object", - }, - }); - }, - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseWritten, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-reordered-elicitation"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-reordered-elicitation"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if (pending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected a pending elicitation request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: pending.runtimeRequest.id, - answers: { approved: ["true"] }, - }) - .pipe(Effect.forkScoped); - - yield* Deferred.await(responseWritten); - assert.isUndefined(responseFiber.pollUnsafe()); - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(responseFiber); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("fails a held native response acknowledgement before normal session close", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseWritten = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const responseLifecycle: Array = []; - const instanceId = ProviderInstanceId.make("acp-test-normal-close-held-response"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseWritten, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - testHooks: { - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-normal-close-held-response"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-normal-close-held-response", - ), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if (pending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(responseWritten); - - const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped); - while (!responseLifecycle.includes("failed")) { - yield* Effect.yieldNow; - } - const responseExit = yield* Fiber.join(responseFiber); - if (Exit.isSuccess(responseExit)) { - assert.fail("normal close must fail a response whose transport acknowledgement is held"); - } - assert.include(Cause.pretty(responseExit.cause), "ACP session transport closed"); - assert.include(responseLifecycle, "removed"); - assert.include(responseLifecycle, "failed"); - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(closeFiber); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("rejects delayed native response registration when normal close wins the permit", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const registrationStarted = yield* Deferred.make(); - const releaseRegistration = yield* Deferred.make(); - const transportClosed = yield* Deferred.make(); - const releaseTransportClose = yield* Deferred.make(); - const responseLifecycle: Array = []; - const instanceId = ProviderInstanceId.make("acp-test-close-wins-registration"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - }), - }, - fileSystem, - idAllocator, - serverConfig, - testHooks: { - afterNativeResponseTransportClosed: () => - Deferred.succeed(transportClosed, undefined).pipe( - Effect.andThen(Deferred.await(releaseTransportClose)), - ), - beforeNativeResponseAdmissionCheck: () => - Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - ), - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-close-wins-registration"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-close-wins-registration"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if (pending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(registrationStarted); - - const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped); - yield* Deferred.await(transportClosed); - yield* Deferred.succeed(releaseRegistration, undefined); - while (!responseLifecycle.includes("admission_rejected")) { - yield* Effect.yieldNow; - } - const responseExit = yield* Fiber.join(responseFiber); - if (Exit.isSuccess(responseExit)) { - assert.fail("normal close must reject a response delayed before transport registration"); - } - assert.include(Cause.pretty(responseExit.cause), "ACP session transport closed"); - assert.equal(responseLifecycle.filter((event) => event === "registered").length, 1); - assert.equal(responseLifecycle.filter((event) => event === "removed").length, 1); - assert.equal(responseLifecycle.filter((event) => event === "admission_rejected").length, 1); - yield* Deferred.succeed(releaseTransportClose, undefined); - yield* Fiber.join(closeFiber); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("bounds a missing pending permission response acknowledgement", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const responseLifecycle: Array = []; - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test-pending-response-timeout"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_TOOL_CALLS: "1", - T3_ACP_HANG_AFTER_PERMISSION: "1", - }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - protocolEvents, - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - testHooks: { - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-pending-response-timeout"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-pending-response-timeout", - ), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - yield* pollProtocolMethods(protocolEvents); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending permission request"); - } - const responseExit = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.exit); - if (Exit.isSuccess(responseExit)) { - assert.fail("missing native response acknowledgement must fail the pending response"); - } - assert.include(Cause.pretty(responseExit.cause), "Native response acknowledgement timed out"); - assert.isTrue(yield* Deferred.isDone(responseEnqueued)); - assert.isFalse(yield* Deferred.isDone(releaseNativeHook)); - assert.isBelow(responseLifecycle.indexOf("removed"), responseLifecycle.indexOf("failed")); - assert.includeMembers(responseLifecycle, [ - "registered", - "removed", - "failed", - "timer_exited", - "timer_started", - "watcher_exited", - "watcher_started", - ]); - - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }); - assert.isTrue(yield* Deferred.isDone(releaseNativeHook)); - yield* Effect.sleep("50 millis"); - assert.include(responseLifecycle, "late_noop"); - yield* Scope.close(sessionScope, Exit.void); - assert.notInclude(yield* pollProtocolMethods(protocolEvents), "session/close"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("defers caller cancellation until a pending response acknowledgement is bounded", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-pending-response-cancel"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_TOOL_CALLS: "1", - T3_ACP_HANG_AFTER_PERMISSION: "1", - }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-pending-response-cancel"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-pending-response-cancel"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.forkScoped); - yield* Deferred.await(responseEnqueued); - const cancellationFiber = yield* Fiber.interrupt(responseFiber).pipe(Effect.forkScoped); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.sleep("100 millis"); - assert.isUndefined(cancellationFiber.pollUnsafe()); - assert.isUndefined(interruptFiber.pollUnsafe()); - assert.isFalse(yield* Deferred.isDone(releaseNativeHook)); - - yield* Fiber.join(cancellationFiber); - yield* Fiber.join(interruptFiber); - assert.isTrue(yield* Deferred.isDone(releaseNativeHook)); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("waits for immediate allow and deny permission responses before hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - - for (const [name, sandboxPolicy] of [ - ["allow", undefined], - ["deny", { type: "readOnly" } as const], - ] as const) { - yield* Effect.gen(function* () { - const responseEnqueued = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make(`acp-test-${name}`); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make(`thread-acp-immediate-permission-${name}`); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - approvalPolicy: "never", - cwd: process.cwd(), - ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - `provider-session-acp-immediate-permission-${name}`, - ), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }), - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(interruptFiber.pollUnsafe()); - - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.scoped); - } - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("waits for immediate URL elicitation responses before hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-url-elicitation"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_URL_ELICITATION: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-immediate-url-elicitation"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-immediate-url-elicitation"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }), - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(interruptFiber.pollUnsafe()); - - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("bounds a missing immediate response acknowledgement before hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-missing-response-ack"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-missing-response-ack"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - approvalPolicy: "never", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-missing-response-ack"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const startedAt = yield* Clock.currentTimeMillis; - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }), - requestRuntimeRestart: true, - }); - assert.isAtLeast((yield* Clock.currentTimeMillis) - startedAt, 1_500); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("rejects an elicitation response when hard teardown wins admission", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_ELICITATION: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-teardown-wins-elicitation"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-teardown-wins-elicitation"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending elicitation request"); - } - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: pending.runtimeRequest.id, - answers: { approved: ["true"] }, - }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(responseFiber.pollUnsafe()); - - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(interruptFiber); - const responseExit = yield* Fiber.join(responseFiber); - if (Exit.isSuccess(responseExit)) { - assert.fail("teardown winning admission must reject the elicitation response"); - } - assert.include(Cause.pretty(responseExit.cause), "No pending ACP runtime request"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - it.effect("releases an ACP turn when cancellation times out", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -3934,6 +2739,7 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test"); const protocolEvents = yield* Queue.bounded(256); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -10122,4088 +8928,6 @@ describe("AcpAdapterV2", () => { assert.isFalse(staleEventSeen, "interrupted runtime events must not attach to attempt 2"); }).pipe(Effect.provide(testLayer), Effect.scoped), ); - - it.live("treats a second hard Stop as success when the turn is already gone", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: false, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-double-stop"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now })) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }); - // Second durable interrupt after activeTurn is cleared must not fail. - const second = yield* Effect.exit( - runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }), - ); - assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent"); - let terminal: string | null = null; - while (terminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminal = event.status; - } - } - assert.equal(terminal, "interrupted"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect("finalizes a settled turn held open for background work when interrupted", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId === "tool-call-generic-1" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : undefined, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-interrupt-background-hold"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-interrupt-background"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - 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; - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "carries a live subagent lineage across an interrupt so the next turn can complete it", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : // Hydration-only shape (empty prompt, null title): without a - // carried-over lineage this update is dropped and the item - // stays running forever. - { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-subagent-carryover"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-subagent-carryover"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - 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; - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "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); - - let subagentTurnItemId: string | null = null; - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); - - subagentPhase = "complete"; - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - carriedItemStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(carriedItemStatus, "completed"); - assert.equal(secondTerminalStatus, "completed"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "preserveRuntimeOnSettledInterrupt keeps the process alive and carries subagents through a settled steering interrupt", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - // Hard interrupt flags (stricter than production Grok, which no - // longer sets restartRuntimeOnEveryInterrupt): every interrupt - // would hard-kill the process group without the settled-soft gate - // under test. - restartRuntimeAfterInterrupt: true, - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - // No ownDetachedProcessGroup: if the interrupt wrongly takes the - // hard path, terminateProcessGroup is missing and the interrupt - // fails loudly with a poisoned session. - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; - }, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-settled-soft-steer"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-settled-soft-steer"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - // 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; - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "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); - assert.isFalse( - cancelCalled, - "settled soft steer must not send session/cancel (the real Grok CLI kills background subagents on cancel)", - ); - - let subagentTurnItemId: string | null = null; - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); - - subagentPhase = "complete"; - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - // Same runtime process (mock-session-1): a respawn would start - // mock-session-2 and drop the carryover on the session mismatch. - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - carriedItemStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(carriedItemStatus, "completed"); - assert.equal(secondTerminalStatus, "completed"); - assert.equal( - runtimeOrdinalSeen, - 1, - "settled soft steer must not respawn the ACP runtime process", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("preserveRuntimeOnSettledInterrupt does not soften a mid-prompt steering interrupt", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - // Local hard-flavor gate: production Grok no longer sets - // restartRuntimeOnEveryInterrupt, but when a flavor does, the - // settled-soft gate must not leak onto an unsettled prompt. - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - // No ownDetachedProcessGroup: the expected hard path fails loudly - // on the missing terminateProcessGroup, proving the settled-soft - // gate did not apply to an unsettled prompt. - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-unsettled-steer-stays-hard"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-unsettled-steer-stays-hard", - ), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const interruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId }) - .pipe(Effect.exit); - if (Exit.isSuccess(interruptExit)) { - assert.fail("mid-prompt steering interrupt must still take the hard teardown path"); - } - assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live( - "soft mid-prompt interrupt cancels in place, reuses the runtime, and tracks cancel-backgrounded work", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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"); - let cancelCalled = false; - let runtimeOrdinalSeen = 0; - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - // Production Grok interrupt flags: hard teardown only with - // requestRuntimeRestart (user Stop). Without - // restartRuntimeOnEveryInterrupt a mid-prompt steering interrupt - // stays soft: session/cancel, same process, session reuse. - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: ({ runtime: extensionRuntime, applyBackgroundTaskMutation }) => - registerXAiBackgroundTaskTracking(extensionRuntime, applyBackgroundTaskMutation), - // No ownDetachedProcessGroup: if the interrupt wrongly takes the - // hard path, terminateProcessGroup is missing and the interrupt - // fails loudly with a poisoned session. - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT: "1", - T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL: "1", - }; - }, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-soft-mid-prompt-steer"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-soft-mid-prompt-steer"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - // Wait for the running command tool so the interrupt lands mid-prompt. - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("tool-call-running-1"), - ), - Stream.runHead, - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - // No requestRuntimeRestart: a steering interrupt, not a user Stop. - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - assert.isTrue( - cancelCalled, - "soft mid-prompt interrupt must send session/cancel to detach the running work", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - // The cancel handler emitted _x.ai/task_backgrounded for the detached - // command; the tracked task must report as pending background work. - let backgroundTracked = false; - for (let attempt = 0; attempt < 80 && !backgroundTracked; attempt += 1) { - backgroundTracked = yield* hasPendingBackgroundWork; - if (!backgroundTracked) { - yield* Effect.sleep("25 millis"); - } - } - assert.isTrue( - backgroundTracked, - "cancel-backgrounded task must be tracked as running background work", - ); - - // The second prompt reuses the same process and session. - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(secondTerminalStatus, "completed"); - assert.equal( - runtimeOrdinalSeen, - 1, - "soft mid-prompt interrupt must not respawn the ACP runtime process", - ); - - // _x.ai/task_completed lands ~1.2s after the cancel and clears the - // tracked task without opening a synthetic continuation run. - let backgroundPending = true; - for (let attempt = 0; attempt < 50 && backgroundPending; attempt += 1) { - backgroundPending = yield* hasPendingBackgroundWork; - if (backgroundPending) { - yield* Effect.sleep("100 millis"); - } - } - assert.isFalse( - backgroundPending, - "tracked background task must clear after _x.ai/task_completed", - ); - assert.lengthOf( - continuationRequests, - 0, - "a cancel-backgrounded task completion must not wake a synthetic continuation run", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("direct Stop quarantine drops late background task mutations from the stopped run", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - ownDetachedProcessGroup: true, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-stop-quarantine-late-task"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-stop-quarantine-late-task"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - // Plumbing sanity: pre-Stop mutations on the root session track and - // clear pending background work through the extension callback. - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-pre-stop", - status: "running", - }); - assert.isTrue( - yield* hasPendingBackgroundWork, - "a running background task mutation on the root session must track before Stop", - ); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-pre-stop", - status: "completed", - }); - assert.isFalse( - yield* hasPendingBackgroundWork, - "a completed background task mutation must clear pending background work", - ); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - - // Residual lifecycle from the stopped run: activeSessionId still points - // at the stopped session until the next turn respawns the runtime, so - // only the direct Stop quarantine stands between this mutation and the - // wake machinery. - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-late-after-stop", - status: "running", - }); - assert.isFalse( - yield* hasPendingBackgroundWork, - "direct Stop quarantine must drop residual background task mutations from the stopped run", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("production Grok interrupt flags still hard-kill and respawn on user Stop", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 runtimeOrdinalSeen = 0; - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - // The full production Grok interrupt flag set after the non-Stop - // softening: no restartRuntimeOnEveryInterrupt. User Stop - // (requestRuntimeRestart) must still take the hard teardown and - // respawn path, not the soft cancel path. - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: ({ runtime: extensionRuntime, applyBackgroundTaskMutation }) => - registerXAiBackgroundTaskTracking(extensionRuntime, applyBackgroundTaskMutation), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - // Only hang the interrupted first turn. The replacement process must - // complete normally so startTurn / session-load assertions can finish. - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, - ownDetachedProcessGroup: true, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-production-stop-hard-kill"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-production-stop-hard-kill"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - - // Effect 4 Queue.takeAll waits for at least one element when empty. After - // the session/prompt stream drain the protocol queue is often empty, so - // takeAll would hang forever. Use clear (non-blocking drain) instead so - // the session/load wait cannot match residual pre-restart traffic. - yield* Queue.clear(protocolEvents); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/load", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "user Stop must respawn the runtime and reload the session on the next turn", - ); - assert.equal( - runtimeOrdinalSeen, - 2, - "user Stop with production Grok flags must replace the ACP runtime process", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - // it.live: ownDetachedProcessGroup teardown uses wall-clock sleeps; under - // it.effect the interrupt timeout on context.completed still needs real time - // after the soft steer clears the turn. - it.live( - "Stop after settled soft steer contains the orphan runtime and respawns without subagent carryover", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 childSessionId = "mock-child-session-1"; - const streamedSubagentText = "streamed subagent carryover text"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - // Production Grok interrupt flags: soft settle keeps the process; - // only requestRuntimeRestart (user Stop) hard-kills. - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; - }, - ownDetachedProcessGroup: true, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-stop-after-soft-steer-orphan"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-stop-after-soft-steer-orphan", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - 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; - - // Stream assistant text onto the carryover subagent while the deferred - // turn is still active so assistantText races ahead of task.result. - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: streamedSubagentText }, - }, - }); - let subagentTurnItemId: string | null = null; - let streamedTextSeen = false; - for (let attempt = 0; attempt < 64; attempt += 1) { - const maybeEvent = yield* Queue.take(events).pipe(Effect.timeoutOption("50 millis")); - if (Option.isNone(maybeEvent)) break; - const event = maybeEvent.value; - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if ( - event.type === "message.updated" && - event.message.text.includes(streamedSubagentText) - ) { - streamedTextSeen = true; - break; - } - } - assert.isTrue( - streamedTextSeen, - "pre-steer child session chunk must project as subagent assistant text", - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - // Soft steer first: clears the turn, leaves the process alive. - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - assert.isFalse( - cancelCalled, - "settled soft steer must not send session/cancel before the later Stop", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); - assert.equal( - runtimeOrdinalSeen, - 1, - "soft steer must leave the original ACP runtime process alive", - ); - - // User Stop against the already-cleared turn: contain the orphan runtime. - const stopExit = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.exit); - if (Exit.isFailure(stopExit)) { - assert.fail( - `cleared-turn Stop must contain the orphan runtime, not fail: ${Cause.pretty(stopExit.cause)}`, - ); - } - - // Orphan Stop must terminalize carried-over subagents (soft steer left them - // running on purpose; quarantine alone would leave them stuck "running"). - let subagentStopStatus: string | null = null; - let subagentStopResult: string | null | undefined; - let subagentStopProviderThreadId: string | null | undefined; - let subagentUpdatedResult: string | null | undefined; - for (let attempt = 0; attempt < 64; attempt += 1) { - const maybeEvent = yield* Queue.take(events).pipe(Effect.timeoutOption("50 millis")); - if (Option.isNone(maybeEvent)) break; - const event = maybeEvent.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - subagentStopStatus = event.turnItem.status; - subagentStopResult = event.turnItem.result; - subagentStopProviderThreadId = event.turnItem.providerThreadId; - if (subagentStopStatus === "interrupted") break; - } - if ( - event.type === "subagent.updated" && - event.subagent.status === "interrupted" && - event.subagent.result === streamedSubagentText - ) { - subagentUpdatedResult = event.subagent.result; - } - } - assert.equal( - subagentStopStatus, - "interrupted", - "orphan Stop must emit interrupted terminal for turn-1 carryover subagent", - ); - assert.equal( - subagentStopResult, - streamedSubagentText, - "orphan Stop must merge streamed assistantText into the interrupted result", - ); - assert.equal( - subagentStopProviderThreadId, - providerThread.id, - "orphan Stop parent-level events must use the spawn-time parent provider thread id", - ); - assert.equal( - subagentUpdatedResult, - streamedSubagentText, - "orphan Stop subagent.updated must also carry the streamed result", - ); - - yield* Queue.clear(protocolEvents); - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && - (rawProtocolMethod(event) === "session/load" || - rawProtocolMethod(event) === "session/new"), - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "orphan containment must force a runtime respawn before the next turn", - ); - assert.equal( - runtimeOrdinalSeen, - 2, - "Stop after soft steer must replace the orphan ACP runtime process", - ); - - // nativeTurnId is `${sessionId}:turn:${ordinal}`. The mock always uses - // mock-session-1; ordinal 2 yields turn:2 on the replacement process. - // Carryover was quarantined by Stop, so turn-1's subagent must not re-attach. - subagentPhase = "complete"; - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - carriedItemStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.isNull( - carriedItemStatus, - "Stop quarantine must drop turn-1 subagent carryover on the respawned runtime", - ); - assert.equal(secondTerminalStatus, "completed"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "settled soft interrupt skips cancel when prompt wire is settled before completion callback", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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; - const promptPhases: Array = []; - // Gate adapter-visible prompt return so we can open the race window after - // the native stopReason is on the wire. Release lets Effect.tap mark - // promptWireSettled before the completion callback requests the permit; - // interrupt then ORs wire-done with promptSettled under the permit. - const promptWireReturned = yield* Deferred.make(); - const releasePromptCompletion = yield* Deferred.make(); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - // Production Grok flags: without settled-soft, a steer soft-cancels. - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - wrapRuntime: (runtime) => ({ - ...runtime, - prompt: (payload) => - Effect.gen(function* () { - promptPhases.push("prompt-start"); - const result = yield* runtime.prompt(payload); - promptPhases.push("wire-returned"); - yield* Deferred.succeed(promptWireReturned, undefined); - yield* Deferred.await(releasePromptCompletion); - promptPhases.push("completion-released"); - return result; - }), - }), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-settled-soft-admission-race"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-settled-soft-admission-race", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptWireReturned); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - assert.deepEqual(promptPhases, ["prompt-start", "wire-returned"]); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - // Fork interrupt while the adapter-side return is still gated. Release so - // promptWireSettled completes (Effect.tap) before/while the completion - // callback contends for runtimeCallbackPermit. Holding the gate forever - // would also block the wire signal (same Effect resolution), so release - // is required; the assertion is cancel skipped after that race window. - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* Deferred.succeed(releasePromptCompletion, undefined); - for (let attempt = 0; attempt < 20; attempt += 1) { - if (promptPhases.includes("completion-released")) break; - yield* Effect.yieldNow; - } - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - - assert.includeMembers(promptPhases, [ - "prompt-start", - "wire-returned", - "completion-released", - ]); - assert.isFalse( - cancelCalled, - "settled soft steer must skip session/cancel once the prompt wire has settled", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.equal(subagentPhase, "spawn"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "does not pin hasPendingBackgroundWork when a late TaskOutput re-reports an in-turn-handled task", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-1" - ? [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ] - : [], - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1", - }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-already-handled-wake-pin"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-already-handled-wake-pin", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - - // Wait for the late post-finalize duplicate TaskOutput frame. - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("MONITOR_LISTING_TOKEN_LATE"), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - assert.lengthOf( - continuationRequests, - 0, - "already-handled late TaskOutput must not open a continuation run", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "wake buffer must not stay non-empty and pin idle release after an already-handled re-report", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "holds a settled turn until the injected monitor report streams instead of finalizing into it", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const triggerDir = yield* fileSystem.makeTempDirectoryScoped(); - const triggerPath = path.join(triggerDir, "report-trigger"); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundToolMutation: (text) => - text.includes('Monitor "task-monitor-1" ended') - ? [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }] - : [], - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-1" - ? [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ] - : [], - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW: "1", - T3_ACP_INJECTED_REPORT_TRIGGER_PATH: triggerPath, - }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-injected-report-hold"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-injected-report"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - - // Wait (real time) until the post-settle end notice and TaskOutput - // hydration are ingested: the hydrated monitor card carries the - // fetched listing. - let reportSeen = false; - const trackReport = (event: ProviderAdapterV2Event): void => { - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text.includes("MONITOR_REPORT_TOKEN") - ) { - reportSeen = true; - } - }; - let hydrated = false; - while (!hydrated) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "completed" && - (event.turnItem.output ?? "").includes("MONITOR_LISTING_TOKEN") - ) { - hydrated = true; - } - } - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - // Pre-fix the 2s deferred-finalize debounce fires here and the report - // streamed by the injected turn afterwards is dropped on the floor. - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - let drained = yield* Queue.poll(events); - while (Option.isSome(drained)) { - trackReport(drained.value); - assert.notEqual( - drained.value.type, - "turn.terminal", - "deferred finalize must hold while the injected-turn report is owed", - ); - drained = yield* Queue.poll(events); - } - - // Release the report, then the normal debounce finalizes the turn. - yield* fileSystem.writeFileString(triggerPath, "go"); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("MONITOR_REPORT_TOKEN"), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* TestClock.adjust("3 seconds"); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - trackReport(event); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.isTrue( - reportSeen, - "the injected-turn report must project before the turn finalizes", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect("restarts the ACP child process before the next prompt after interrupt", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-restart-after-interrupt"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-restart-after-interrupt"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: `${providerThread.nativeThreadRef?.nativeId}:turn:1`, - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/cancel", - ), - Stream.runHead, - ); - - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/load", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "post-interrupt startTurn should respawn the runtime and replay session/load", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect("Windows teardown is one-shot explicitly with independent finalizer cleanup", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const runtimeScope = yield* Scope.make(); - const taskkillCommands: Array<{ - readonly command: string; - readonly args: ReadonlyArray; - }> = []; - const taskkillSpawner = makeTaskkillSpawner({ exitCode: 0, commands: taskkillCommands }); - const spawner = ChildProcessSpawner.make((command) => { - const value = command as unknown as { readonly command: string }; - return value.command === "taskkill" - ? taskkillSpawner.spawn(command) - : childProcessSpawner.spawn(command); - }); - const context = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: process.cwd(), - env: { T3_ACP_SESSION_LIFECYCLE: "1" }, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-acp-test", version: "0.0.0" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))), - ).pipe(Effect.provideService(Scope.Scope, runtimeScope)); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(context), - ); - assert.isDefined(runtime.terminateProcessGroup); - yield* Effect.all([runtime.terminateProcessGroup!, runtime.terminateProcessGroup!], { - concurrency: "unbounded", - }); - assert.equal(taskkillCommands.length, 1); - yield* Scope.close(runtimeScope, Exit.void); - assert.equal(taskkillCommands.length, 1); - }).pipe(Effect.provide(testLayer)), - ); - - it("accepts only taskkill exit code zero as successful tree termination", () => { - assert.isTrue(AcpSessionRuntime.windowsTaskkillResultIsSuccess(0, "")); - assert.isFalse( - AcpSessionRuntime.windowsTaskkillResultIsSuccess( - 128, - "FEHLER: Der Prozess wurde nicht gefunden.", - ), - ); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(128, "")); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(1, "localized failure")); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(255, "")); - }); - - it.effect("runs the default taskkill path and preserves every failure mode", () => - Effect.gen(function* () { - const commands: Array<{ readonly command: string; readonly args: ReadonlyArray }> = - []; - yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill( - makeTaskkillSpawner({ exitCode: 0, commands }), - 4321, - ); - assert.deepEqual(commands, [{ command: "taskkill", args: ["/PID", "4321", "/T", "/F"] }]); - - for (const fixture of [ - { exitCode: 128, output: 'ERROR: The process "4321" not found.' }, - { exitCode: 128, output: "FEHLER: Prozess nicht gefunden." }, - { exitCode: 128, output: "" }, - { exitCode: 128, output: "ERROR: Access is denied." }, - { exitCode: 1, output: "generic failure" }, - ]) { - const failed = yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill( - makeTaskkillSpawner(fixture), - 4321, - ).pipe(Effect.exit); - if (Exit.isSuccess(failed)) assert.fail(`taskkill ${fixture.exitCode} must fail`); - const error = Cause.squash(failed.cause); - assert.instanceOf(error, AcpSessionRuntime.AcpProcessGroupTerminationError); - const termination = error as AcpSessionRuntime.AcpProcessGroupTerminationError; - assert.equal( - termination.detail, - `taskkill exited ${fixture.exitCode} for ACP process tree 4321`, - ); - assert.equal(termination.pid, 4321); - assert.equal(termination.exitCode, fixture.exitCode); - if (fixture.output.length > 0) { - assert.equal(termination.cause, fixture.output); - } - } - - for (const fixture of [ - { spawnFailure: true }, - { outputFailure: true }, - { exitFailure: true }, - ]) { - const failed = yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill( - makeTaskkillSpawner(fixture), - 4321, - ).pipe(Effect.exit); - if (Exit.isSuccess(failed)) assert.fail("taskkill infrastructure failure must fail"); - const error = Cause.squash(failed.cause); - assert.instanceOf(error, AcpSessionRuntime.AcpProcessGroupTerminationError); - assert.equal( - (error as AcpSessionRuntime.AcpProcessGroupTerminationError).detail, - "Failed to run taskkill for ACP process tree 4321", - ); - } - }), - ); - - it.effect("Windows process-tree teardown surfaces taskkill failure", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const context = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn: { command: process.execPath, args: [mockAgentPath], cwd: process.cwd() }, - cwd: process.cwd(), - clientInfo: { name: "t3-acp-test", version: "0.0.0" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Effect.fail( - new AcpSessionRuntime.AcpProcessGroupTerminationError({ - detail: "mock taskkill failure", - }), - ), - }).pipe( - Layer.provide( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - ), - ), - ); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(context), - ); - const error = yield* Effect.flip(runtime.terminateProcessGroup!); - assert.equal(error.detail, "mock taskkill failure"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("poisons the session when hard teardown defects and blocks replacement work", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-failed-teardown-command-", - }); - const residualCallbackDir = yield* fileSystem.makeTempDirectoryScoped(); - const residualCallbackResponseLogPath = path.join(residualCallbackDir, "responses.log"); - const residualCallbackTriggerPath = path.join(residualCallbackDir, "trigger"); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = []; - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let terminatorCallCount = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Effect.gen(function* () { - terminatorCallCount += 1; - yield* Deferred.succeed(teardownStarted, undefined); - yield* Deferred.await(releaseTeardown); - return yield* Effect.die("mock taskkill defect"); - }), - environment: { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH: residualCallbackResponseLogPath, - T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH: residualCallbackTriggerPath, - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-failed-hard-teardown"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-failed-hard-teardown"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - const adapterEvents = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(adapterEvents, event)), - Effect.forkIn(sessionScope), - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - while ((yield* fileSystem.readFileString(commandPidPath)).trim().length === 0) { - yield* Effect.yieldNow; - } - const [commandRootPid, commandSleepPid] = (yield* fileSystem.readFileString(commandPidPath)) - .trim() - .split(/\s+/) - .map(Number); - assert.isTrue( - Option.isSome(yield* waitForProcesses([commandRootPid!, commandSleepPid!])), - "declared failed-teardown Bash and sleep PIDs must both become live", - ); - yield* pollProtocolMethods(protocolEvents); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const startFiber = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.exit, Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(startFiber.pollUnsafe()); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - yield* Deferred.succeed(releaseTeardown, undefined); - assert.notInclude(methodsDuringTeardown, "session/load"); - assert.notInclude(methodsDuringTeardown, "session/prompt"); - - const interruptExit = yield* Fiber.join(interruptFiber); - if (Exit.isSuccess(interruptExit)) assert.fail("hard teardown failure must fail interrupt"); - assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - assert.isTrue( - Option.isSome(yield* waitForProcesses([commandRootPid!, commandSleepPid!])), - "failed teardown must leave both declared Bash and sleep PIDs live", - ); - - while (Option.isSome(yield* Queue.poll(adapterEvents))) { - // Discard the interrupted turn's expected projection before residual traffic. - } - yield* fileSystem.writeFileString(residualCallbackTriggerPath, "go"); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"method":"session/elicitation"'), - ), - Stream.runHead, - ); - yield* Effect.sleep("100 millis"); - assert.isTrue( - Option.isNone(yield* Queue.poll(adapterEvents)), - "residual callbacks must not mutate or emit adapter projection after poison", - ); - assert.isFalse( - yield* fileSystem.exists(residualCallbackResponseLogPath), - "permission and elicitation callbacks must remain unresolved after poison", - ); - assert.lengthOf( - continuationRequests, - 0, - "residual callbacks must not offer a continuation after poison", - ); - - const startExit = yield* Fiber.join(startFiber); - if (Exit.isSuccess(startExit)) assert.fail("poisoned session must reject startTurn"); - assert.include(Cause.pretty(startExit.cause), "session is poisoned"); - const resumeExit = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.exit); - if (Exit.isSuccess(resumeExit)) assert.fail("poisoned session must reject resumeThread"); - assert.include(Cause.pretty(resumeExit.cause), "session is poisoned"); - const snapshotExit = yield* runtime.readThreadSnapshot({ providerThread }).pipe(Effect.exit); - if (Exit.isSuccess(snapshotExit)) { - assert.fail("poisoned session must reject readThreadSnapshot"); - } - assert.include(Cause.pretty(snapshotExit.cause), "session is poisoned"); - const forkExit = yield* runtime - .forkThread({ - sourceProviderThread: providerThread, - targetThreadId: ThreadId.make("thread-acp-poisoned-fork"), - }) - .pipe(Effect.exit); - if (Exit.isSuccess(forkExit)) assert.fail("poisoned session must reject forkThread"); - assert.include(Cause.pretty(forkExit.cause), "session is poisoned"); - yield* pollProtocolMethods(protocolEvents); - const retryInterruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit); - if (Exit.isSuccess(retryInterruptExit)) { - assert.fail("poisoned session must reject a repeated hard interrupt"); - } - const firstInterruptError = Cause.squash(interruptExit.cause) as Error; - const retryInterruptError = Cause.squash(retryInterruptExit.cause) as Error; - assert.strictEqual(retryInterruptError.cause, firstInterruptError.cause); - assert.equal(terminatorCallCount, 1); - const methodsAfterPoison = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsAfterPoison, "initialize"); - assert.notInclude(methodsAfterPoison, "session/cancel"); - assert.notInclude(methodsAfterPoison, "session/fork"); - assert.notInclude(methodsAfterPoison, "session/load"); - assert.notInclude(methodsAfterPoison, "session/prompt"); - assert.isTrue(processExists(commandRootPid!)); - assert.isTrue(processExists(commandSleepPid!)); - yield* Scope.close(sessionScope, Exit.void); - assert.isTrue( - Option.isSome(yield* waitForProcessesToExit([commandRootPid!, commandSleepPid!])), - "finalizer cleanup must reap both declared Bash and sleep PIDs", - ); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); - const finalizerMethods = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(finalizerMethods, "session/close"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("durably poisons start and resume when required hard teardown is unavailable", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-missing-hard-teardown"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-missing-hard-teardown"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const interruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit); - if (Exit.isSuccess(interruptExit)) assert.fail("missing hard teardown must fail interrupt"); - assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - - const startExit = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.exit); - if (Exit.isSuccess(startExit)) assert.fail("poisoned session must reject startTurn"); - assert.include(Cause.pretty(startExit.cause), "session is poisoned"); - const resumeExit = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.exit); - if (Exit.isSuccess(resumeExit)) assert.fail("poisoned session must reject resumeThread"); - assert.include(Cause.pretty(resumeExit.cause), "session is poisoned"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("holds concurrent startTurn behind successful hard teardown and reloads once", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let runtimeOrdinalSeen = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - ), - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-concurrent-hard-teardown"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-concurrent-hard-teardown"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - yield* pollProtocolMethods(protocolEvents); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const startFiber = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(startFiber.pollUnsafe()); - assert.equal(runtimeOrdinalSeen, 1); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsDuringTeardown, "session/load"); - assert.notInclude(methodsDuringTeardown, "session/prompt"); - - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.join(startFiber); - assert.equal(runtimeOrdinalSeen, 2); - const replacementMethods = yield* pollProtocolMethods(protocolEvents); - assert.equal(replacementMethods.filter((method) => method === "session/load").length, 1); - if (!replacementMethods.includes("session/prompt")) { - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - } - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("quarantines old-runtime callbacks after successful hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 responseLifecycle: Array = []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - type HandlerRecord = { - sessionUpdate?: Parameters[0]; - permission?: Parameters[0]; - elicitation?: Parameters[0]; - requestUserInput?: AcpAdapterV2ExtensionContext["requestUserInput"]; - }; - const handlerRecords: HandlerRecord[] = []; - const runtimeInputs: AcpAdapterV2RuntimeInput[] = []; - const oldPromptCompletion = yield* Deferred.make(); - const transportDrained = yield* Deferred.make(); - const releaseTransportDrain = yield* Deferred.make(); - let extensionOrdinal = 0; - let runtimeOrdinalSeen = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const makeRuntime = makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => Effect.void, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return { T3_ACP_HANG_PROMPT_FOREVER: "1" }; - }, - protocolEvents, - wrapRuntime: (runtime, runtimeOrdinal) => { - const record: HandlerRecord = {}; - handlerRecords[runtimeOrdinal - 1] = record; - return { - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - record.sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - handleRequestPermission: (handler) => - Effect.sync(() => { - record.permission = handler; - }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), - handleElicitation: (handler) => - Effect.sync(() => { - record.elicitation = handler; - }).pipe(Effect.andThen(runtime.handleElicitation(handler))), - ...(runtimeOrdinal === 1 - ? { - prompt: (payload) => - Effect.gen(function* () { - yield* runtime.prompt(payload).pipe(Effect.ignore, Effect.forkDetach); - return yield* Deferred.await(oldPromptCompletion); - }), - } - : {}), - }; - }, - }); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - registerExtensions: ({ requestUserInput }) => - Effect.sync(() => { - handlerRecords[extensionOrdinal++]!.requestUserInput = requestUserInput; - }), - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: (runtimeInput) => - Effect.sync(() => { - runtimeInputs.push(runtimeInput); - }).pipe(Effect.andThen(makeRuntime(runtimeInput))), - }, - fileSystem, - idAllocator, - serverConfig, - testHooks: { - afterHardTeardownTransportDrained: () => - Deferred.succeed(transportDrained, undefined).pipe( - Effect.andThen(Deferred.await(releaseTransportDrain)), - ), - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-successful-teardown-callback-quarantine"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-successful-teardown-callback-quarantine", - ), - modelSelection, - runtimePolicy, - }); - const adapterEvents = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(adapterEvents, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const permissionRequest = { - sessionId: "mock-session-1", - toolCall: { - toolCallId: "stale-generation-1-permission", - title: "Stale generation 1 permission", - }, - options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }], - }; - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(transportDrained); - const heldInboundFiber = yield* runtimeInputs[0]!.onIncomingRequest!( - "post-drain-stale-permission-id", - "session/request_permission", - permissionRequest, - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(heldInboundFiber.pollUnsafe()); - yield* Deferred.succeed(releaseTransportDrain, undefined); - yield* Fiber.join(heldInboundFiber); - yield* Fiber.join(interruptFiber); - assert.notInclude(responseLifecycle, "registered"); - assert.notInclude(responseLifecycle, "watcher_started"); - assert.isFalse( - (yield* Queue.takeAll(adapterEvents)).some( - (event) => event.type === "runtime_request.updated", - ), - "post-drain inbound callback must not emit a runtime request", - ); - assert.equal(runtimeOrdinalSeen, 1); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - assert.equal(runtimeOrdinalSeen, 2); - const oldHandlers = handlerRecords[0]!; - const replacementHandlers = handlerRecords[1]!; - assert.isDefined(oldHandlers.sessionUpdate); - assert.isDefined(oldHandlers.permission); - assert.isDefined(oldHandlers.elicitation); - assert.isDefined(oldHandlers.requestUserInput); - assert.isDefined(replacementHandlers.sessionUpdate); - assert.isDefined(replacementHandlers.permission); - assert.isDefined(replacementHandlers.elicitation); - assert.isDefined(replacementHandlers.requestUserInput); - assert.lengthOf(runtimeInputs, 2); - while (Option.isSome(yield* Queue.poll(adapterEvents))) { - // Discard generation 1 terminal and generation 2 startup projection. - } - - yield* oldHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "stale generation 1 assistant" }, - }, - }); - yield* oldHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "stale-generation-1-tool", - title: "Stale generation 1 tool", - kind: "other", - status: "completed", - rawOutput: { output: "stale continuation evidence" }, - }, - }); - const oldPermissionFiber = yield* oldHandlers.permission!(permissionRequest).pipe( - Effect.exit, - Effect.forkScoped, - ); - const oldElicitationFiber = yield* oldHandlers.elicitation!({ - sessionId: "mock-session-1", - message: "Stale generation 1 elicitation", - mode: "form", - requestedSchema: { - type: "object", - properties: { approved: { type: "boolean", title: "Approved" } }, - }, - }).pipe(Effect.exit, Effect.forkScoped); - const oldXAiUserInputFiber = yield* oldHandlers.requestUserInput!({ - nativeItemId: "stale-generation-1-xai-item", - nativeMethod: "_x.ai/ask_user_question", - nativeRequestId: "stale-generation-1-xai-request", - nativeSessionId: "mock-session-1", - questions: [ - { - id: "approved", - header: "Approve", - question: "Approve stale generation 1?", - options: [{ label: "yes", description: "Approve" }], - }, - ], - }).pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.succeed(oldPromptCompletion, { stopReason: "end_turn" }); - yield* Effect.sleep("100 millis"); - assert.isTrue(Option.isNone(yield* Queue.poll(adapterEvents))); - assert.isUndefined(oldPermissionFiber.pollUnsafe()); - assert.isUndefined(oldElicitationFiber.pollUnsafe()); - assert.isUndefined(oldXAiUserInputFiber.pollUnsafe()); - assert.lengthOf(continuationRequests, 0); - - yield* replacementHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "live generation 2 assistant" }, - }, - }); - let replacementMessageSeen = false; - while (!replacementMessageSeen) { - const event = yield* Queue.take(adapterEvents); - replacementMessageSeen = - event.type === "message.updated" && event.message.text.includes("live generation 2"); - } - const missingPermissionTransport = yield* replacementHandlers.permission!( - permissionRequest, - ).pipe(Effect.exit); - if (Exit.isSuccess(missingPermissionTransport)) { - assert.fail("a core permission request without transport correlation must fail closed"); - } - assert.include(Cause.pretty(missingPermissionTransport.cause), "Could not correlate"); - yield* runtimeInputs[1]!.onIncomingRequest!( - "live-generation-2-permission-id", - "session/request_permission", - permissionRequest, - ); - const replacementPermission = yield* replacementHandlers.permission!(permissionRequest); - assert.equal(replacementPermission.outcome.outcome, "selected"); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-permission-id"); - const urlElicitation = { - elicitationId: "replacement-url-id", - message: "Open replacement URL", - mode: "url" as const, - sessionId: "mock-session-1", - url: "https://example.com/replacement", - }; - const missingElicitationTransport = yield* replacementHandlers.elicitation!( - urlElicitation, - ).pipe(Effect.exit); - if (Exit.isSuccess(missingElicitationTransport)) { - assert.fail("a core elicitation request without transport correlation must fail closed"); - } - assert.include(Cause.pretty(missingElicitationTransport.cause), "Could not correlate"); - yield* runtimeInputs[1]!.onIncomingRequest!( - "live-generation-2-url-id", - "session/elicitation", - urlElicitation, - ); - yield* replacementHandlers.elicitation!(urlElicitation); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-url-id"); - - const collidingRequestPayload = { - sessionId: "mock-session-1", - toolCallId: "shared-request-id", - }; - const missingXAiTransport = yield* replacementHandlers.requestUserInput!({ - nativeItemId: "missing-generation-2-xai-item", - nativeMethod: "_x.ai/ask_user_question", - nativeRequestId: "shared-request-id", - nativeSessionId: "mock-session-1", - questions: [ - { - id: "approved", - header: "Approve", - question: "Approve missing transport?", - options: [{ label: "yes", description: "Approve" }], - }, - ], - }).pipe(Effect.exit); - if (Exit.isSuccess(missingXAiTransport)) { - assert.fail("an xAI user input request without transport correlation must fail closed"); - } - assert.include(Cause.pretty(missingXAiTransport.cause), "Could not correlate"); - yield* runtimeInputs[0]!.onIncomingRequest!( - "stale-generation-1-transport-id", - "x.ai/ask_user_question", - collidingRequestPayload, - ); - yield* runtimeInputs[1]!.onIncomingRequest!( - "live-generation-2-wrong-method-id", - "x.ai/ask_user_question", - collidingRequestPayload, - ); - yield* runtimeInputs[1]!.onIncomingRequest!( - "live-generation-2-transport-id", - "_x.ai/ask_user_question", - collidingRequestPayload, - ); - const replacementUserInputFiber = yield* replacementHandlers.requestUserInput!({ - nativeItemId: "live-generation-2-xai-item", - nativeMethod: "_x.ai/ask_user_question", - nativeRequestId: "shared-request-id", - nativeSessionId: "mock-session-1", - questions: [ - { - id: "approved", - header: "Approve", - question: "Approve live generation 2?", - options: [{ label: "yes", description: "Approve" }], - }, - ], - }).pipe(Effect.forkScoped); - let replacementRequest: ProviderAdapterV2Event | undefined; - while (replacementRequest === undefined) { - const event = yield* Queue.take(adapterEvents); - if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") { - replacementRequest = event; - } - } - if (replacementRequest.type !== "runtime_request.updated") { - return yield* Effect.die("Expected generation 2 xAI user input request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: replacementRequest.runtimeRequest.id, - answers: { approved: ["yes"] }, - }) - .pipe(Effect.forkScoped); - const replacementUserInput = yield* Fiber.join(replacementUserInputFiber); - assert.deepEqual(replacementUserInput.answers, { approved: ["yes"] }); - yield* replacementUserInput.acknowledgeNativeResponse; - yield* runtimeInputs[0]!.onOutgoingResponse!("stale-generation-1-transport-id"); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-wrong-method-id"); - yield* Effect.yieldNow; - assert.isUndefined(responseFiber.pollUnsafe()); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-transport-id"); - yield* Fiber.join(responseFiber); - - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }), - requestRuntimeRestart: true, - }); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("keeps stale deferred cleanup inert while replacement requests remain live", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => Effect.void, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-stale-deferred-cleanup"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-stale-deferred-cleanup"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ); - const oldPending = yield* Queue.take(events).pipe( - Effect.repeat({ - until: (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - }), - ); - if ( - oldPending.type !== "runtime_request.updated" || - oldPending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected the old runtime permission request"); - } - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: oldPending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }); - const staleResponse = yield* runtime - .respondToRuntimeRequest({ - requestId: oldPending.runtimeRequest.id, - decision: "accept", - }) - .pipe(Effect.exit); - if (Exit.isSuccess(staleResponse)) { - assert.fail("teardown must synchronously remove the old pending request"); - } - while (Option.isSome(yield* Queue.poll(events))) { - // Discard generation 1 cancellation and terminal projection. - } - - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - let replacementPending: ProviderAdapterV2Event | undefined; - while (replacementPending === undefined) { - const event = yield* Queue.take(events); - if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") { - replacementPending = event; - } - } - if (replacementPending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected the replacement runtime permission request"); - } - assert.notEqual(replacementPending.runtimeRequest.id, oldPending.runtimeRequest.id); - yield* runtime.respondToRuntimeRequest({ - requestId: replacementPending.runtimeRequest.id, - decision: "accept", - }); - let replacementTerminal = false; - while (!replacementTerminal) { - const event = yield* Queue.take(events); - if ( - event.type === "runtime_request.updated" && - event.runtimeRequest.id === oldPending.runtimeRequest.id - ) { - assert.fail("stale deferred cleanup must not emit into generation 2"); - } - replacementTerminal = event.type === "turn.terminal"; - } - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("resolves owner cancellation and concurrent resume waiters after hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let runtimeOrdinalSeen = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - ), - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-concurrent-resume-teardown"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-concurrent-resume-teardown", - ), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* pollProtocolMethods(protocolEvents); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const resumeFiber = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.forkScoped); - const secondResumeFiber = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.forkScoped); - const snapshotProviderThread = { - ...providerThread, - nativeThreadRef: { - ...providerThread.nativeThreadRef!, - nativeId: "mock-session-snapshot", - }, - }; - const snapshotFiber = yield* runtime - .readThreadSnapshot({ providerThread: snapshotProviderThread }) - .pipe(Effect.forkScoped); - const forkFiber = yield* runtime - .forkThread({ - sourceProviderThread: providerThread, - targetThreadId: ThreadId.make("thread-acp-concurrent-fork-after-teardown"), - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(resumeFiber.pollUnsafe()); - assert.isUndefined(secondResumeFiber.pollUnsafe()); - assert.isUndefined(snapshotFiber.pollUnsafe()); - assert.isUndefined(forkFiber.pollUnsafe()); - assert.equal(runtimeOrdinalSeen, 1); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsDuringTeardown, "session/load"); - assert.notInclude(methodsDuringTeardown, "session/fork"); - const cancelInterruptOwner = yield* Fiber.interrupt(interruptFiber).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(cancelInterruptOwner.pollUnsafe()); - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(cancelInterruptOwner); - yield* Fiber.join(resumeFiber); - yield* Fiber.join(secondResumeFiber); - yield* Fiber.join(snapshotFiber); - yield* Fiber.join(forkFiber); - assert.equal(runtimeOrdinalSeen, 2); - const methodsAfterRestart = yield* pollProtocolMethods(protocolEvents); - assert.equal(methodsAfterRestart.filter((method) => method === "session/load").length, 2); - assert.equal(methodsAfterRestart.filter((method) => method === "session/fork").length, 1); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("direct Stop skips uninterruptible ACP cancel and recovers after native teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-direct-stop-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - let cancelCalled = false; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-running-1" ? "task-running-1" : undefined, - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-output-1" - ? [{ taskId: "task-running-1", status: "running", appendOutput: "" }] - : [], - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 - ? { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1", - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - T3_ACP_RUNNING_COMMAND_IGNORE_TERM: "1", - T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION: "1", - } - : {}, - protocolEvents, - wrapCancel: () => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(Effect.never)), - }), - }, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-direct-stop-running-command"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-direct-stop-running-command", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - - let runningMonitorSeen = false; - let runningTaskOutputSeen = false; - while (!runningMonitorSeen || !runningTaskOutputSeen) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - (event.turnItem.status === "running" || event.turnItem.status === "pending") - ) { - if (event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1") { - runningMonitorSeen = true; - } - if (event.turnItem.nativeItemRef?.nativeId === "tool-call-output-1") { - runningTaskOutputSeen = true; - } - } - } - const [commandLauncherPid, commandRootPid, commandSleepPid] = Option.getOrThrow( - yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 3), - ); - assert.isTrue( - Option.isSome( - yield* waitForProcesses([commandLauncherPid!, commandRootPid!, commandSleepPid!]), - ), - "declared direct Stop launcher, Bash, and sleep PIDs must become live", - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - yield* Queue.takeAll(events); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - const interruptCompleted = yield* Fiber.join(interruptFiber).pipe( - Effect.timeoutOption("3 seconds"), - ); - assert.isTrue(Option.isSome(interruptCompleted), "hung ACP cancel must not block teardown"); - assert.isFalse(cancelCalled, "hard process-group teardown must skip ACP cancel"); - yield* Effect.sleep("250 millis"); - assert.isFalse(processExists(commandLauncherPid!)); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); - - let terminalStatus: string | null = null; - let openToolTerminalStatus: string | null = null; - let openToolInterruptedExitCode: number | undefined = 42; - let lateAfterCancelSeen = false; - let runningMonitorAfterInterrupt = false; - while (terminalStatus === null || openToolTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" && - event.turnItem.status === "running" - ) { - runningMonitorAfterInterrupt = true; - if (event.turnItem.type === "command_execution") { - assert.equal( - event.turnItem.exitCode, - undefined, - "mid-stream exit_code 0 must not project while the command is still running", - ); - } - } - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - (event.turnItem.status === "failed" || - event.turnItem.status === "cancelled" || - event.turnItem.status === "interrupted" || - event.turnItem.status === "completed") - ) { - openToolTerminalStatus = event.turnItem.status; - openToolInterruptedExitCode = event.turnItem.exitCode; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - terminalStatus = event.status; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - lateAfterCancelSeen = true; - } - } - assert.equal(terminalStatus, "interrupted"); - assert.equal(openToolTerminalStatus, "interrupted"); - assert.equal( - openToolInterruptedExitCode, - undefined, - "interrupted commands must not retain a mid-stream exit_code 0", - ); - assert.isFalse(runningMonitorAfterInterrupt); - assert.isFalse(yield* runtime.hasPendingBackgroundWork!); - assert.isFalse( - lateAfterCancelSeen, - "late post-Stop assistant text must not attach to the stopped run", - ); - - // Give residual cancel-path updates a chance to mis-project if quarantine fails. - yield* Effect.sleep("200 millis"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - let residual = yield* Queue.poll(events); - while (Option.isSome(residual)) { - const event = residual.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" - ) { - assert.notEqual(event.turnItem.status, "running"); - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - lateAfterCancelSeen = true; - } - residual = yield* Queue.poll(events); - } - assert.isFalse(lateAfterCancelSeen, "quarantine must drop residual stopped-run events"); - - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/load", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "Direct Stop follow-up must respawn the ACP runtime", - ); - - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let secondTerminal: string | null = null; - let stoppedRunTextOnFollowUp = false; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - stoppedRunTextOnFollowUp = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; - } - } - assert.equal(secondTerminal, "completed"); - assert.isFalse( - stoppedRunTextOnFollowUp, - "stopped-run residual text must not attach to the follow-up run", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.effect( - "direct Stop on a deferred subagent hold terminalizes the subagent and does not carry it forward", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - 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 adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - restartRuntimeAfterInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-direct-stop-subagent-hold"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-direct-stop-subagent-hold", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - 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; - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "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); - - let subagentStatus: string | null = null; - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.equal(subagentStatus, "interrupted"); - - subagentPhase = "complete"; - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let carriedCompleted = false; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - carriedCompleted = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(secondTerminalStatus, "completed"); - assert.isFalse( - carriedCompleted, - "Direct Stop must not carry a stopped subagent into the follow-up run", - ); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); - - it.live("restart_active terminates native work and reloads a clean runtime", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocatorV2; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-restart-active-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = makeAcpAdapterV2({ - crypto: yield* Crypto.Crypto, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - processGroupTerminationGrace: 0, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 - ? { - T3_ACP_EXIT_ON_CANCEL: "1", - T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1", - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION: "1", - } - : {}, - protocolEvents, - wrapCancel: (cancel) => cancel.pipe(Effect.andThen(Effect.sleep("250 millis"))), - }), - }, - fileSystem, - idAllocator, - serverConfig, - }); - const threadId = ThreadId.make("thread-acp-restart-active-in-process"); - const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-restart-active-in-process"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - - let runningToolSeen = false; - while (!runningToolSeen) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - (event.turnItem.status === "running" || event.turnItem.status === "pending") - ) { - runningToolSeen = true; - } - } - const [commandLauncherPid, commandRootPid, commandSleepPid] = Option.getOrThrow( - yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 3), - ); - assert.isTrue( - Option.isSome( - yield* waitForProcesses([commandLauncherPid!, commandRootPid!, commandSleepPid!]), - ), - "declared restart_active launcher, Bash, and sleep PIDs must become live", - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:1", - }); - // restart_active path: interrupt without requestRuntimeRestart. - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - }) - .pipe(Effect.forkScoped); - yield* Fiber.join(interruptFiber); - yield* Effect.sleep("250 millis"); - assert.isFalse(processExists(commandLauncherPid!)); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); - - let firstTerminal: string | null = null; - while (firstTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminal = event.status; - } - } - assert.equal(firstTerminal, "interrupted"); - - yield* Queue.takeAll(protocolEvents); - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now, - ordinal: 2, - }), - ) - .pipe(Effect.forkScoped); - let loadSeen = false; - let promptSeen = false; - while (!loadSeen || !promptSeen) { - const event = yield* Queue.take(protocolEvents); - if (event.direction !== "outgoing") continue; - const method = rawProtocolMethod(event); - loadSeen ||= method === "session/load"; - promptSeen ||= method === "session/prompt"; - } - assert.isTrue(loadSeen, "restart_active must replay session/load on a new ACP process"); - assert.isTrue(promptSeen, "replacement prompt must start after reload"); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: "mock-session-1:turn:2", - }); - let staleEventSeen = false; - let secondTerminal: string | null = null; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" - ) { - staleEventSeen = true; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - staleEventSeen = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; - } - } - assert.equal(secondTerminal, "completed"); - assert.isFalse(staleEventSeen, "interrupted runtime events must not attach to attempt 2"); - }).pipe(Effect.provide(testLayer), Effect.scoped), - ); -}); - -describe("acpPostSettleWakeEvidence", () => { - const sessionId = "session-wake"; - - it("accepts assistant text and tool updates as wake evidence", () => { - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Subagent finished. SUBAGENT_DONE" }, - }, - }), - ); - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call", - toolCallId: "call-1", - title: "get_command_or_subagent_output", - status: "pending", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("rejects monitor end chatter and background mutations", () => { - assert.isFalse( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { - type: "text", - text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended', - }, - }, - }), - ); - assert.isFalse( - acpPostSettleWakeEvidence( - { - sessionId, - update: { - sessionUpdate: "user_message_chunk", - content: { type: "text", text: "task-1 completed" }, - }, - }, - { - extractBackgroundToolMutation: () => [ - { - taskId: "task-1", - status: "completed", - appendOutput: "", - }, - ], - }, - ), - ); - }); -}); - -describe("acpPostSettleContinuationOfferEvidence", () => { - const sessionId = "session-wake-offer"; - - it("offers on assistant text and terminal tool status", () => { - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Background shell finished." }, - }, - }), - ); - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "completed", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-2", - title: "run_terminal_command", - status: "failed", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("does not offer on thought-only chunks", () => { - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Still reasoning about the monitor output…" }, - }, - }), - ); - // Thoughts may still be wake evidence for buffering once a real offer opens. - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Still reasoning about the monitor output…" }, - }, - }), - ); - }); - - it("buffers in-progress tool updates without offering", () => { - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call", - toolCallId: "call-1", - title: "run_terminal_command", - status: "pending", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("does not offer filtered monitor chatter", () => { - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { - type: "text", - text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended', - }, - }, - }), - ); - }); - - it("does not offer on a normalized monitor start ACK despite raw completed status", () => { - const monitorStartAck = { - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-monitor", - title: "Tool", - status: "completed", - kind: "other", - content: [], - locations: [], - rawInput: { variant: "Monitor", description: "stream test" }, - rawOutput: { - type: "Monitor", - taskId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", - timeoutMs: 60000, - }, - }, - } as const; - // Raw frame looks terminal; the Grok flavor knows it is a running monitor. - assert.isTrue(acpPostSettleContinuationOfferEvidence(monitorStartAck)); - assert.isFalse( - acpPostSettleContinuationOfferEvidence(monitorStartAck, { - normalizeToolCall: normalizeXAiAcpToolCallState, - }), - ); - }); -}); - -describe("acpPostSettleWakeShouldBuffer", () => { - const sessionId = "session-wake-buffer"; - - it("drops agent progress chatter while background work is running", () => { - for (const sessionUpdate of ["agent_message_chunk", "agent_thought_chunk"] as const) { - assert.isFalse( - acpPostSettleWakeShouldBuffer( - { - sessionId, - update: { - sessionUpdate, - content: { type: "text", text: "Still running." }, - }, - }, - true, - ), - ); - } - }); - - it("retains tool state while running and agent output after completion", () => { - const agentMessage = { - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Monitor finished successfully." }, - }, - } as const; - const toolUpdate = { - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-monitor", - title: "monitor", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - } as const; - - assert.isTrue(acpPostSettleWakeShouldBuffer(toolUpdate, true)); - assert.isTrue(acpPostSettleWakeShouldBuffer(agentMessage, false)); - }); -}); - -describe("acpPostSettleMonitorPromptShouldSuppress", () => { - it("suppresses running monitor prompts but not terminal notices", () => { - assert.isTrue( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-active", status: "running" }), - ); - assert.isFalse( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-ended", status: "completed" }), - ); - assert.isFalse( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-failed", status: "failed" }), - ); - }); }); describe("acpPostSettleWakeEvidence", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts index 1a8971eb24..a1b481ed81 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -4,6 +4,7 @@ import { type ProviderReplayTranscript, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -159,7 +160,7 @@ export function makeAcpReplayRuntime(input: { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope > { const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString( "base64", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index 6426e032c0..6ae3c65078 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -29,6 +29,7 @@ import { } from "@t3tools/contracts"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import * as Cause from "effect/Cause"; +import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -198,7 +199,7 @@ export interface AcpAdapterV2Flavor { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly resolveModelId?: (selection: ModelSelection) => string | undefined; readonly registerExtensions?: ( @@ -339,6 +340,7 @@ export interface AcpAdapterV2SubagentUpdate { export interface AcpAdapterV2Options { readonly instanceId: ProviderInstanceId; readonly flavor: AcpAdapterV2Flavor; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2Shape; readonly serverConfig: ServerConfig["Service"]; @@ -2851,7 +2853,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); }); - const offerContinuationRun = Effect.fnUntraced(function* (sessionId: string) { + const offerContinuationRun = Effect.fnUntraced(function* (_sessionId: string) { if (continuationRequests === undefined) { return; } @@ -2883,6 +2885,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV providerThreadId: route.providerThreadId, driver, detail: null, + clearIfCurrent: () => + continuationPermit.withPermit( + Effect.gen(function* () { + if ((yield* Ref.get(continuationGeneration)) === generation) { + yield* Ref.set(continuationRequested, false); + } + }), + ), dispatchIfCurrent: (effect) => continuationPermit.withPermit( Effect.gen(function* () { @@ -2900,11 +2910,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV return Option.none(); } if (!(yield* Ref.get(continuationRequested))) return Option.none(); - // Clear after success or failure so a dropped dispatch does not - // stick the flag and pin hasPendingBackgroundWork forever. + // A successful durable dispatch owns the sticky flag until its + // continuation turn starts. Clearing here opens a dispatch-to- + // start race where every late ACP frame can enqueue another + // synthetic continuation. Failures clear immediately because + // no turn will arrive to do so. const exit = yield* Effect.exit(effect); - yield* clearIfOwner; if (Exit.isFailure(exit)) { + yield* clearIfOwner; return yield* Effect.failCause(exit.cause); } return Option.some(exit.value); @@ -4111,8 +4124,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV runtime = yield* flavor .makeRuntime(makeRuntimeInput(runtimeGeneration)) .pipe( - Effect.provideService(Crypto.Crypto, options.crypto), Effect.provideService(Scope.Scope, runtimeScope), + Effect.provideService(Crypto.Crypto, options.crypto), ); }); @@ -4463,10 +4476,12 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV // Minimal quiet for all models (no per-model carveouts). Defer + // awaitingBackgroundHydration hold the turn through monitors; this // is only a short debounce after the last rearm so a slightly late - // first post-hydration assistant chunk is not dropped. Multi-second - // floors (4–20s) only prolonged Working on grok-4.5. + // post-hydration assistant chunk stays in the same continuation. + // Grok commonly sends its final summary just over two seconds after + // the hydrated tool frame; two seconds split that tail into a second + // synthetic wake. Longer floors (4–20s) only prolonged Working. yield* Effect.gen(function* () { - yield* Effect.sleep("2000 millis"); + yield* Effect.sleep("3000 millis"); if ( context.finalized || context.interrupted || @@ -4587,7 +4602,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const needsSessionActivation = (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; if (needsSessionActivation) { - const activated = yield* activateSession(requestedSessionId); + const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); @@ -4991,7 +5006,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV loadingRole: null, loadingIndex: 0, }); - const activated = yield* activateSession(sessionId); + const activated = yield* activateSession( + sessionId, + threadInput.providerThread.appThreadId, + ); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); const nextSelection = threadInput.modelSelection ?? input.modelSelection; @@ -5295,6 +5313,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.timeoutOption("10 seconds"), ); if (Option.isNone(stopped)) { + if (!context.finalized) { + yield* finalizeTurn(context, "interrupted"); + } return yield* new ProviderAdapterProtocolError({ driver, detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`, @@ -5402,7 +5423,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV loadingRole: null, loadingIndex: 0, }); - const activated = yield* runtime.loadSession(sessionId); + const activated = yield* runtime.loadSession(sessionId, { + mcpServers: acpMcpServers(snapshotInput.providerThread.appThreadId), + }); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); yield* Ref.set(activeSelection, null); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index acb2a48d57..04e5eda12d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -107,6 +108,7 @@ describe("AcpRegistryAdapterV2", () => { }); const instanceId = ProviderInstanceId.make("acp-registry-fixture"); const adapter = makeAcpRegistryAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, settings, environment: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts index 93cbc7f93f..0384fab0ac 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { AcpRegistrySettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -41,6 +42,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const idAllocator = yield* IdAllocatorV2; const serverConfig = yield* ServerConfig; const replayDir = yield* fileSystem @@ -57,6 +59,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac settings: REPLAY_SETTINGS, environment: {}, childProcessSpawner, + crypto, fileSystem, idAllocator, resolver: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts index 66e64d94d1..a88cedce11 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts @@ -49,6 +49,7 @@ export interface AcpRegistryAdapterV2Options { readonly settings: AcpRegistrySettings; readonly environment: NodeJS.ProcessEnv; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2["Service"]; readonly resolver: AcpRegistryResolverShape; @@ -59,7 +60,7 @@ export interface AcpRegistryAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -70,7 +71,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) { ): Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope > => Effect.gen(function* () { const resolved = yield* options.resolver @@ -111,6 +112,7 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) { return makeAcpAdapterV2({ instanceId: options.instanceId, flavor, + crypto: options.crypto, fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, @@ -139,6 +141,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< function* (input: ProviderAdapterDriverCreateInput) { const hostEnvironment = yield* HostProcessEnvironment; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; const providerEventLoggers = yield* ProviderEventLoggers; @@ -152,6 +155,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< settings: { ...input.config, enabled: input.enabled }, environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment), childProcessSpawner, + crypto, fileSystem, idAllocator, resolver, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 00965d58e4..053338be01 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -235,6 +235,21 @@ describe("ClaudeAdapterV2 runtime query policy", () => { }); }); + it("maps Auto runtime mode to Claude's AI-reviewed permission mode", () => { + const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy( + ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "auto", + interactionMode: "default", + cwd: "/workspace", + }), + ); + + assert.deepEqual(queryPolicy, { + permissionMode: "auto", + installPermissionCallback: false, + }); + }); + it("keeps approval-required mode interactive with danger-full-access sandboxing", () => { const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy( ProviderAdapterV2RuntimePolicy.make({ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index 86ecac192a..6725a60130 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -23,6 +23,9 @@ import * as Stream from "effect/Stream"; import { ServerConfig } from "../../config.ts"; import { CLAUDE_PROVIDER, + CLAUDE_DEFAULT_INSTANCE_ID, + CLAUDE_DRIVER_KIND, + ClaudeAdapterV2Driver, ClaudeAgentSdkQueryRunner, ClaudeAgentSdkQueryRunnerError, makeClaudeUserMessage, @@ -159,6 +162,11 @@ export const ClaudeAgentSdkReplayError = Schema.Union([ ClaudeReplayDriverError, ]); export type ClaudeAgentSdkReplayError = typeof ClaudeAgentSdkReplayError.Type; +export const ClaudeOrchestratorReplayHarnessError = Schema.Union([ + ClaudeAgentSdkReplayError, + ProviderAdapterDriverCreateError, +]); +export type ClaudeOrchestratorReplayHarnessError = typeof ClaudeOrchestratorReplayHarnessError.Type; interface ClaudeQueryOpenFrame { readonly type: "query.open"; @@ -761,7 +769,6 @@ export function makeClaudeProviderAdapterRegistryReplayLayer( ), ), ); - return layerFromProviderAdapter.pipe(Layer.provide(adapterLayer)); } export async function replayClaudeAgentSdkTranscript(input: { @@ -2405,7 +2412,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: { export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< ClaudeAgentSdkReplayTranscript, - ClaudeAgentSdkReplayError + ClaudeOrchestratorReplayHarnessError > = { driver: CLAUDE_PROVIDER, decodeTranscript: (transcript) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 0c43abe823..3269ffc760 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -64,10 +64,8 @@ import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { compileClaudeModelSelection } from "../../claudeModelOptions.ts"; import { ServerConfig } from "../../config.ts"; import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts"; -import { - type EventNdjsonLogger, - makeEventNdjsonLogger, -} from "../../provider/Layers/EventNdjsonLogger.ts"; +import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; @@ -477,15 +475,12 @@ export function makeClaudeAgentSdkProtocolLogger(input: { export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer< ClaudeAgentSdkQueryRunner, never, - Crypto.Crypto | ServerConfig + Crypto.Crypto | ProviderEventLoggers > = Layer.effect( ClaudeAgentSdkQueryRunner, Effect.gen(function* () { - const { providerEventLogPath } = yield* ServerConfig; const crypto = yield* Crypto.Crypto; - const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); + const { native: nativeEventLogger } = yield* ProviderEventLoggers; return ClaudeAgentSdkQueryRunner.of({ allocateSessionId: crypto.randomUUIDv4.pipe( @@ -1176,6 +1171,8 @@ function permissionModeForClaudeRuntimePolicy( return "default"; case "auto-accept-edits": return "acceptEdits"; + case "auto": + return "auto"; case "full-access": return "bypassPermissions"; } diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 28af984fba..ca3e0cbbb9 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -265,7 +265,9 @@ describe("CodexAdapterV2 assistant message streaming", () => { describe("CodexAdapterV2 runtime policy", () => { it.effect("derives concrete Codex turn policies from every T3 runtime mode", () => Effect.gen(function* () { - const build = (runtimeMode: "approval-required" | "auto-accept-edits" | "full-access") => + const build = ( + runtimeMode: "approval-required" | "auto-accept-edits" | "auto" | "full-access", + ) => buildCodexTurnStartParams({ nativeThreadId: `native-${runtimeMode}`, codexInput: [{ type: "text", text: "test" }], @@ -282,13 +284,20 @@ describe("CodexAdapterV2 runtime policy", () => { const approvalRequired = yield* build("approval-required"); const autoAcceptEdits = yield* build("auto-accept-edits"); + const auto = yield* build("auto"); const fullAccess = yield* build("full-access"); assert.equal(approvalRequired.approvalPolicy, "untrusted"); + assert.equal(approvalRequired.approvalsReviewer, "user"); assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly"); assert.equal(autoAcceptEdits.approvalPolicy, "on-request"); + assert.equal(autoAcceptEdits.approvalsReviewer, "user"); assert.equal(autoAcceptEdits.sandboxPolicy?.type, "workspaceWrite"); + assert.equal(auto.approvalPolicy, "on-request"); + assert.equal(auto.approvalsReviewer, "auto_review"); + assert.equal(auto.sandboxPolicy?.type, "workspaceWrite"); assert.equal(fullAccess.approvalPolicy, "never"); + assert.equal(fullAccess.approvalsReviewer, "user"); assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess"); }), ); @@ -975,6 +984,9 @@ function codexReplayPreamble(input: { input: [{ type: "text", text: input.prompt }], cwd: "/workspace", model: "gpt-5.4", + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, }, }, }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts index 3b8fc5258b..0b55234cb3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import type { ProviderReplayTranscript } from "@t3tools/contracts"; +import { type ProviderReplayTranscript } from "@t3tools/contracts"; import * as CodexClient from "effect-codex-app-server/client"; import * as CodexReplay from "effect-codex-app-server/replay"; import * as Effect from "effect/Effect"; @@ -12,9 +12,15 @@ import * as Schema from "effect/Schema"; import { ServerConfig } from "../../config.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { ProviderAdapterOpenSessionError } from "../ProviderAdapter.ts"; -import { layerFromProviderAdapter } from "../ProviderAdapterRegistry.ts"; +import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts"; +import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts"; import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts"; -import { CodexAppServerClientFactory, layer as codexAdapterLayer } from "./CodexAdapterV2.ts"; +import { + CODEX_DEFAULT_INSTANCE_ID, + CODEX_DRIVER_KIND, + CodexAdapterV2Driver, + CodexAppServerClientFactory, +} from "./CodexAdapterV2.ts"; export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "CodexReplayTranscriptDecodeError", @@ -33,6 +39,7 @@ export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass Effect.Effect< CodexClient.CodexAppServerClient["Service"], ProviderAdapterOpenSessionError, @@ -1246,16 +1264,12 @@ function isSensitiveCodexProtocolKey(key: string): boolean { export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer< CodexAppServerClientFactory, never, - ChildProcessSpawner.ChildProcessSpawner | ServerConfig | ServerSettingsService + ChildProcessSpawner.ChildProcessSpawner | ProviderEventLoggers > = Layer.effect( CodexAppServerClientFactory, Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const { providerEventLogPath } = yield* ServerConfig; - const settingsService = yield* ServerSettingsService; - const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); + const { native: nativeEventLogger } = yield* ProviderEventLoggers; return CodexAppServerClientFactory.of({ open: (input) => @@ -1330,7 +1344,7 @@ export const CodexAdapterV2Driver: ProviderAdapterDriver, - ) => - Effect.gen(function* () { - const inputItems: Array = []; - if (turnInput.message.text.length > 0) { - inputItems.push({ - type: "text", - text: turnInput.message.text, - }); - } - const attachmentItems = yield* Effect.forEach( - turnInput.message.attachments, - resolveCodexAttachment, - { concurrency: 1 }, - ); - inputItems.push(...attachmentItems); - if (inputItems.length === 0) { - return yield* toProtocolError("Turn requires non-empty text or attachments."); - } - return inputItems; - }); - - const buildAgentMessageArtifacts = ( - context: ActiveCodexTurnContext, - item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "agentMessage" } - >, - ) => - Effect.gen(function* () { - const completedAt = yield* DateTime.now; - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const ordinal = yield* resolveItemOrdinal(context, item.id); - const messageId = idAllocator.derive.messageFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: context.input.threadId, - runId: context.input.runId, - parentNodeId: context.input.rootNodeId, - rootNodeId: context.input.rootNodeId, - kind: "assistant_message", - status: "completed", - countsForRun: false, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: context.startedAt, - completedAt, - }; - const message: OrchestrationV2ConversationMessage = { - id: messageId, - threadId: context.input.threadId, - runId: context.input.runId, - nodeId, - role: "assistant", - text: item.text, - attachments: [], - streaming: false, - createdAt: completedAt, - updatedAt: completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: context.input.threadId, - runId: context.input.runId, - nodeId, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - parentItemId: null, - ordinal, - status: "completed", - title: null, - startedAt: context.startedAt, - completedAt, - updatedAt: completedAt, - type: "assistant_message", - messageId, - text: item.text, - streaming: false, - }; - return { node, message, turnItem }; - }); - - const buildCommandExecutionArtifacts = ( - context: ActiveCodexTurnContext, - item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "commandExecution" } - >, - ) => - Effect.gen(function* () { - const updatedAt = yield* DateTime.now; - const status = codexItemStatus(item.status); - const completedAt = status.completed ? updatedAt : null; - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const ordinal = yield* resolveItemOrdinal(context, item.id); - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: context.input.threadId, - runId: context.input.runId, - parentNodeId: context.input.rootNodeId, - rootNodeId: context.input.rootNodeId, - kind: "tool_call", - status: status.node, - countsForRun: false, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: context.startedAt, - completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: context.input.threadId, - runId: context.input.runId, - nodeId, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - parentItemId: null, - ordinal, - status: status.turnItem, - title: null, - startedAt: context.startedAt, - completedAt, - updatedAt, - type: "command_execution", - input: item.command, - ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined - ? {} - : { output: item.aggregatedOutput }), - ...(item.exitCode === null || item.exitCode === undefined - ? {} - : { exitCode: item.exitCode }), - }; - return { node, turnItem }; - }); - - const buildFileChangeArtifacts = ( - context: ActiveCodexTurnContext, - item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "fileChange" } - >, - ) => - Effect.gen(function* () { - const firstChange = item.changes[0]; - if (firstChange === undefined) { - return null; - } - - const updatedAt = yield* DateTime.now; - const status = codexItemStatus(item.status); - const completedAt = status.completed ? updatedAt : null; - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: item.id, - }); - const ordinal = yield* resolveItemOrdinal(context, item.id); - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: context.input.threadId, - runId: context.input.runId, - parentNodeId: context.input.rootNodeId, - rootNodeId: context.input.rootNodeId, - kind: "tool_call", - status: status.node, - countsForRun: false, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: context.startedAt, - completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: context.input.threadId, - runId: context.input.runId, - nodeId, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: codexNativeItemRef(item.id), - parentItemId: null, - ordinal, - status: status.turnItem, - title: null, - startedAt: context.startedAt, - completedAt, - updatedAt, - type: "file_change", - fileName: firstChange.path, - diffStr: firstChange.diff, - }; - return { node, turnItem }; - }); - - const buildWebSearchArtifacts = (input: { - readonly context: ActiveCodexTurnContext; - readonly item: CodexWebSearchItem; - readonly completed: boolean; - }) => - Effect.gen(function* () { - const updatedAt = yield* DateTime.now; - const completedAt = input.completed ? updatedAt : null; - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.item.id, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.item.id, - }); - const ordinal = yield* resolveItemOrdinal(input.context, input.item.id); - const patterns = webSearchPatterns(input.item); - const status = input.completed ? "completed" : "running"; - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.input.rootNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "tool_call", - status, - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.item.id), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: input.context.startedAt, - completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.item.id), - parentItemId: null, - ordinal, - status, - title: null, - startedAt: input.context.startedAt, - completedAt, - updatedAt, - type: "web_search", - ...(patterns.length === 0 ? {} : { patterns: [...patterns] }), - }; - return { node, turnItem }; - }); - - const buildProposedPlanArtifacts = (input: { - readonly context: ActiveCodexTurnContext; - readonly nativeItemId: string; - readonly status: OrchestrationV2PlanArtifact["status"]; - readonly markdown: string; - readonly completed?: boolean; - }) => - Effect.gen(function* () { - const updatedAt = yield* DateTime.now; - const completedAt = input.completed === true ? updatedAt : null; - const planId = yield* resolvePlanId(input.context, input.nativeItemId); - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); - const plan: OrchestrationV2PlanArtifact = { - id: planId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - kind: "proposed_plan", - status: input.status, - markdown: input.markdown, - }; - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.input.rootNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "plan", - status: input.completed === true ? "completed" : "running", - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: input.context.startedAt, - completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - parentItemId: null, - ordinal, - status: input.completed === true ? "completed" : "running", - title: null, - startedAt: input.context.startedAt, - completedAt, - updatedAt, - type: "proposed_plan", - planId, - markdown: input.markdown, - streaming: input.completed !== true, - }; - return { node, plan, turnItem }; - }); - - const buildTodoListArtifacts = (input: { - readonly context: ActiveCodexTurnContext; - readonly nativeItemId: string; - readonly status: OrchestrationV2PlanArtifact["status"]; - readonly steps: ReadonlyArray; - readonly explanation?: string; - readonly completed?: boolean; - }) => - Effect.gen(function* () { - const updatedAt = yield* DateTime.now; - const completedAt = input.completed === true ? updatedAt : null; - const planId = yield* resolvePlanId(input.context, input.nativeItemId); - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); - const plan: OrchestrationV2PlanArtifact = { - id: planId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - kind: "todo_list", - status: input.status, - steps: [...input.steps], - ...(input.explanation === undefined ? {} : { explanation: input.explanation }), - }; - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.input.rootNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "todo_list", - status: input.completed === true ? "completed" : "running", - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: input.context.startedAt, - completedAt, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - parentItemId: null, - ordinal, - status: input.completed === true ? "completed" : "running", - title: null, - startedAt: input.context.startedAt, - completedAt, - updatedAt, - type: "todo_list", - planId, - steps: [...input.steps], - ...(input.explanation === undefined ? {} : { explanation: input.explanation }), - }; - return { node, plan, turnItem }; - }); - - const buildApprovalRequestArtifacts = (input: { - readonly context: ActiveCodexTurnContext; - readonly nativeItemId: string; - readonly nativeRequestId: string; - readonly requestKind: ProviderRequestKind; - readonly prompt?: string | null; - }) => - Effect.gen(function* () { - const createdAt = yield* DateTime.now; - const parentNodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const ordinal = yield* resolveItemOrdinal( - input.context, - `${input.nativeItemId}:approval:${input.nativeRequestId}`, - ); - const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: CODEX_PROVIDER, - providerTurnId: input.context.providerTurnId, - nativeRequestId: input.nativeRequestId, - }); - const nodeId = idAllocator.derive.approvalNode({ requestId }); - const providerSessionId = input.context.input.providerThread.providerSessionId; - if (providerSessionId === null) { - return yield* toProtocolError( - `Provider thread ${input.context.input.providerThread.id} is missing a provider session id.`, - ); - } - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "approval_request", - status: "waiting", - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - runtimeRequestId: requestId, - checkpointScopeId: null, - startedAt: createdAt, - completedAt: null, - }; - const request: OrchestrationV2RuntimeRequest = { - id: requestId, - nodeId, - providerTurnId: input.context.providerTurnId, - nativeRequestRef: { - provider: CODEX_PROVIDER, - nativeId: input.nativeRequestId, - strength: "strong", - }, - kind: input.requestKind, - status: "pending", - responseCapability: { - type: "live", - providerSessionId, - }, - createdAt, - resolvedAt: null, - }; - const turnItem: OrchestrationV2TurnItem = { - id: idAllocator.derive.approvalTurnItem({ requestId }), - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - parentItemId: null, - ordinal, - status: "waiting", - title: null, - startedAt: createdAt, - completedAt: null, - updatedAt: createdAt, - type: "approval_request", - requestId, - requestKind: input.requestKind, - ...(input.prompt === null || input.prompt === undefined - ? {} - : { prompt: input.prompt }), - }; - return { node, request, turnItem }; - }); - - const buildUserInputRequestArtifacts = (input: { - readonly context: ActiveCodexTurnContext; - readonly nativeItemId: string; - readonly nativeRequestId: string; - readonly questions: ReadonlyArray; - }) => - Effect.gen(function* () { - const createdAt = yield* DateTime.now; - const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: CODEX_PROVIDER, - providerTurnId: input.context.providerTurnId, - nativeRequestId: input.nativeRequestId, - }); - const providerSessionId = input.context.input.providerThread.providerSessionId; - if (providerSessionId === null) { - return yield* toProtocolError( - `Provider thread ${input.context.input.providerThread.id} is missing a provider session id.`, - ); - } - const questions = input.questions.map((question, index) => ({ - id: nonEmptyText(question.id, `question-${index + 1}`), - header: nonEmptyText(question.header, "Question"), - question: nonEmptyText(question.question, "Choose an answer."), - options: - question.options?.map((option, optionIndex) => ({ - label: nonEmptyText(option.label, `Option ${optionIndex + 1}`), - description: nonEmptyText(option.description, option.label), - })) ?? [], - })); - const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, - nativeItemId: input.nativeItemId, - }); - const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); - const node: OrchestrationV2ExecutionNode = { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.input.rootNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "user_input_request", - status: "waiting", - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - runtimeRequestId: requestId, - checkpointScopeId: null, - startedAt: createdAt, - completedAt: null, - }; - const request: OrchestrationV2RuntimeRequest = { - id: requestId, - nodeId, - providerTurnId: input.context.providerTurnId, - nativeRequestRef: { - provider: CODEX_PROVIDER, - nativeId: input.nativeRequestId, - strength: "strong", - }, - kind: "user_input", - status: "pending", - responseCapability: { - type: "live", - providerSessionId, - }, - createdAt, - resolvedAt: null, - }; - const turnItem: OrchestrationV2TurnItem = { - id: turnItemId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - nodeId, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.nativeItemId), - parentItemId: null, - ordinal, - status: "waiting", - title: null, - startedAt: createdAt, - completedAt: null, - updatedAt: createdAt, - type: "user_input_request", - requestId, - questions, - }; - return { node, request, turnItem }; - }); - - yield* client.handleServerNotification("item/agentMessage/delta", (payload) => - Ref.update(agentMessageDeltas, (current) => { + yield* Ref.update(planIds, (current) => { const updated = new Map(current); - updated.set(payload.itemId, `${updated.get(payload.itemId) ?? ""}${payload.delta}`); + updated.set(planKey, planId); return updated; - }), - ); + }); + return planId; + }); const resolveCodexAttachment = (attachment: ChatAttachment) => Effect.gen(function* () { @@ -4095,9 +3502,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi : (deltas.get(payload.item.id) ?? ""); const artifacts = yield* buildProposedPlanArtifacts({ context, - nativeItemId: payload.itemId, - status: "active", + nativeItemId: payload.item.id, + status: "completed", markdown, + completed: true, }); yield* emitProviderEvent({ type: "node.updated", @@ -4114,27 +3522,13 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); - }).pipe(Effect.orDie), - ); + return; + } - yield* client.handleServerNotification("turn/plan/updated", (payload) => - Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined) { - return; - } - const steps = payload.plan.map((step, index) => ({ - id: `step-${index + 1}`, - text: nonEmptyText(step.step, `Step ${index + 1}`), - status: codexPlanStepStatus(step.status), - })); - const explanation = trimText(payload.explanation); - const artifacts = yield* buildTodoListArtifacts({ + if (payload.item.type === "collabAgentToolCall") { + yield* registerSubagentThreads({ context, - nativeItemId: `turn-plan:${payload.turnId}`, - status: "active", - ...(explanation === undefined ? {} : { explanation }), - steps, + item: payload.item, }); yield* updateSubagentStates({ item: payload.item, @@ -4952,10 +4346,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ), resumeThread: (threadInput) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined || payload.item.type !== "webSearch") { - return; - } + const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const response = yield* ensureInitialized.pipe( Effect.andThen( @@ -5056,13 +4447,6 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, ); } - yield* Ref.update(activeTurns, (current) => { - const updated = new Map(current); - updated.delete(payload.turn.id); - return updated; - }); - }), - ); const codexInput = yield* toCodexInput(turnInput); yield* client.request("turn/steer", { @@ -5447,123 +4831,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi `No pending Codex runtime request ${requestInput.requestId}.`, ), }); - const started = yield* client.request("turn/start", turnStartParams); - const nativeTurnId = started.turn.id; - const startedAt = codexTimestamp(started.turn.startedAt); - const pTurnId = idAllocator.derive.providerTurn({ - provider: CODEX_PROVIDER, - nativeTurnId, - }); - const providerTurnOrdinal = turnInput.runOrdinal; - const context: ActiveCodexTurnContext = { - input: turnInput, - nativeTurnId, - providerTurnId: pTurnId, - providerTurnOrdinal, - startedAt, - }; - yield* Ref.update(activeTurns, (current) => { - const updated = new Map(current); - updated.set(nativeTurnId, context); - return updated; - }); - yield* emitProviderEvent({ - type: "provider_turn.updated", - provider: CODEX_PROVIDER, - providerTurn: { - id: pTurnId, - providerThreadId: turnInput.providerThread.id, - nodeId: turnInput.rootNodeId, - runAttemptId: turnInput.attemptId, - nativeTurnRef: { - provider: CODEX_PROVIDER, - nativeId: nativeTurnId, - strength: "strong", - }, - ordinal: providerTurnOrdinal, - status: "running", - startedAt, - completedAt: null, - }, - }); - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterTurnStartError({ - provider: CODEX_PROVIDER, - threadId: turnInput.threadId, - providerThreadId: turnInput.providerThread.id, - runId: turnInput.runId, - cause, - }), - ), - ), - steerTurn: (turnInput) => - Effect.gen(function* () { - const threadId = yield* getNativeThreadId(turnInput.providerThread); - const activeTurn = Array.from((yield* Ref.get(activeTurns)).values()).find( - (candidate) => candidate.providerTurnId === turnInput.providerTurnId, - ); - if (activeTurn === undefined) { - return yield* toProtocolError( - `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, - ); - } - - const codexInput = yield* toCodexInput(turnInput); - yield* client.request("turn/steer", { - expectedTurnId: activeTurn.nativeTurnId, - input: codexInput, - threadId, - }); - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterSteerRunError({ - provider: CODEX_PROVIDER, - providerThreadId: turnInput.providerThread.id, - providerTurnId: turnInput.providerTurnId, - cause, - }), - ), - ), - interruptTurn: (turnInput) => - Effect.gen(function* () { - const threadId = yield* getNativeThreadId(turnInput.providerThread); - const activeTurn = Array.from((yield* Ref.get(activeTurns)).values()).find( - (candidate) => candidate.providerTurnId === turnInput.providerTurnId, - ); - if (activeTurn === undefined) { - return yield* toProtocolError( - `Provider turn ${turnInput.providerTurnId} is not active and cannot be interrupted.`, - ); - } - yield* client.request("turn/interrupt", { - threadId, - turnId: activeTurn.nativeTurnId, - }); - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterInterruptError({ - provider: CODEX_PROVIDER, - providerThreadId: turnInput.providerThread.id, - providerTurnId: turnInput.providerTurnId, - cause, - }), - ), - ), - respondToRuntimeRequest: (requestInput) => - Effect.gen(function* () { - const pending = (yield* Ref.get(pendingRuntimeRequests)).get( - String(requestInput.requestId), - ); - if (pending === undefined) { + } + if (pending.type === "user_input") { + if (requestInput.answers === undefined) { return yield* new ProviderAdapterRuntimeRequestResponseError({ driver: CODEX_PROVIDER, requestId: requestInput.requestId, cause: toProtocolError( - `No pending Codex runtime request ${requestInput.requestId}.`, + `Codex user input request ${requestInput.requestId} requires answers.`, ), }); } @@ -5587,65 +4862,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi : new ProviderAdapterRuntimeRequestResponseError({ driver: CODEX_PROVIDER, requestId: requestInput.requestId, - cause: toProtocolError( - `Codex user input request ${requestInput.requestId} requires answers.`, - ), - }); - } - yield* Deferred.succeed(pending.answers, requestInput.answers); - return; - } - if (requestInput.decision === undefined) { - return yield* new ProviderAdapterRuntimeRequestResponseError({ - provider: CODEX_PROVIDER, - requestId: requestInput.requestId, - cause: toProtocolError( - `Codex ${pending.requestKind} request ${requestInput.requestId} requires an approval decision.`, - ), - }); - } - yield* Deferred.succeed(pending.decision, requestInput.decision); - }).pipe( - Effect.mapError((cause) => - Schema.is(ProviderAdapterRuntimeRequestResponseError)(cause) - ? cause - : new ProviderAdapterRuntimeRequestResponseError({ - provider: CODEX_PROVIDER, - requestId: requestInput.requestId, - cause, - }), - ), - ), - readThreadSnapshot: (threadInput) => - Effect.gen(function* () { - const threadId = yield* getNativeThreadId(threadInput.providerThread); - const response = yield* ensureInitialized.pipe( - Effect.andThen(client.request("thread/read", { threadId, includeTurns: true })), - ); - return { - providerThread: { - ...threadInput.providerThread, - nativeThreadRef: { - provider: CODEX_PROVIDER, - nativeId: response.thread.id, - strength: "strong" as const, - }, - updatedAt: codexTimestamp(response.thread.updatedAt), - }, - providerTurns: [], - messages: [], - runtimeRequests: [], - providerPayload: response.thread, - }; - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterReadThreadSnapshotError({ - provider: CODEX_PROVIDER, - providerThreadId: threadInput.providerThread.id, cause, }), - ), ), ), readThreadSnapshot: (threadInput) => @@ -5812,6 +5030,6 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi cause, }), ), - }); - }), -); + ), + }); +} diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts index cb1e108afc..29d210ec98 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts @@ -568,6 +568,7 @@ function makeReplayServerConfig( baseDir, staticDir: undefined, devUrl: undefined, + devAllowedOrigins: [], noBrowser: false, startupPresentation: "browser", tailscaleServeEnabled: false, diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.test.ts b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.test.ts index cbc465e8ad..84299c8dbc 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.test.ts @@ -5,7 +5,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { vi } from "vite-plus/test"; -import { ServerConfig } from "../../config.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; import { CursorAgentSdkRunner, CursorAgentSdkRunnerError, @@ -68,29 +68,6 @@ const cursorSdkMock = vi.hoisted(() => { }; }); -vi.mock("../../provider/Layers/EventNdjsonLogger.ts", async () => { - const Effect = await import("effect/Effect"); - - return { - makeEventNdjsonLogger: vi.fn(() => - Effect.succeed({ - filePath: "cursor-agent-sdk-test.log", - write: (event: unknown) => - Effect.sync(() => { - if ( - typeof event === "object" && - event !== null && - Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close" - ) { - cursorSdkMock.closeExecutionOrder.push("protocol:agent.close"); - } - }), - close: () => Effect.void, - }), - ), - }; -}); - vi.mock("@cursor/sdk", () => ({ Agent: { create: cursorSdkMock.create, @@ -103,8 +80,22 @@ vi.mock("@cursor/sdk", () => ({ const testLayer = cursorAgentSdkRunnerLiveLayer.pipe( Layer.provide( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-cursor-agent-sdk-runner-", + Layer.succeed(ProviderEventLoggers, { + native: { + filePath: "cursor-agent-sdk-test.log", + write: (event: unknown) => + Effect.sync(() => { + if ( + typeof event === "object" && + event !== null && + Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close" + ) { + cursorSdkMock.closeExecutionOrder.push("protocol:agent.close"); + } + }), + close: () => Effect.void, + }, + canonical: undefined, }), ), Layer.provide(NodeServices.layer), diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts index 7750a47e37..d1806820b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts @@ -17,11 +17,8 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { ServerConfig } from "../../config.ts"; -import { - type EventNdjsonLogger, - makeEventNdjsonLogger, -} from "../../provider/Layers/EventNdjsonLogger.ts"; +import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const; export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor"); @@ -298,231 +295,231 @@ export function makeCursorAgentSdkProtocolLogger(input: { .pipe(Effect.ignore); } -export const cursorAgentSdkRunnerLiveLayer: Layer.Layer = - Layer.effect( - CursorAgentSdkRunner, - Effect.gen(function* () { - const { providerEventLogPath } = yield* ServerConfig; - const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); +export const cursorAgentSdkRunnerLiveLayer: Layer.Layer< + CursorAgentSdkRunner, + never, + ProviderEventLoggers +> = Layer.effect( + CursorAgentSdkRunner, + Effect.gen(function* () { + const { native: nativeEventLogger } = yield* ProviderEventLoggers; - return CursorAgentSdkRunner.of({ - open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) { - const protocolLogger = makeCursorAgentSdkProtocolLogger({ - nativeEventLogger, - threadId: input.threadId, - providerSessionId: input.providerSessionId, - }); - const log = (event: CursorAgentSdkProtocolLogEvent) => - protocolLogger === undefined ? Effect.void : protocolLogger(event); + return CursorAgentSdkRunner.of({ + open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) { + const protocolLogger = makeCursorAgentSdkProtocolLogger({ + nativeEventLogger, + threadId: input.threadId, + providerSessionId: input.providerSessionId, + }); + const log = (event: CursorAgentSdkProtocolLogEvent) => + protocolLogger === undefined ? Effect.void : protocolLogger(event); - yield* log({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "agent.open", - operation: input.operation, - ...(input.agentId === undefined ? {} : { agentId: input.agentId }), - options: loggedCursorAgentOptions(input.options), - }, - }); + yield* log({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "agent.open", + operation: input.operation, + ...(input.agentId === undefined ? {} : { agentId: input.agentId }), + options: loggedCursorAgentOptions(input.options), + }, + }); - const agent = yield* Effect.tryPromise({ - try: () => - input.operation === "create" - ? Agent.create(input.options) - : Agent.resume(input.agentId!, input.options), - catch: (cause) => runnerError(cause, `agent.${input.operation}`), - }); + const agent = yield* Effect.tryPromise({ + try: () => + input.operation === "create" + ? Agent.create(input.options) + : Agent.resume(input.agentId!, input.options), + catch: (cause) => runnerError(cause, `agent.${input.operation}`), + }); - yield* log({ - direction: "incoming", - stage: "decoded", - payload: { - type: "agent.opened", - agentId: agent.agentId, - }, - }); - - const cwd = - typeof input.options.local?.cwd === "string" - ? input.options.local.cwd - : input.options.local?.cwd?.[0]; - - return { + yield* log({ + direction: "incoming", + stage: "decoded", + payload: { + type: "agent.opened", agentId: agent.agentId, - send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) { - const context = yield* Effect.context(); - yield* log({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "run.start", - message: sendInput.message, - options: loggedCursorSendOptions(sendInput.options), - }, - }); + }, + }); - let callbacksReady = false; - const pendingUpdates: Array = []; - let callbackFailure: { readonly cause: unknown } | undefined; - let callbackChain = Promise.resolve(); - let runId = ""; - const dispatchUpdate = (update: InteractionUpdate): Promise => { - callbackChain = callbackChain - .then(() => { - if (callbackFailure !== undefined) { - return; - } - return Effect.runPromiseWith(context)( - log({ - direction: "incoming", - stage: "decoded", - payload: { - type: "interaction.update", - runId, - update, - }, - }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)), - ); - }) - .catch((cause) => { - callbackFailure ??= { cause }; - }); - return callbackChain; - }; + const cwd = + typeof input.options.local?.cwd === "string" + ? input.options.local.cwd + : input.options.local?.cwd?.[0]; - const run = yield* Effect.tryPromise({ - try: () => - agent.send(sendInput.message, { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }), - catch: (cause) => runnerError(cause, "run.start"), - }); - runId = run.id; - yield* log({ - direction: "incoming", - stage: "decoded", - payload: { - type: "run.started", - runId: run.id, - agentId: run.agentId, - }, - }); - callbacksReady = true; - for (const update of pendingUpdates) { - yield* Effect.tryPromise({ - try: () => dispatchUpdate(update), - catch: (cause) => runnerError(cause, "run.onDelta"), - }); - } + return { + agentId: agent.agentId, + send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) { + const context = yield* Effect.context(); + yield* log({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "run.start", + message: sendInput.message, + options: loggedCursorSendOptions(sendInput.options), + }, + }); - return { - runId: run.id, - agentId: run.agentId, - wait: Effect.tryPromise({ - try: async () => { - const result = await run.wait(); - await callbackChain; - if (callbackFailure !== undefined) { - throw callbackFailure.cause; - } - return result; - }, - catch: (cause) => runnerError(cause, "run.wait"), - }).pipe( - Effect.tap((result) => + let callbacksReady = false; + const pendingUpdates: Array = []; + let callbackFailure: { readonly cause: unknown } | undefined; + let callbackChain = Promise.resolve(); + let runId = ""; + const dispatchUpdate = (update: InteractionUpdate): Promise => { + callbackChain = callbackChain + .then(() => { + if (callbackFailure !== undefined) { + return; + } + return Effect.runPromiseWith(context)( log({ direction: "incoming", stage: "decoded", payload: { - type: "run.completed", - result, + type: "interaction.update", + runId, + update, }, - }), - ), - ), - cancel: log({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "run.cancel", - runId: run.id, + }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)), + ); + }) + .catch((cause) => { + callbackFailure ??= { cause }; + }); + return callbackChain; + }; + + const run = yield* Effect.tryPromise({ + try: () => + agent.send(sendInput.message, { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingUpdates.push(update); + return; + } + await dispatchUpdate(update); }, - }).pipe( - Effect.andThen( - Effect.tryPromise({ - try: async () => { - try { - await run.cancel(); - } catch (cause) { - if (!isCursorCancellationError(cause)) { - throw cause; - } + }), + catch: (cause) => runnerError(cause, "run.start"), + }); + runId = run.id; + yield* log({ + direction: "incoming", + stage: "decoded", + payload: { + type: "run.started", + runId: run.id, + agentId: run.agentId, + }, + }); + callbacksReady = true; + for (const update of pendingUpdates) { + yield* Effect.tryPromise({ + try: () => dispatchUpdate(update), + catch: (cause) => runnerError(cause, "run.onDelta"), + }); + } + + return { + runId: run.id, + agentId: run.agentId, + wait: Effect.tryPromise({ + try: async () => { + const result = await run.wait(); + await callbackChain; + if (callbackFailure !== undefined) { + throw callbackFailure.cause; + } + return result; + }, + catch: (cause) => runnerError(cause, "run.wait"), + }).pipe( + Effect.tap((result) => + log({ + direction: "incoming", + stage: "decoded", + payload: { + type: "run.completed", + result, + }, + }), + ), + ), + cancel: log({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "run.cancel", + runId: run.id, + }, + }).pipe( + Effect.andThen( + Effect.tryPromise({ + try: async () => { + try { + await run.cancel(); + } catch (cause) { + if (!isCursorCancellationError(cause)) { + throw cause; } - }, - catch: (cause) => runnerError(cause, "run.cancel"), - }), - ), + } + }, + catch: (cause) => runnerError(cause, "run.cancel"), + }), ), - } satisfies CursorAgentSdkRun; - }), - listMessages: log({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "agent.messages.list", - agentId: agent.agentId, - }, - }).pipe( - Effect.andThen( - Effect.tryPromise({ - try: () => - Agent.messages.list(agent.agentId, { - runtime: "local", - ...(cwd === undefined ? {} : { cwd }), - }), - catch: (cause) => runnerError(cause, "agent.messages.list"), - }), - ), - Effect.tap((messages) => - log({ - direction: "incoming", - stage: "decoded", - payload: { - type: "agent.messages", - agentId: agent.agentId, - messages, - }, - }), ), + } satisfies CursorAgentSdkRun; + }), + listMessages: log({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "agent.messages.list", + agentId: agent.agentId, + }, + }).pipe( + Effect.andThen( + Effect.tryPromise({ + try: () => + Agent.messages.list(agent.agentId, { + runtime: "local", + ...(cwd === undefined ? {} : { cwd }), + }), + catch: (cause) => runnerError(cause, "agent.messages.list"), + }), ), - close: log({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "agent.close", - agentId: agent.agentId, - }, - }).pipe( - Effect.andThen( - Effect.try({ - try: () => agent.close(), - catch: (cause) => runnerError(cause, "agent.close"), - }), - ), + Effect.tap((messages) => + log({ + direction: "incoming", + stage: "decoded", + payload: { + type: "agent.messages", + agentId: agent.agentId, + messages, + }, + }), ), - } satisfies CursorAgentSdkSession; - }), - assertComplete: Effect.void, - }); - }), - ); + ), + close: log({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "agent.close", + agentId: agent.agentId, + }, + }).pipe( + Effect.andThen( + Effect.try({ + try: () => agent.close(), + catch: (cause) => runnerError(cause, "agent.close"), + }), + ), + ), + } satisfies CursorAgentSdkSession; + }), + assertComplete: Effect.void, + }); + }), +); diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts index 68834a7126..18fb50d0b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { GrokSettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -34,6 +35,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const idAllocator = yield* IdAllocatorV2; const serverConfig = yield* ServerConfig; const replayDir = yield* fileSystem @@ -50,6 +52,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay settings: DEFAULT_GROK_SETTINGS, environment: {}, childProcessSpawner, + crypto, fileSystem, idAllocator, serverConfig, diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts index b89be38a8a..163bb32581 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -94,6 +94,7 @@ export interface GrokAdapterV2Options { readonly settings: GrokSettings; readonly environment: NodeJS.ProcessEnv; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2["Service"]; readonly serverConfig: ServerConfig["Service"]; @@ -104,7 +105,7 @@ export interface GrokAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -210,6 +211,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) { return makeAcpAdapterV2({ instanceId: options.instanceId, flavor, + crypto: options.crypto, fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, @@ -236,6 +238,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver) { const hostEnvironment = yield* HostProcessEnvironment; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; const providerEventLoggers = yield* ProviderEventLoggers; @@ -247,6 +250,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver { ); assert.equal(permissionAction(granularApproval, "bash"), "ask"); assert.equal(permissionAction(granularApproval, "read"), "allow"); + + const approvalRequiredWorkspaceWrite = openCodePermissionRules( + runtimePolicy("approval-required", { + sandboxPolicy: { + type: "workspaceWrite", + writableRoots: ["/tmp/opencode-workspace"], + networkAccess: false, + }, + }), + ); + assert.equal(permissionAction(approvalRequiredWorkspaceWrite, "edit"), "ask"); }); it("enforces non-interactive sandbox policy through OpenCode permissions", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts index 8e8d36b030..a5fa86ccba 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts @@ -334,6 +334,13 @@ function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript) detail: "OpenCode replay does not load inventory.", }), ), + loadInventoryFromCli: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadInventoryFromCli", + detail: "OpenCode replay does not load inventory.", + }), + ), } satisfies OpenCodeRuntimeShape); }), ); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts index 0625418ff9..e0834bec85 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts @@ -555,7 +555,10 @@ export function openCodePermissionRules( })), ); - if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") { + if ( + runtimePolicy.runtimeMode === "auto-accept-edits" || + (!requiresApproval && sandboxType === "workspaceWrite") + ) { rules.push({ permission: "edit", pattern: "*", action: "allow" }); } diff --git a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts index 75e0325c08..52c3bb0c1c 100644 --- a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts @@ -14,6 +14,8 @@ import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as HostPowerMonitor from "../background/HostPowerMonitor.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; @@ -48,6 +50,10 @@ const serverSettingsLayer = ServerSettingsService.layerTest({ cursor: { enabled: true }, }, }); +const backgroundPolicyLayer = BackgroundPolicy.layer.pipe( + Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())), + Layer.provide(serverSettingsLayer), +); const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( Layer.provide( Layer.mergeAll( @@ -68,6 +74,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(serverConfigLayer), Layer.provide(serverSettingsLayer), Layer.provide(providerInstanceRegistryLayer), + Layer.provide(backgroundPolicyLayer), Layer.provide(NodeServices.layer), ); diff --git a/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts index 6c8ac93777..5e5bc62ba0 100644 --- a/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts @@ -14,6 +14,8 @@ import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as HostPowerMonitor from "../background/HostPowerMonitor.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; @@ -47,6 +49,10 @@ const serverSettingsLayer = ServerSettingsService.layerTest({ grok: { enabled: true }, }, }); +const backgroundPolicyLayer = BackgroundPolicy.layer.pipe( + Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())), + Layer.provide(serverSettingsLayer), +); const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( Layer.provide( Layer.mergeAll( @@ -67,6 +73,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(serverConfigLayer), Layer.provide(serverSettingsLayer), Layer.provide(providerInstanceRegistryLayer), + Layer.provide(backgroundPolicyLayer), Layer.provide(NodeServices.layer), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5fad0cfc07..55eb2ecc8b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -994,6 +994,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is not archived.`, }); } + if ( + (command.type === "thread.settle" || + command.type === "thread.unsettle" || + command.type === "thread.snooze" || + command.type === "thread.unsnooze") && + thread.archivedAt !== null + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is archived.`, + }); + } + if ( + command.type === "thread.settle" && + (projection.runs.some((run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + ) || + projection.runtimeRequests.some((request) => request.status === "pending")) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} has active or blocked work and cannot be settled.`, + }); + } const providerSwitchPlan = command.type === "thread.model-selection.set" || command.type === "provider.switch" @@ -2276,7 +2302,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio effects: Ref.Ref>, ) => Effect.gen(function* () { - const projection = yield* getProjectionWithPendingEvents(command.threadId, events); + let projection = yield* getProjectionWithPendingEvents(command.threadId, events); + if (projection.thread.settledOverride !== null) { + const now = yield* DateTime.now; + const thread: OrchestrationV2AppThread = { + ...projection.thread, + settledOverride: null, + settledAt: null, + updatedAt: now, + }; + yield* emit( + events, + command, + )({ + type: "thread.unsettled", + threadId: command.threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: thread, + }); + projection = yield* getProjectionWithPendingEvents(command.threadId, events); + } + if (projection.thread.snoozedUntil != null) { + const now = yield* DateTime.now; + const thread: OrchestrationV2AppThread = { + ...projection.thread, + snoozedUntil: null, + snoozedAt: null, + updatedAt: now, + }; + yield* emit( + events, + command, + )({ + type: "thread.unsnoozed", + threadId: command.threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: thread, + }); + projection = yield* getProjectionWithPendingEvents(command.threadId, events); + } const modelSelection = command.modelSelection ?? projection.thread.modelSelection; const dispatchMode = command.dispatchMode; const sourcePlanProjection = diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ad34753efc..645283705d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -180,6 +180,10 @@ export function applyToProjection( case "thread.archived": case "thread.unarchived": case "thread.deleted": + case "thread.settled": + case "thread.unsettled": + case "thread.snoozed": + case "thread.unsnoozed": case "thread.metadata-updated": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts index c4a467e04c..bcc135140e 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts @@ -22,11 +22,11 @@ import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "./ProviderAdapte export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass()( "ProviderAdapterRegistryLookupError", { - provider: ProviderKind, + instanceId: ProviderInstanceId, }, ) { override get message(): string { - return `No orchestration provider adapter is registered for ${this.provider}.`; + return `No orchestration provider adapter is registered for ${this.instanceId}.`; } } @@ -44,7 +44,7 @@ export type ProviderAdapterRegistryV2Error = typeof ProviderAdapterRegistryV2Err export interface ProviderAdapterRegistryV2Shape { readonly get: ( - provider: ProviderKind, + instanceId: ProviderInstanceId, ) => Effect.Effect; readonly list: () => Effect.Effect>; readonly getMetadata?: (instanceId: ProviderInstanceId) => Effect.Effect< @@ -122,15 +122,15 @@ function makeRegistry( adapters: ReadonlyArray, ): ProviderAdapterRegistryV2Shape { return { - get: (provider) => + get: (instanceId) => Effect.gen(function* () { - const adapter = adapters.find((candidate) => candidate.provider === provider); + const adapter = adapters.find((candidate) => candidate.instanceId === instanceId); if (!adapter) { - return yield* new ProviderAdapterRegistryLookupError({ provider }); + return yield* new ProviderAdapterRegistryLookupError({ instanceId }); } return adapter; }), - list: () => Effect.succeed(adapters.map((adapter) => adapter.provider as ProviderKind)), + list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)), }; } @@ -309,11 +309,11 @@ export const layerFromProviderAdapter: Layer.Layer< Effect.gen(function* () { const adapter = yield* ProviderAdapterV2; return ProviderAdapterRegistryV2.of({ - get: (provider) => - adapter.provider === provider + get: (instanceId) => + adapter.instanceId === instanceId ? Effect.succeed(adapter) - : Effect.fail(new ProviderAdapterRegistryLookupError({ provider })), - list: () => Effect.succeed([adapter.provider]), + : Effect.fail(new ProviderAdapterRegistryLookupError({ instanceId })), + list: () => Effect.succeed([adapter.instanceId]), } satisfies ProviderAdapterRegistryV2Shape); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderContinuationRequests.ts b/apps/server/src/orchestration-v2/ProviderContinuationRequests.ts index 9af9a74288..5c6260baaa 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationRequests.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationRequests.ts @@ -26,6 +26,8 @@ export interface ProviderContinuationRequest { readonly dispatchIfCurrent?: ( effect: Effect.Effect, ) => Effect.Effect, E, R>; + /** Clears a pending offer that the continuation worker intentionally drops. */ + readonly clearIfCurrent?: () => Effect.Effect; } /** diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.ts index dbc6167ac6..b580bec342 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.ts @@ -32,8 +32,12 @@ export const workerLive = Layer.effectDiscard( threadId: request.threadId, providerThreadId: request.providerThreadId, }); - // Still run the guard so adapters can clear sticky continuationRequested. - if (request.dispatchIfCurrent !== undefined) { + // No continuation turn will start to clear the adapter's sticky offer. + if (request.clearIfCurrent !== undefined) { + yield* request.clearIfCurrent(); + } else if (request.dispatchIfCurrent !== undefined) { + // Backward compatibility for request producers without an explicit + // drop callback. yield* request.dispatchIfCurrent(Effect.void); } return; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index bb1c8733d7..b681836682 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -103,7 +103,7 @@ const emptyState: TestProviderRuntimeState = { }; const modelSelection = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", } satisfies ModelSelection; const CODEX_DRIVER = ProviderDriverKind.make("codex"); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 03f2162dcd..8eeacd7f68 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -3,7 +3,7 @@ import { OrchestrationV2DomainEvent, OrchestrationV2ProviderSession, OrchestrationV2RuntimeRequest, - ProviderKind, + ProviderInstanceId, ProviderSessionId, ThreadId, } from "@t3tools/contracts"; @@ -62,13 +62,13 @@ export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.T export class ProviderSessionOpenError extends Schema.TaggedErrorClass()( "ProviderSessionOpenError", { - provider: ProviderKind, + instanceId: ProviderInstanceId, providerSessionId: ProviderSessionId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to open ${this.provider} provider session ${this.providerSessionId}.`; + return `Failed to open provider instance ${this.instanceId} session ${this.providerSessionId}.`; } } @@ -1393,7 +1393,7 @@ export const layerWithOptions = ( Effect.mapError( (cause) => new ProviderSessionOpenError({ - provider: input.modelSelection.provider, + instanceId: input.modelSelection.instanceId, providerSessionId: input.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 28f2120e59..dc5982bffa 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -1,4 +1,4 @@ -import { assert, it } from "@effect/vitest"; +import { assert, it, vi } from "@effect/vitest"; import { CheckpointScopeId, CommandId, @@ -32,6 +32,7 @@ import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { EventSinkV2 } from "./EventSink.ts"; @@ -307,6 +308,77 @@ it.effect("rechecks run ownership immediately before calling the provider", () = }).pipe(Effect.provide(RunExecutionTestLayer)), ); +it.effect("refreshes MCP credential liveness before calling the provider", () => + Effect.gen(function* () { + const runExecution = yield* RunExecutionServiceV2; + const order = yield* Ref.make>([]); + const threadId = ThreadId.make("thread:run-execution-mcp-liveness"); + const touchActiveMcpThread = vi + .spyOn(McpSessionRegistry, "touchActiveMcpThread") + .mockImplementation((touchedThreadId) => + Ref.update(order, (entries) => [...entries, `touch:${touchedThreadId}`]), + ); + + yield* runExecution + .startRootRun({ + commandId: CommandId.make("command:run-execution-mcp-liveness"), + appThread: { id: threadId } as OrchestrationV2AppThread, + providerSessionId: ProviderSessionId.make("session:run-execution-mcp-liveness"), + session: { + events: Stream.never, + startTurn: () => Ref.update(order, (entries) => [...entries, "start-turn"]), + } as unknown as ProviderAdapterV2SessionRuntime, + run: { + id: RunId.make("run:run-execution-mcp-liveness"), + threadId, + ordinal: 1, + providerInstanceId: ProviderInstanceId.make("codex"), + } as OrchestrationV2Run, + rootNode: { + id: NodeId.make("node:run-execution-mcp-liveness"), + } as OrchestrationV2ExecutionNode, + checkpointScope: { + id: CheckpointScopeId.make("checkpoint-scope:run-execution-mcp-liveness"), + } as OrchestrationV2CheckpointScope, + providerThread: { + id: ProviderThreadId.make("provider-thread:run-execution-mcp-liveness"), + driver, + } as OrchestrationV2ProviderThread, + attempt: { + id: RunAttemptId.make("attempt:run-execution-mcp-liveness"), + providerTurnId: null, + } as OrchestrationV2RunAttempt, + attemptId: RunAttemptId.make("attempt:run-execution-mcp-liveness"), + providerTurnOrdinal: 1, + message: { + messageId: MessageId.make("message:run-execution-mcp-liveness"), + text: "Keep the MCP credential alive.", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + 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.ensuring(Effect.sync(() => touchActiveMcpThread.mockRestore()))); + + assert.deepEqual(yield* Ref.get(order), [`touch:${threadId}`, "start-turn"]); + }).pipe(Effect.provide(RunExecutionTestLayer)), +); + it.effect("keeps ingesting owned child events after the root turn terminalizes", () => Effect.gen(function* () { const threadId = ThreadId.make("thread:run-execution-late-child"); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index a3d72b065b..0105fe37c9 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -31,6 +31,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { EventSinkV2 } from "./EventSink.ts"; @@ -1094,6 +1095,10 @@ export const layer: Layer.Layer< return; } + // A provider turn is a sign that the session is still alive. Keep + // its already-issued MCP credential valid even when the agent goes + // a long time between browser-tool calls. + yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId); yield* input.session .startTurn({ appThread: input.appThread, diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index bfa89449e3..744a8720fe 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -1,4 +1,5 @@ import type { + ApplicationStoredEvent, OrchestrationV2ArchivedShellStreamItem, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index de45bac5ae..21e3518983 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -1,10 +1,12 @@ import { assert, it, vi } from "@effect/vitest"; import { CommandId, + DEFAULT_SERVER_SETTINGS, MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, + type ServerProvider, ThreadId, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -20,6 +22,8 @@ import * as GitWorkflow from "../git/GitWorkflowService.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; @@ -61,6 +65,9 @@ interface HarnessOptions { readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"]; readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]; readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"]; + readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"]; + readonly serverSettings?: Parameters[0]; + readonly providers?: ReadonlyArray; } function makeHarness(options: HarnessOptions = {}) { @@ -84,6 +91,9 @@ function makeHarness(options: HarnessOptions = {}) { const runSetup = vi.fn( options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })), ); + const generateBranchName = vi.fn( + options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })), + ); const externalServices = Layer.mergeAll( Layer.succeed(ProjectService.ProjectService, { create: () => Effect.die("unused"), @@ -107,8 +117,10 @@ function makeHarness(options: HarnessOptions = {}) { Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle: options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })), - generateBranchName: () => Effect.succeed({ branch: "generated-branch" }), + generateBranchName, }), + ServerSettings.layerTest(options.serverSettings), + makeProviderRegistryLayer(options.providers), ); const launch = ThreadLaunch.layer.pipe( Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)), @@ -116,6 +128,7 @@ function makeHarness(options: HarnessOptions = {}) { return { layer: Layer.mergeAll(launch, threadManagement, outbox, database), createWorktree, + generateBranchName, runSetup, }; } @@ -443,6 +456,98 @@ it.effect("does not put optional title generation on the provisioning critical p }), ); +it.effect("uses the available source control writer for generated worktree branches", () => + Effect.gen(function* () { + const writerInstanceId = ProviderInstanceId.make("source-control-writer"); + const writerModelSelection = { + instanceId: writerInstanceId, + model: "branch-writer-model", + } as const; + const harness = makeHarness({ + serverSettings: { + providerInstances: { + [writerInstanceId]: { + driver: ProviderDriverKind.make("codex"), + config: {}, + }, + }, + sourceControlWriterModelSelection: writerModelSelection, + }, + providers: [ + { + instanceId: writerInstanceId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-07-28T00:00:00.000Z", + availability: "available", + models: [], + slashCommands: [], + skills: [], + }, + ], + }); + + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* launches.launch( + launchInput({ + command: "command:launch:source-control-writer", + thread: "thread:launch:source-control-writer", + message: "Generate a branch with the configured writer", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1)); + assert.deepEqual( + harness.generateBranchName.mock.calls[0]?.[0].modelSelection, + writerModelSelection, + ); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("falls back when the source control writer is unavailable", () => + Effect.gen(function* () { + const writerInstanceId = ProviderInstanceId.make("missing-source-control-writer"); + const harness = makeHarness({ + serverSettings: { + providerInstances: { + [writerInstanceId]: { + driver: ProviderDriverKind.make("missing-driver"), + config: {}, + }, + }, + sourceControlWriterModelSelection: { + instanceId: writerInstanceId, + model: "missing-branch-writer-model", + }, + }, + providers: [], + }); + + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* launches.launch( + launchInput({ + command: "command:launch:source-control-writer-fallback", + thread: "thread:launch:source-control-writer-fallback", + message: "Generate a branch with the available writer", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1)); + assert.deepEqual( + harness.generateBranchName.mock.calls[0]?.[0].modelSelection, + DEFAULT_SERVER_SETTINGS.textGenerationModelSelection, + ); + }).pipe(Effect.provide(harness.layer)); + }), +); + for (const failurePoint of ["worktree", "setup"] as const) { it.effect( `${failurePoint} failure keeps the thread and message visible and emits failure items`, diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 69e3fc83d8..ae67feec50 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -25,6 +25,8 @@ import * as Scope from "effect/Scope"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as IdAllocator from "./IdAllocator.ts"; @@ -132,6 +134,8 @@ export const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const git = yield* GitWorkflow.GitWorkflowService; const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + const serverSettings = yield* ServerSettings.ServerSettingsService; const textGeneration = yield* TextGeneration.TextGeneration; const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; const ids = yield* IdAllocator.IdAllocatorV2; @@ -222,21 +226,29 @@ export const make = Effect.gen(function* () { ); } + const initialMessage = input.initialMessage; let branch = input.workspaceStrategy.type === "worktree" && input.workspaceStrategy.branch === undefined && - input.initialMessage !== undefined - ? yield* textGeneration - .generateBranchName({ - cwd: project.workspaceRoot, - message: input.initialMessage.text, - attachments: input.initialMessage.attachments, - modelSelection: input.modelSelection, - }) - .pipe( - Effect.map((result) => result.branch), - Effect.mapError(mapError(input, "generate-metadata", threadId)), - ) + initialMessage !== undefined + ? yield* Effect.gen(function* () { + const settings = yield* serverSettings.getSettings; + const modelSelection = + settings.sourceControlWriterModelSelection === null + ? settings.textGenerationModelSelection + : ServerSettings.resolveSourceControlWriterModelSelection( + settings, + yield* providerRegistry.getProviders, + ); + return yield* textGeneration + .generateBranchName({ + cwd: project.workspaceRoot, + message: initialMessage.text, + attachments: initialMessage.attachments, + modelSelection, + }) + .pipe(Effect.map((result) => result.branch)); + }).pipe(Effect.mapError(mapError(input, "generate-metadata", threadId))) : (input.workspaceStrategy.branch ?? (input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null)); let worktreePath = diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 896c40275f..1f34589ec3 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -15,6 +15,7 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as DateTime from "effect/DateTime"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; @@ -54,7 +55,13 @@ const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-orchestration-v2-runtime-layer-", }); -const GitCoreTestLayer = GitCoreLive.pipe( +const modelSelection = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", +} satisfies ModelSelection; + +const VcsDriverRegistryTestLayer = VcsDriverRegistry.layer.pipe( + Layer.provide(VcsProcess.layer), Layer.provide(ServerConfigLayer), Layer.provide(NodeServices.layer), ); @@ -161,10 +168,7 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => { threadId, projectId, title: "Runtime layer thread", - modelSelection: { - provider: "codex", - model: "gpt-5.4", - }, + modelSelection: modelSelection, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -618,6 +622,25 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { modelSelection: { ...modelSelection, model: "gpt-5.5" }, }); + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("runtime-layer-lifecycle-settle"), + threadId, + }); + const settledProjection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(settledProjection.thread.settledOverride, "settled"); + assert.isNotNull(settledProjection.thread.settledAt); + + yield* orchestrator.dispatch({ + type: "thread.unsettle", + commandId: CommandId.make("runtime-layer-lifecycle-unsettle"), + threadId, + reason: "user", + }); + const activeProjection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(activeProjection.thread.settledOverride, "active"); + assert.isNull(activeProjection.thread.settledAt); + const archive = yield* orchestrator.dispatch({ type: "thread.archive", commandId: CommandId.make("runtime-layer-lifecycle-archive"), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index ab345146d5..38aa57b570 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -89,13 +89,6 @@ const providerSwitchServiceProvided = providerSwitchServiceLayer.pipe( Layer.provide(providerAdapterRegistryProvided), ); -const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromEffect( - Effect.all([ - Effect.service(ProviderAdapterV2).pipe(Effect.provide(codexAdapterProvided)), - Effect.service(ProviderAdapterV2).pipe(Effect.provide(claudeAdapterProvided)), - ]), -); - const providerSessionManagerProvided = providerSessionManagerLayer.pipe( Layer.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index da34715e6f..332db73af3 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -109,6 +109,7 @@ export function makeReplayServerConfig( baseDir, staticDir: undefined, devUrl: undefined, + devAllowedOrigins: [], noBrowser: false, startupPresentation: "browser", tailscaleServeEnabled: false, @@ -245,7 +246,8 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( const providerEventIngestorProvided = providerEventIngestorLayer.pipe( Layer.provide(Layer.mergeAll(storesLayer, eventSinkProvided, idAllocatorLayer)), ); - const gitCoreLayer = GitCoreLive.pipe( + const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( + Layer.provide(VcsProcess.layer), Layer.provide(serverConfigLayer), Layer.provide(NodeServices.layer), ); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index 009c916077..0a50aca4e5 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -239,7 +239,7 @@ export interface FixtureIds { } export const CODEX_MODEL_SELECTION = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", } satisfies ModelSelection; diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index c1d509323e..9a7224a3b7 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -17,6 +17,7 @@ import { OrchestrationThreadSearchSource, OrchestrationShellSnapshot, OrchestrationThread, + OrchestrationThreadDetailSnapshot, type OrchestrationCheckpointSummary, type OrchestrationLatestTurn, type OrchestrationMessage, @@ -766,31 +767,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { Result: ProjectionThreadSearchRow, execute: ({ pattern, limit }) => sql` - WITH ranked AS ( + WITH candidate AS ( SELECT threads.thread_id AS thread_id, threads.project_id AS project_id, - CASE messages.role - WHEN 'user' THEN 'user' - ELSE 'assistant' - END AS source, + messages.role AS role, messages.text AS match_text, messages.created_at AS message_created_at, - CASE messages.role - WHEN 'user' THEN 0 - ELSE 1 - END AS match_rank, - threads.updated_at AS thread_updated_at, - ROW_NUMBER() OVER ( - PARTITION BY threads.thread_id - ORDER BY - CASE messages.role - WHEN 'user' THEN 0 - ELSE 1 - END ASC, - messages.created_at DESC, - messages.message_id ASC - ) AS thread_match_rank + messages.message_id AS message_id, + threads.updated_at AS thread_updated_at FROM projection_thread_messages AS messages INNER JOIN projection_threads AS threads ON threads.thread_id = messages.thread_id @@ -812,6 +797,53 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ) ) AND messages.text LIKE ${pattern} ESCAPE '!' + UNION ALL + SELECT + v2_threads.thread_id AS thread_id, + v2_threads.project_id AS project_id, + v2_messages.role AS role, + json_extract(v2_messages.payload_json, '$.text') AS match_text, + v2_messages.created_at AS message_created_at, + v2_messages.message_id AS message_id, + v2_threads.updated_at AS thread_updated_at + FROM orchestration_v2_projection_messages AS v2_messages + INNER JOIN orchestration_v2_projection_threads AS v2_threads + ON v2_threads.thread_id = v2_messages.thread_id + INNER JOIN projection_projects AS projects + ON projects.project_id = v2_threads.project_id + WHERE v2_threads.deleted_at IS NULL + AND v2_threads.archived_at IS NULL + AND projects.deleted_at IS NULL + AND v2_messages.streaming = 0 + AND v2_messages.role IN ('user', 'assistant') + AND json_extract(v2_messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!' + ), + ranked AS ( + SELECT + thread_id, + project_id, + CASE role + WHEN 'user' THEN 'user' + ELSE 'assistant' + END AS source, + match_text, + message_created_at, + CASE role + WHEN 'user' THEN 0 + ELSE 1 + END AS match_rank, + thread_updated_at, + ROW_NUMBER() OVER ( + PARTITION BY thread_id + ORDER BY + CASE role + WHEN 'user' THEN 0 + ELSE 1 + END ASC, + message_created_at DESC, + message_id ASC + ) AS thread_match_rank + FROM candidate ) SELECT thread_id AS "threadId", @@ -1891,6 +1923,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { createdAt: row.createdAt, updatedAt: row.updatedAt, archivedAt: row.archivedAt, + settledOverride: row.settledOverride, + settledAt: row.settledAt, + snoozedUntil: row.snoozedUntil, + snoozedAt: row.snoozedAt, + titleRegeneration: mapTitleRegeneration(row), session: sessionByThread.get(row.threadId) ?? null, latestUserMessageAt: row.latestUserMessageAt, hasPendingApprovals: row.pendingApprovalCount > 0, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.approval.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.approval.test.ts deleted file mode 100644 index 05370781c0..0000000000 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.approval.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { - EventId, - ProviderDriverKind, - RuntimeRequestId, - ThreadId, - type ProviderRuntimeEvent, -} from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { runtimeEventToActivities } from "./ProviderRuntimeIngestion.ts"; - -describe("runtimeEventToActivities approval details", () => { - it("preserves complete multiline command details", () => { - const detail = `bun run release -- ${"long-argument ".repeat(20)}\nsecond line`; - const event = { - type: "request.opened", - eventId: EventId.make("evt-request-opened"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-07-18T00:00:00.000Z", - threadId: ThreadId.make("thread-1"), - requestId: RuntimeRequestId.make("approval-1"), - payload: { - requestType: "command_execution_approval", - detail, - }, - } satisfies ProviderRuntimeEvent; - - const [activity] = runtimeEventToActivities(event); - - expect(activity?.kind).toBe("approval.requested"); - expect((activity?.payload as Record | undefined)?.detail).toBe(detail); - }); -}); diff --git a/apps/server/src/orchestration/Normalizer.test.ts b/apps/server/src/orchestration/Normalizer.test.ts deleted file mode 100644 index 113b6e1bae..0000000000 --- a/apps/server/src/orchestration/Normalizer.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { - CommandId, - type ClientOrchestrationCommand, - MessageId, - ProjectId, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; - -import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts"; - -const clientCreatedAt = "2031-01-01T00:00:00.000Z"; -const serverReceivedAt = "2026-07-18T00:00:00.000Z"; - -describe("canonicalizeClientCommandTimestamps", () => { - it("replaces a client command timestamp with the server receipt timestamp", () => { - const command: ClientOrchestrationCommand = { - type: "project.create", - commandId: CommandId.make("command-1"), - projectId: ProjectId.make("project-1"), - title: "Clock-safe project", - workspaceRoot: "/tmp/clock-safe-project", - createdAt: clientCreatedAt, - }; - - expect(canonicalizeClientCommandTimestamps(command, serverReceivedAt)).toEqual({ - ...command, - createdAt: serverReceivedAt, - }); - }); - - it("replaces both timestamps when the first turn bootstraps a thread", () => { - const command: ClientOrchestrationCommand = { - type: "thread.turn.start", - commandId: CommandId.make("command-2"), - threadId: ThreadId.make("thread-1"), - message: { - messageId: MessageId.make("message-1"), - role: "user", - text: "Start a thread", - attachments: [], - }, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: ProjectId.make("project-1"), - title: "Clock-safe thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: clientCreatedAt, - }, - }, - createdAt: clientCreatedAt, - }; - - const result = canonicalizeClientCommandTimestamps(command, serverReceivedAt); - - expect(result.type).toBe("thread.turn.start"); - if (result.type !== "thread.turn.start") { - throw new Error("Expected a thread.turn.start command"); - } - expect(result.createdAt).toBe(serverReceivedAt); - expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt); - }); -}); diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index 15153225cc..8ab1b53732 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -5,6 +5,7 @@ import type { OrchestrationReadModel, OrchestrationThread, } from "@t3tools/contracts/legacy-orchestration"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import * as Effect from "effect/Effect"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts index 252350dabb..1698c84c52 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts @@ -206,6 +206,20 @@ layer("OrchestrationEventStore", (it) => { assert.isTrue("aggregateKind" in applicationEvents[0]!); assert.isTrue("event" in applicationEvents[1]!); + const finiteReplay = yield* eventStore + .readApplicationEvents({ + afterSequence: baselineSequence, + throughSequence: threadEvent!.sequence, + }) + .pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + ); + assert.deepEqual( + finiteReplay.map((event) => event.sequence), + [projectEvent.sequence, threadEvent!.sequence], + ); + const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe( Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts index cf7db447d1..0beedd9956 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -504,7 +504,7 @@ const makeEventStore = Effect.gen(function* () { ), ); - const readApplicationEvents = (input: { + const readApplicationEventPage = (input: { readonly afterSequence: number; readonly throughSequence: number; readonly limit: number; @@ -534,7 +534,7 @@ const makeEventStore = Effect.gen(function* () { afterSequence: number, ): Stream.Stream => Stream.unwrap( - readApplicationEvents({ + readApplicationEventPage({ afterSequence, throughSequence: input.throughSequence, limit: READ_PAGE_SIZE, @@ -581,6 +581,7 @@ const makeEventStore = Effect.gen(function* () { readAgentEvents, latestAgentSequence, latestApplicationSequence, + readApplicationEvents: catchUpApplicationEvents, publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid), streamApplicationEvents, } satisfies OrchestrationEventStoreShape; diff --git a/apps/server/src/persistence/Migrations/036_037_OrchestrationV2.test.ts b/apps/server/src/persistence/Migrations/036_037_OrchestrationV2.test.ts index 297bf48df7..209aa3f8e1 100644 --- a/apps/server/src/persistence/Migrations/036_037_OrchestrationV2.test.ts +++ b/apps/server/src/persistence/Migrations/036_037_OrchestrationV2.test.ts @@ -3,7 +3,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as SqlClient from "effect/unstable/sql/SqlClient"; -import { runMigrations } from "../Migrations.ts"; +import { migrationEntries, runMigrations } from "../Migrations.ts"; import * as NodeSqliteClient from "../NodeSqliteClient.ts"; const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); @@ -13,7 +13,7 @@ layer("036_037_OrchestrationV2", (it) => { Effect.sync(() => { assert.deepStrictEqual( migrationEntries.map(([id]) => id), - Array.from({ length: 43 }, (_, index) => index + 1), + Array.from({ length: 44 }, (_, index) => index + 1), ); }), ); @@ -64,7 +64,7 @@ layer("036_037_OrchestrationV2", (it) => { }), ); - it.effect("backfills provider-session thread bindings in migration 036", () => + it.effect("backfills provider-session thread bindings in migration 038", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* runMigrations({ toMigrationInclusive: 38 }); diff --git a/apps/server/src/persistence/Migrations/041_ApplicationEventSource.test.ts b/apps/server/src/persistence/Migrations/041_ApplicationEventSource.test.ts index c41b7a5319..f59b55bfd2 100644 --- a/apps/server/src/persistence/Migrations/041_ApplicationEventSource.test.ts +++ b/apps/server/src/persistence/Migrations/041_ApplicationEventSource.test.ts @@ -8,7 +8,7 @@ import * as NodeSqliteClient from "../NodeSqliteClient.ts"; const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); -layer("039_ApplicationEventSource", (it) => { +layer("040_ApplicationEventSource", (it) => { it.effect("moves V2 events and current project state behind one global sequence", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/persistence/Migrations/042_OrchestrationV2EffectCancellation.test.ts b/apps/server/src/persistence/Migrations/042_OrchestrationV2EffectCancellation.test.ts index ffb24996f7..b7982b4e49 100644 --- a/apps/server/src/persistence/Migrations/042_OrchestrationV2EffectCancellation.test.ts +++ b/apps/server/src/persistence/Migrations/042_OrchestrationV2EffectCancellation.test.ts @@ -8,7 +8,7 @@ import * as NodeSqliteClient from "../NodeSqliteClient.ts"; const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); -layer("040_OrchestrationV2EffectCancellation", (it) => { +layer("041_OrchestrationV2EffectCancellation", (it) => { it.effect("preserves existing effects and adds the cancelled terminal status", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts index 801d4137a0..eb1f0cd7bb 100644 --- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -82,6 +82,12 @@ export interface OrchestrationEventStoreShape { readonly latestApplicationSequence: Effect.Effect; + /** Read the finite retained application-event range `(afterSequence, throughSequence]`. */ + readonly readApplicationEvents: (input: { + readonly afterSequence: number; + readonly throughSequence: number; + }) => Stream.Stream; + /** Publish only after the surrounding event/projection transaction commits. */ readonly publishCommitted: (events: ReadonlyArray) => Effect.Effect; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 56c269b881..731485a1a4 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -30,6 +30,7 @@ import { ClaudeAdapterV2Driver, type ClaudeAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderDriverError } from "../Errors.ts"; import { checkClaudeProviderStatus, @@ -84,6 +85,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ export type ClaudeDriverEnv = | ClaudeAdapterV2DriverEnv + | BackgroundPolicy.BackgroundPolicy | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 43c93e47f3..54b94f71be 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -37,6 +37,7 @@ import { CodexAdapterV2Driver, type CodexAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderDriverError } from "../Errors.ts"; import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; @@ -75,6 +76,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ */ export type CodexDriverEnv = | CodexAdapterV2DriverEnv + | BackgroundPolicy.BackgroundPolicy | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index e7a28cb26b..c6d5af5308 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -8,7 +8,6 @@ * @module provider/Drivers/CursorDriver */ import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -43,13 +42,16 @@ import { const decodeCursorSettings = Schema.decodeSync(CursorSettings); const DRIVER_KIND = ProviderDriverKind.make("cursor"); -const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({ provider: DRIVER_KIND, packageName: null, }); -export type CursorDriverEnv = CursorAdapterV2DriverEnv | ServerConfig | ServerSettingsService; +export type CursorDriverEnv = + | CursorAdapterV2DriverEnv + | BackgroundPolicy.BackgroundPolicy + | ServerConfig + | ServerSettingsService; const withInstanceIdentity = (input: { @@ -125,9 +127,6 @@ export const CursorDriver: ProviderDriver = { initialSnapshot: (settings) => buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)), checkProvider, - // Model catalog and capabilities come from Cursor's SDK catalog during - // provider checks. - refreshInterval: SNAPSHOT_REFRESH_INTERVAL, }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.ts index 7b6d78aaab..0a15de1715 100644 --- a/apps/server/src/provider/Drivers/GrokDriver.ts +++ b/apps/server/src/provider/Drivers/GrokDriver.ts @@ -51,6 +51,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver( export type GrokDriverEnv = | GrokAdapterV2DriverEnv + | BackgroundPolicy.BackgroundPolicy | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index 30077d97c1..fb9ae2723f 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -28,6 +28,7 @@ import { OpenCodeAdapterV2Driver, type OpenCodeAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderDriverError } from "../Errors.ts"; import { checkOpenCodeProviderStatus, @@ -79,6 +80,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ export type OpenCodeDriverEnv = | OpenCodeAdapterV2DriverEnv + | BackgroundPolicy.BackgroundPolicy | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index af498e1a52..0e019f003c 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -12,7 +12,14 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Result from "effect/Result"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { + createModelCapabilities, + getModelSelectionStringOptionValue, + getProviderOptionCurrentValue, + getProviderOptionDescriptors, +} from "@t3tools/shared/model"; +import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import { compareSemverVersions } from "@t3tools/shared/semver"; import { query as claudeQuery, type Options as ClaudeQueryOptions, @@ -376,8 +383,74 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo ); } -export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string { - switch (modelSelection.options?.contextWindow) { +export function resolveClaudeEffort( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const descriptors = getProviderOptionDescriptors({ + caps, + ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}), + }); + const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort"); + const value = getProviderOptionCurrentValue(effortDescriptor); + return typeof value === "string" ? value : undefined; +} + +/** + * Normalize a resolved Claude effort value into one suitable for the Claude + * CLI's `--effort` flag. + * + * Mirrors the mapping used when invoking the Claude Agent SDK + * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a + * Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out + * because it is a prompt-prefix mode, and older model compatibility mappings + * are preserved for current Claude Code behavior. + */ +export function normalizeClaudeCliEffort( + effort: string | null | undefined, + model: string | null | undefined, +): string | undefined { + if (!effort || effort === "ultrathink") { + return undefined; + } + if (effort === "ultracode") { + return "xhigh"; + } + if ( + effort === "xhigh" && + model !== "claude-fable-5" && + model !== "claude-opus-5" && + model !== "claude-opus-4-8" && + model !== "claude-sonnet-5" + ) { + return "max"; + } + if (effort === "max" && model === "claude-sonnet-4-6") { + return "high"; + } + return effort; +} + +export function isClaudeUltracodeEffort(effort: string | null | undefined): boolean { + return effort === "ultracode"; +} + +export function resolveClaudeContextWindow( + modelSelection: ModelSelection | undefined, +): string | undefined { + const caps = getClaudeModelCapabilities(modelSelection?.model); + const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow"); + const descriptors = getProviderOptionDescriptors({ + caps, + ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}), + }); + const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow"); + const value = getProviderOptionCurrentValue(descriptor); + return typeof value === "string" ? value : undefined; +} + +export function resolveClaudeApiModelId(modelSelection: ModelSelection): string { + switch (resolveClaudeContextWindow(modelSelection)) { case "1m": return `${modelSelection.model}[1m]`; default: @@ -929,43 +1002,4 @@ export const makePendingClaudeProvider = ( }); }); -export const ClaudeProviderLive = Layer.effect( - ClaudeProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - - const subscriptionProbeCache = yield* Cache.make({ - capacity: 1, - timeToLive: Duration.minutes(5), - lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath), - }); - - const checkProvider = checkClaudeProviderStatus( - (binaryPath) => - Cache.get(subscriptionProbeCache, binaryPath).pipe( - Effect.map((probe) => probe?.subscriptionType), - ), - (binaryPath) => - Cache.get(subscriptionProbeCache, binaryPath).pipe( - Effect.map((probe) => probe?.slashCommands), - ), - ).pipe( - Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - - return yield* makeManagedServerProvider({ - getSettings: serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.claudeAgent), - Effect.orDie, - ), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.claudeAgent), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingClaudeProvider, - checkProvider, - }); - }), -); +export { probeClaudeCapabilities }; diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index e3ddfa9e98..5c0f76dff4 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,41 +1,463 @@ -import type { CodexSettings, ServerProvider, ServerProviderState } from "@t3tools/contracts"; -import { ServerSettingsError } from "@t3tools/contracts"; -import { Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Types from "effect/Types"; +import * as ChildProcess from "effect/unstable/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; +import * as CodexClient from "effect-codex-app-server/client"; +import * as CodexSchema from "effect-codex-app-server/schema"; import * as CodexErrors from "effect-codex-app-server/errors"; -import { ChildProcessSpawner } from "effect/unstable/process"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; -import { buildServerProvider } from "../providerSnapshot.ts"; +import type { + CodexSettings, + ServerProvider, + ServerProviderState, + ModelCapabilities, + ProviderOptionDescriptor, + ServerProviderModel, + ServerProviderSkill, +} from "@t3tools/contracts"; +import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts"; + +import { createModelCapabilities } from "@t3tools/shared/model"; +import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts"; import { - codexAccountAuthLabel, - probeCodexAppServerProvider, - type CodexAppServerProviderSnapshot, -} from "../codexAppServer.ts"; -import { CodexProvider } from "../Services/CodexProvider.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; + AUTH_PROBE_TIMEOUT_MS, + buildServerProvider, + type ServerProviderDraft, +} from "../providerSnapshot.ts"; +import { expandHomePath } from "../../pathExpansion.ts"; +import packageJson from "../../../package.json" with { type: "json" }; +const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError); -const PROVIDER = "codex" as const; -const PROVIDER_PROBE_TIMEOUT_MS = 8_000; +const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const; -const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => - codexSettings.customModels - .map((model) => model.trim()) - .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index) - .map((model) => ({ - slug: model, - name: model, +const CODEX_PRESENTATION = { + displayName: "Codex", + showInteractionModeToggle: true, +} as const; + +export interface CodexAppServerProviderSnapshot { + readonly account: CodexSchema.V2GetAccountResponse; + readonly version: string | undefined; + readonly models: ReadonlyArray; + readonly skills: ReadonlyArray; +} + +const REASONING_EFFORT_LABELS: Readonly> = { + none: "None", + minimal: "Minimal", + low: "Low", + medium: "Medium", + high: "High", + xhigh: "Extra High", + max: "Max", + ultra: "Ultra", +}; + +const DEFAULT_SERVICE_TIER_ID = "default"; +const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]); + +export function isLegacyCodexModel(model: string): boolean { + return !CURRENT_CODEX_MODELS.has(model); +} + +function reasoningEffortLabel(reasoningEffort: string): string { + return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort; +} + +function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) { + if (!account) return undefined; + if (account.type === "apiKey") return "OpenAI API Key"; + if (account.type === "amazonBedrock") return "Amazon Bedrock"; + if (account.type !== "chatgpt") return undefined; + + switch (account.planType) { + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro 20x Subscription"; + case "prolite": + return "ChatGPT Pro 5x Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "self_serve_business_usage_based": + case "business": + return "ChatGPT Business Subscription"; + case "enterprise_cbp_usage_based": + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + case "unknown": + return "ChatGPT Subscription"; + default: + account.planType satisfies never; + return undefined; + } +} + +function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) { + if (!account || account.type !== "chatgpt") return undefined; + return account.email; +} + +export function mapCodexModelCapabilities( + model: CodexSchema.V2ModelListResponse__Model, +): ModelCapabilities { + const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) => + reasoningEffort === model.defaultReasoningEffort + ? { + id: reasoningEffort, + label: reasoningEffortLabel(reasoningEffort), + isDefault: true, + } + : { + id: reasoningEffort, + label: reasoningEffortLabel(reasoningEffort), + }, + ); + const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id; + const serviceTiers = + model.serviceTiers && model.serviceTiers.length > 0 + ? model.serviceTiers + : (model.additionalSpeedTiers ?? []).map((id) => ({ + id, + name: id === "fast" ? "Fast" : id, + description: "", + })); + const catalogDefaultServiceTier = serviceTiers.some( + (tier) => tier.id === model.defaultServiceTier, + ) + ? model.defaultServiceTier + : null; + const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID; + const optionDescriptors: ProviderOptionDescriptor[] = []; + + if (reasoningOptions.length > 0) { + optionDescriptors.push({ + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: reasoningOptions, + ...(defaultReasoning ? { currentValue: defaultReasoning } : {}), + }); + } + if (serviceTiers.length > 0) { + optionDescriptors.push({ + id: "serviceTier", + label: "Service Tier", + type: "select", + options: [ + { + id: DEFAULT_SERVICE_TIER_ID, + label: "Standard", + ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}), + }, + ...serviceTiers.map((tier) => ({ + id: tier.id, + label: tier.name, + ...(tier.description ? { description: tier.description } : {}), + ...(defaultServiceTier === tier.id ? { isDefault: true } : {}), + })), + ], + currentValue: defaultServiceTier, + }); + } + + return createModelCapabilities({ + optionDescriptors, + }); +} + +const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => { + // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash + return model.displayName + .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT' + .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase()); +}; + +function parseCodexModelListResponse( + response: CodexSchema.V2ModelListResponse, +): ReadonlyArray { + return response.data.map((model) => ({ + slug: model.model, + name: toDisplayName(model), + isCustom: false, + ...(model.isDefault ? { isDefault: true } : {}), + ...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}), + capabilities: mapCodexModelCapabilities(model), + })); +} + +/** + * Prefer our own default-model ranking when one of the preferred slugs is in + * the live catalog; otherwise keep whatever Codex itself flagged as default. + */ +export function applyPreferredCodexDefaultModel( + models: ReadonlyArray, +): ReadonlyArray { + const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) => + models.some((model) => model.slug === slug && !model.isCustom), + ); + if (!preferredSlug) { + return models; + } + return models.map((model) => { + if (model.slug === preferredSlug) { + return model.isDefault ? model : { ...model, isDefault: true }; + } + if (!model.isDefault) { + return model; + } + const { isDefault: _isDefault, ...rest } = model; + return rest; + }); +} + +function appendCustomCodexModels( + models: ReadonlyArray, + customModels: ReadonlyArray, +): ReadonlyArray { + if (customModels.length === 0) { + return models; + } + + const seen = new Set(models.map((model) => model.slug)); + const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null; + const customEntries: ServerProviderModel[] = []; + for (const rawModel of customModels) { + const slug = rawModel.trim(); + if (!slug || seen.has(slug)) { + continue; + } + seen.add(slug); + customEntries.push({ + slug, + name: slug, isCustom: true, - capabilities: null, - })); + capabilities: fallbackCapabilities, + }); + } + return customEntries.length === 0 ? models : [...models, ...customEntries]; +} -const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => { - const checkedAt = new Date().toISOString(); - const models = emptyCodexModelsFromSettings(codexSettings); +function parseCodexSkillsListResponse( + response: CodexSchema.V2SkillsListResponse, + cwd: string, +): ReadonlyArray { + const matchingEntry = response.data.find((entry) => entry.cwd === cwd); + const skills = matchingEntry + ? matchingEntry.skills + : response.data.flatMap((entry) => entry.skills); + + return skills.map((skill) => { + const shortDescription = + skill.shortDescription ?? skill.interface?.shortDescription ?? undefined; + + const parsedSkill: Types.Mutable = { + name: skill.name, + path: skill.path, + enabled: skill.enabled, + }; + + if (skill.description) { + parsedSkill.description = skill.description; + } + if (skill.scope) { + parsedSkill.scope = skill.scope; + } + if (skill.interface?.displayName) { + parsedSkill.displayName = skill.interface.displayName; + } + if (shortDescription) { + parsedSkill.shortDescription = shortDescription; + } + + return parsedSkill; + }); +} + +const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* ( + client: CodexClient.CodexAppServerClient["Service"], +) { + const models: ServerProviderModel[] = []; + let cursor: string | null | undefined = undefined; + + do { + const response: CodexSchema.V2ModelListResponse = yield* client.request( + "model/list", + cursor ? { cursor } : {}, + ); + models.push(...parseCodexModelListResponse(response)); + cursor = response.nextCursor; + } while (cursor); + + return models; +}); + +export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams { + return { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: packageJson.version, + }, + capabilities: { + experimentalApi: true, + }, + }; +} + +const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly launchArgs?: string; + readonly cwd: string; + readonly customModels?: ReadonlyArray; + readonly environment?: NodeJS.ProcessEnv; +}) { + // `~` is not shell-expanded when env vars are set via `child_process.spawn`, + // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip + // "CODEX_HOME points to '~/.codex_work', but that path does not exist". + // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`. + const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const environment = { + ...input.environment, + ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}), + }; + const spawnCommand = yield* resolveSpawnCommand( + input.binaryPath, + codexAppServerArgs(input.launchArgs), + { + env: environment, + extendEnv: true, + }, + ); + const child = yield* spawner + .spawn( + ChildProcess.make(spawnCommand.command, spawnCommand.args, { + cwd: input.cwd, + env: environment, + extendEnv: true, + forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER, + shell: spawnCommand.shell, + }), + ) + .pipe( + Effect.mapError( + (cause) => + new CodexErrors.CodexAppServerSpawnError({ + command: `${input.binaryPath} app-server`, + cause, + }), + ), + ); + const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child)); + const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.provide(clientContext), + ); + + const initialize = yield* client.request("initialize", { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, + }, + }); + yield* client.notify("initialized", undefined); + + // Extract the version string after the first '/' in userAgent, up to the next space or the end + const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); + const version = versionMatch ? versionMatch[1] : undefined; + + const accountResponse = yield* client.request("account/read", {}); + if (!accountResponse.account && accountResponse.requiresOpenaiAuth) { + return { + account: accountResponse, + version, + models: appendCustomCodexModels([], input.customModels ?? []), + skills: [], + } satisfies CodexAppServerProviderSnapshot; + } + + const [skillsResponse, models] = yield* Effect.all( + [ + client.request("skills/list", { + cwds: [input.cwd], + }), + requestAllCodexModels(client), + ], + { concurrency: "unbounded" }, + ); + + return { + account: accountResponse, + version, + models: applyPreferredCodexDefaultModel( + appendCustomCodexModels(models, input.customModels ?? []), + ), + skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), + } satisfies CodexAppServerProviderSnapshot; +}); + +const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => { + const models = new Set(); + for (const model of codexSettings.customModels) { + const trimmed = model.trim(); + if (trimmed.length > 0) { + models.add(trimmed); + } + } + return Array.from(models, (model) => ({ + slug: model, + name: model, + isCustom: true, + capabilities: null, + })); +}; + +const makePendingCodexProvider = ( + codexSettings: CodexSettings, +): Effect.Effect => + Effect.gen(function* () { + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso); + const models = emptyCodexModelsFromSettings(codexSettings); + + if (!codexSettings.enabled) { + return buildServerProvider({ + presentation: CODEX_PRESENTATION, + enabled: false, + checkedAt, + models, + skills: [], + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex is disabled in T3 Code settings.", + }, + }); + } - if (!codexSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, - enabled: false, + presentation: CODEX_PRESENTATION, + enabled: true, checkedAt, models, skills: [], @@ -44,26 +466,10 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider version: null, status: "warning", auth: { status: "unknown" }, - message: "Codex is disabled in T3 Code settings.", + message: "Codex provider status has not been checked in this session yet.", }, }); - } - - return buildServerProvider({ - provider: PROVIDER, - enabled: true, - checkedAt, - models, - skills: [], - probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: "Codex provider status has not been checked in this session yet.", - }, }); -}; function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): { readonly status: Exclude; @@ -71,10 +477,12 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): readonly message?: string; } { const authLabel = codexAccountAuthLabel(account.account); + const authEmail = codexAccountEmail(account.account); const auth = { status: account.account ? ("authenticated" as const) : ("unknown" as const), ...(account.account?.type ? { type: account.account?.type } : {}), ...(authLabel ? { label: authLabel } : {}), + ...(authEmail ? { email: authEmail } : {}), } satisfies ServerProvider["auth"]; if (account.account) { @@ -93,31 +501,32 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): } export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + codexSettings: CodexSettings, probe: (input: { readonly binaryPath: string; readonly homePath?: string; + readonly launchArgs?: string; readonly cwd: string; readonly customModels: ReadonlyArray; + readonly environment?: NodeJS.ProcessEnv; }) => Effect.Effect< CodexAppServerProviderSnapshot, CodexErrors.CodexAppServerError, - ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope > = probeCodexAppServerProvider, + environment?: NodeJS.ProcessEnv, ): Effect.fn.Return< - ServerProvider, + ServerProviderDraft, ServerSettingsError, - ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner > { - const codexSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.codex), - ); - const checkedAt = new Date().toISOString(); + const resolvedEnvironment = environment ?? process.env; + const checkedAt = DateTime.formatIso(yield* DateTime.now); const emptyModels = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: false, checkedAt, models: emptyModels, @@ -132,95 +541,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu }); } - const probeResult = yield* probe({ - binaryPath: codexSettings.binaryPath, - homePath: codexSettings.homePath, - cwd: process.cwd(), - customModels: codexSettings.customModels, - }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result); - - if (Result.isFailure(probeResult)) { - const error = probeResult.failure; - const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: emptyModels, - skills: [], - probe: { - installed, - version: null, - status: "error", - auth: { status: "unknown" }, - message: installed - ? `Codex app-server provider probe failed: ${error.message}.` - : "Codex CLI (`codex`) is not installed or not on PATH.", - }, - }); - } - - if (Option.isNone(probeResult.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: emptyModels, - skills: [], - probe: { - installed: true, - version: null, - status: "error", - auth: { status: "unknown" }, - message: "Timed out while checking Codex app-server provider status.", - }, - }); - } - - const snapshot = probeResult.success.value; - const accountStatus = accountProbeStatus(snapshot.account); - - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: snapshot.models, - skills: snapshot.skills, - probe: { - installed: true, - version: snapshot.version ?? null, - status: accountStatus.status, - auth: accountStatus.auth, - ...(accountStatus.message ? { message: accountStatus.message } : {}), - }, - }); -}); - -export const CodexProviderLive = Layer.effect( - CodexProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const checkProvider = checkCodexProviderStatus().pipe( - Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - - return yield* makeManagedServerProvider({ - getSettings: serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - Effect.orDie, - ), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.codex), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingCodexProvider, - checkProvider, - refreshInterval: Duration.minutes(5), - }); - } - const probeResult = yield* probe({ binaryPath: codexSettings.binaryPath, homePath: codexSettings.homePath, diff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts index 87d6eaebca..3e9631c83e 100644 --- a/apps/server/src/provider/Layers/CursorProvider.ts +++ b/apps/server/src/provider/Layers/CursorProvider.ts @@ -7,7 +7,6 @@ import type { ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; -import { ProviderDriverKind } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -24,7 +23,6 @@ import { } from "../providerSnapshot.ts"; import { CursorSdkCatalog } from "./CursorSdkCatalog.ts"; -const PROVIDER = ProviderDriverKind.make("cursor"); const CURSOR_PRESENTATION = { displayName: "Cursor", showInteractionModeToggle: true, @@ -77,7 +75,7 @@ export function buildInitialCursorProviderSnapshot( export function getCursorFallbackModels( cursorSettings: Pick, ): ReadonlyArray { - return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES); + return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES); } function toTitleCaseWords(value: string): string { diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 101475558d..32f6448dab 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1,8 +1,21 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert } from "@effect/vitest"; -import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect"; +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 PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as CodexErrors from "effect-codex-app-server/errors"; import { + ClaudeSettings, + CodexSettings, DEFAULT_SERVER_SETTINGS, ProviderDriverKind, ProviderInstanceId, @@ -18,8 +31,12 @@ import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; -import { checkCodexProviderStatus } from "./CodexProvider.ts"; -import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; +import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; +import { checkClaudeProviderStatus } from "./ClaudeProvider.ts"; +import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; +import * as OpenCodeRuntime from "../opencodeRuntime.ts"; +import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; +import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts"; import { haveProvidersChanged, mergeProviderSnapshot, @@ -27,16 +44,98 @@ import { ProviderRegistryLive, selectProvidersByKind, } from "./ProviderRegistry.ts"; -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts"; -import { ProviderRegistry } from "../Services/ProviderRegistry.ts"; -import type { CodexAppServerProviderSnapshot } from "../codexAppServer.ts"; +import * as ServerConfig from "../../config.ts"; +import * as ServerSettingsModule from "../../serverSettings.ts"; +import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts"; +import type { ProviderInstance } from "../ProviderDriver.ts"; +import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts"; +import * as ProviderRegistry from "../Services/ProviderRegistry.ts"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; +const decodeServerSettings = Schema.decodeSync(ServerSettings); +const encodeServerSettings = Schema.encodeSync(ServerSettings); +const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS); + +const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({}); +const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({}); +const decodeCodexSettings = Schema.decodeSync(CodexSettings); +const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({ + enabled: false, +}); process.env.T3CODE_CURSOR_ENABLED = "1"; // ── Test helpers ──────────────────────────────────────────────────── const encoder = new TextEncoder(); +const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); + +const TestHttpClientLive = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))), + ), +); + +const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + reportClientActivity: () => Effect.void, + removeRpcClient: () => Effect.void, + reportHostPowerState: () => Effect.void, + snapshot: Effect.succeed({ + hostPower: { + source: "unknown", + idle: "unknown", + idleSeconds: null, + locked: "unknown", + suspended: false, + onBattery: "unknown", + lowPowerMode: "unknown", + thermalState: "unknown", + stale: true, + updatedAt: TEST_EPOCH, + }, + leases: [], + activeForegroundLeaseCount: 0, + activeScopeKeys: [], + shouldRunOpportunisticWork: true, + updatedAt: TEST_EPOCH, + }), + streamChanges: Stream.empty, + hasDemand: () => Effect.succeed(true), + shouldRunScopeWork: () => Effect.succeed(true), + shouldRunOpportunisticWork: Effect.succeed(true), +}); + +function selectDescriptor( + id: string, + label: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, +) { + return { + id, + label, + type: "select" as const, + options: [...options], + ...(options.find((option) => option.isDefault)?.id + ? { currentValue: options.find((option) => option.isDefault)?.id } + : {}), + }; +} + +function booleanDescriptor(id: string, label: string) { + return { + id, + label, + type: "boolean" as const, + }; +} + +type TestClaudeCapabilities = { + readonly email: string | undefined; + readonly subscriptionType: string | undefined; + readonly tokenSource: string | undefined; + readonly apiProvider: string | undefined; + readonly slashCommands: ReadonlyArray; +}; function claudeCapabilities(overrides: Partial = {}) { return () => @@ -146,16 +245,40 @@ function failingSpawnerLayer(description: string) { ); } -const codexModelCapabilities = { - reasoningEffortLevels: [ - { value: "high", label: "High", isDefault: true }, - { value: "low", label: "Low" }, +function hangingScopedSpawnerLayer(killCalls: Ref.Ref) { + return Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const handle = ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + kill: () => Ref.update(killCalls, (current) => current + 1), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.never, + stderr: Stream.never, + all: Stream.never, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); + return handle; + }), + ), + ); +} + +const codexModelCapabilities = createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + { id: "low", label: "Low" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -} satisfies NonNullable; +}) satisfies NonNullable; function makeCodexProbeSnapshot( input: Partial = {}, @@ -215,13 +338,13 @@ function makeMutableServerSettingsService( }); } -it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( +it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TestHttpClientLive))( "ProviderRegistry", (it) => { describe("checkCodexProviderStatus", () => { it.effect("uses the app-server account and model list for provider status", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ skills: [ @@ -236,14 +359,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ), ); - - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); assert.strictEqual(status.version, "1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "chatgpt"); - assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); + assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription"); + assert.strictEqual(status.auth.email, "test@example.com"); assert.deepStrictEqual(status.models, [ { slug: "gpt-live-codex", @@ -264,9 +386,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ); + it.effect("passes configured launch args to the Codex provider probe", () => + Effect.gen(function* () { + let observedLaunchArgs: string | undefined; + const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" }); + + const status = yield* checkCodexProviderStatus(settings, (input) => { + observedLaunchArgs = input.launchArgs; + return Effect.succeed(makeCodexProbeSnapshot()); + }); + + assert.strictEqual(status.status, "ready"); + assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo"); + }), + ); + it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -290,7 +427,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "returns ready with unknown auth when app-server does not require OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -308,7 +445,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns an api key label for codex api key auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -326,9 +463,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ); + it.effect("returns an Amazon Bedrock label for codex Bedrock auth", () => + Effect.gen(function* () { + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: { type: "amazonBedrock" }, + requiresOpenaiAuth: false, + }, + }), + ), + ); + + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "amazonBedrock"); + assert.strictEqual(status.auth.label, "Amazon Bedrock"); + }), + ); + it.effect("returns unavailable when codex is missing", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.fail( new CodexErrors.CodexAppServerSpawnError({ command: "codex app-server", @@ -336,7 +493,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ), ); - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); assert.strictEqual(status.auth.status, "unknown"); @@ -346,6 +502,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ); }), ); + + it.effect("closes the app-server probe scope when provider status times out", () => + Effect.gen(function* () { + const killCalls = yield* Ref.make(0); + const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( + Effect.provide(hangingScopedSpawnerLayer(killCalls)), + Effect.forkChild, + ); + + yield* Effect.yieldNow; + yield* TestClock.adjust("11 seconds"); + yield* Effect.yieldNow; + + const status = yield* Fiber.join(statusFiber); + assert.strictEqual(status.status, "error"); + assert.strictEqual( + status.message, + "Timed out while checking Codex app-server provider status.", + ); + assert.strictEqual(yield* Ref.get(killCalls), 1); + }), + ); }); describe("ProviderRegistryLive", () => { @@ -643,14 +821,36 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("does not run provider probes during layer construction", () => Effect.gen(function* () { - let spawnCount = 0; - const serverSettings = yield* makeMutableServerSettingsService( - Schema.decodeSync(ServerSettings)( - deepMerge(DEFAULT_SERVER_SETTINGS, { - providers: { - codex: { enabled: false }, - cursor: { enabled: false }, - }, + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const initialProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "warning", + enabled: true, + installed: false, + auth: { status: "unknown" }, + checkedAt: "2026-06-10T00:00:00.000Z", + version: null, + message: "Checking Codex provider status.", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshCalls = yield* Ref.make(0); + const instance = { + instanceId: codexInstanceId, + driverKind: codexDriver, + continuationIdentity: { + driverKind: codexDriver, + continuationKey: "codex:instance:codex", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: codexDriver, + packageName: null, }), getSnapshot: Effect.succeed(initialProvider), refresh: Ref.update(refreshCalls, (count) => count + 1).pipe( @@ -684,17 +884,128 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), Layer.provideMerge(NodeServices.layer), ), - Layer.provideMerge( - mockCommandSpawnerLayer((command, args) => { - spawnCount += 1; - const joined = args.join(" "); - if (joined === "--version") { - return { stdout: "claude 1.0.0\n", stderr: "", code: 0 }; - } - if (joined === "auth status") { - return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; - } - throw new Error(`Unexpected args: ${command} ${joined}`); + ).pipe(Scope.provide(scope)); + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]); + assert.strictEqual(yield* Ref.get(refreshCalls), 0); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it("persists merged provider snapshots for the providers that were refreshed", () => { + const previousProviders = [ + { + instanceId: ProviderInstanceId.make("cursor"), + driver: ProviderDriverKind.make("cursor"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-14T00:00:00.000Z", + version: "2026.04.09-f2b0fcd", + models: [ + { + slug: "claude-opus-4-6", + name: "Opus 4.6", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + booleanDescriptor("thinking", "Thinking"), + ], + }), + }, + ], + slashCommands: [], + skills: [], + }, + { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-14T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + }, + ] as const satisfies ReadonlyArray; + const refreshedCursor = { + ...previousProviders[0], + checkedAt: "2026-04-14T00:01:00.000Z", + models: [], + } satisfies ServerProvider; + + const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]); + const persistedProviders = selectProvidersByKind( + mergedProviders, + new Set([ProviderDriverKind.make("cursor")]), + ); + + assert.deepStrictEqual(persistedProviders, [ + { + ...refreshedCursor, + models: [...previousProviders[0].models], + }, + ]); + }); + + it.effect("persists the merged snapshot when a live update has empty models", () => + Effect.gen(function* () { + const cursorDriver = ProviderDriverKind.make("cursor"); + const cursorInstanceId = ProviderInstanceId.make("cursor"); + const initialProvider = { + instanceId: cursorInstanceId, + driver: cursorDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-14T00:00:00.000Z", + version: "2026.04.09-f2b0fcd", + models: [ + { + slug: "claude-opus-4-6", + name: "Opus 4.6", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + ]), + ], + }), + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshedProvider = { + ...initialProvider, + checkedAt: "2026-04-14T00:01:00.000Z", + models: [], + } satisfies ServerProvider; + const changes = yield* PubSub.unbounded(); + const instance = { + instanceId: cursorInstanceId, + driverKind: cursorDriver, + continuationIdentity: { + driverKind: cursorDriver, + continuationKey: "cursor:instance:cursor", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: cursorDriver, + packageName: null, }), getSnapshot: Effect.succeed(initialProvider), refresh: Effect.succeed(refreshedProvider), @@ -732,8 +1043,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ).pipe(Scope.provide(scope)); yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; - const config = yield* ServerConfig; + const registry = yield* ProviderRegistry.ProviderRegistry; + const config = yield* ServerConfig.ServerConfig; const filePath = yield* resolveProviderStatusCachePath({ cacheDir: config.providerStatusCacheDir, instanceId: cursorInstanceId, @@ -763,6 +1074,144 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ); + it.effect( + "persists authoritative OpenCode removals without resurrecting them on a failed live refresh", + () => + Effect.gen(function* () { + const openCodeDriver = ProviderDriverKind.make("opencode"); + const openCodeInstanceId = ProviderInstanceId.make("opencode"); + const initialProvider = { + instanceId: openCodeInstanceId, + driver: openCodeDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-07-17T00:00:00.000Z", + version: "1.0.0", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + { + slug: "removed-plugin/model", + name: "Removed Plugin Model", + subProvider: "Removed Plugin", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const authoritativeProvider = { + ...initialProvider, + checkedAt: "2026-07-17T00:01:00.000Z", + models: [initialProvider.models[0]!], + } satisfies ServerProvider; + const failedProvider = { + ...authoritativeProvider, + status: "error", + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:02:00.000Z", + models: [], + message: "Failed to refresh OpenCode models.", + } satisfies ServerProvider; + const changes = yield* PubSub.unbounded(); + const instance = { + instanceId: openCodeInstanceId, + driverKind: openCodeDriver, + continuationIdentity: { + driverKind: openCodeDriver, + continuationKey: "opencode:instance:opencode", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: openCodeDriver, + packageName: null, + }), + getSnapshot: Effect.succeed(initialProvider), + refresh: Effect.succeed(authoritativeProvider), + streamChanges: Stream.fromPubSub(changes), + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (instanceId) => + Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }, + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-opencode-authoritative-persist-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const config = yield* ServerConfig.ServerConfig; + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: openCodeInstanceId, + }); + + yield* PubSub.publish(changes, authoritativeProvider); + + let cachedProvider = yield* readProviderStatusCache(filePath); + for ( + let attempt = 0; + attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt; + attempt += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + cachedProvider = yield* readProviderStatusCache(filePath); + } + + assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); + + yield* PubSub.publish(changes, failedProvider); + for ( + let attempt = 0; + attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt; + attempt += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + cachedProvider = yield* readProviderStatusCache(filePath); + } + + assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); + assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [ + authoritativeProvider.models[0]!, + ]); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it.effect("returns the cached provider list when a manual refresh fails", () => Effect.gen(function* () { const codexDriver = ProviderDriverKind.make("codex"); @@ -801,16 +1250,19 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; - const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { - getInstance: (instanceId) => - Effect.succeed(instanceId === codexInstanceId ? instance : undefined), - listInstances: Effect.succeed([instance]), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }); + const instanceRegistryLayer = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (instanceId) => + Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }, + ); const scope = yield* Scope.make(); yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( @@ -821,12 +1273,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( prefix: "t3-provider-registry-refresh-failure-", }), ), + Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), Layer.provideMerge(NodeServices.layer), ), ).pipe(Scope.provide(scope)); yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; + const registry = yield* ProviderRegistry.ProviderRegistry; assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]); assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]); @@ -896,25 +1349,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const instancesRef = yield* Ref.make>([codexInstance]); const failNextList = yield* Ref.make(false); const wait = () => Effect.yieldNow; - const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { - getInstance: (instanceId) => - Ref.get(instancesRef).pipe( - Effect.map((instances) => - instances.find((instance) => instance.instanceId === instanceId), + const instanceRegistryLayer = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (instanceId) => + Ref.get(instancesRef).pipe( + Effect.map((instances) => + instances.find((instance) => instance.instanceId === instanceId), + ), ), - ), - listInstances: Effect.gen(function* () { - const shouldFail = yield* Ref.get(failNextList); - if (shouldFail) { - yield* Ref.set(failNextList, false); - return yield* Effect.die(new Error("simulated registry list failure")); - } - return yield* Ref.get(instancesRef); - }), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.fromPubSub(changes), - subscribeChanges: PubSub.subscribe(changes), - }); + listInstances: Effect.gen(function* () { + const shouldFail = yield* Ref.get(failNextList); + if (shouldFail) { + yield* Ref.set(failNextList, false); + return yield* Effect.die(new Error("simulated registry list failure")); + } + return yield* Ref.get(instancesRef); + }), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }, + ); const scope = yield* Scope.make(); yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const runtimeServices = yield* Layer.build( @@ -925,12 +1381,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( prefix: "t3-provider-registry-sync-failure-", }), ), + Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), Layer.provideMerge(NodeServices.layer), ), ).pipe(Scope.provide(scope)); yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; + const registry = yield* ProviderRegistry.ProviderRegistry; assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]); yield* Ref.set(failNextList, true); @@ -1013,15 +1470,23 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const providerRegistryLayer = ProviderRegistryLive.pipe( Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), + ), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-", }), ), Layer.provideMerge(TestHttpClientLive), - Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), - Layer.provideMerge(OpenCodeRuntimeLive), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), + Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), // NO spawner mock — `ChildProcessSpawner` is supplied by the // outer `NodeServices.layer` on `it.layer(...)` and will // genuinely spawn a subprocess. The missing-binary ENOENT is @@ -1033,7 +1498,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ); yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; + const registry = yield* ProviderRegistry.ProviderRegistry; let providers = yield* registry.getProviders; for ( let attempts = 0; @@ -1098,15 +1563,22 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const providerRegistryLayer = ProviderRegistryLive.pipe( Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), + ), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-", }), ), Layer.provideMerge(TestHttpClientLive), - Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), - Layer.provideMerge(OpenCodeRuntimeLive), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) => ChildProcessSpawner.make((command) => { spawnedCommands.push((command as { readonly command: string }).command); @@ -1114,13 +1586,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ), Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), ); const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( Scope.provide(scope), ); yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; + const registry = yield* ProviderRegistry.ProviderRegistry; // Boot-time probe: the default codex instance is enabled with // `firstMissing`, so the real spawner yields ENOENT and the // snapshot should be `status: "error"`. @@ -1161,22 +1634,89 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( // executable. This verifies the public settings-to-probe behavior // without depending on timestamps assigned by TestClock. const refreshed = yield* Effect.gen(function* () { - for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { + for (let attempts = 0; attempts < 60; attempts += 1) { const providers = yield* registry.getProviders; - const claudeProvider = providers.find( - (provider) => provider.provider === "claudeAgent", - ); - if (claudeProvider?.status === "ready") { + const codex = providers.find((provider) => provider.instanceId === "codex"); + if ( + codex !== undefined && + codex.status === "error" && + spawnedCommands.includes(secondMissing) + ) { return providers; } - yield* Effect.sleep("10 millis"); + yield* TestClock.adjust("50 millis"); + yield* Effect.yieldNow; } return yield* registry.getProviders; }); - assert.strictEqual( - refreshed.find((provider) => provider.provider === "claudeAgent")?.status, - "ready", - ); + + const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex"); + assert.deepStrictEqual(spawnedCommands, [firstMissing, secondMissing]); + assert.strictEqual(reprobedCodex?.status, "error"); + assert.strictEqual(reprobedCodex?.installed, false); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("includes unavailable instance snapshots in getProviders", () => + Effect.gen(function* () { + const serverSettings = yield* makeMutableServerSettingsService( + decodeServerSettings( + deepMerge(encodedDefaultServerSettings, { + providers: { + codex: { enabled: false }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + grok: { enabled: false }, + opencode: { enabled: false }, + }, + providerInstances: { + ghost_main: { + driver: "ghostDriver", + displayName: "A fork-only driver we don't ship", + enabled: false, + config: { arbitrary: "payload" }, + }, + } as unknown as ContractServerSettings["providerInstances"], + }), + ), + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + Layer.provideMerge( + Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-", + }), + ), + Layer.provideMerge(TestHttpClientLive), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), + ); + const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( + Scope.provide(scope), + ); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const providers = yield* registry.getProviders; + const ghost = providers.find((provider) => provider.instanceId === "ghost_main"); + + assert.notStrictEqual(ghost, undefined); + assert.strictEqual(ghost?.driver, "ghostDriver"); + assert.strictEqual(ghost?.availability, "unavailable"); + assert.match(ghost?.unavailableReason ?? "", /ghostDriver/); }).pipe(Effect.provide(runtimeServices)); }), ); @@ -1231,7 +1771,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( } const joined = args.join(" "); if (joined === "--version") { - return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 }; + return { + stdout: `${command} 1.0.0\n`, + stderr: "", + code: 0, + }; } if (joined === "auth status") { return { diff --git a/apps/server/src/provider/Layers/scopedSafeTeardown.ts b/apps/server/src/provider/Layers/scopedSafeTeardown.ts deleted file mode 100644 index f1840c5fed..0000000000 --- a/apps/server/src/provider/Layers/scopedSafeTeardown.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * scopedSafeTeardown — run a scope-requiring effect so that finalizer - * failures during scope close cannot override the body's Exit. - * - * Motivation - * ---------- - * The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh - * Scope, run the body, close the scope with the body's Exit. If a - * finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server - * spawn) dies during that close, the combined Exit becomes the - * finalizer's defect — even when the body already succeeded. - * - * Concretely this bit us in the Codex provider probe: a successful - * `initialize` → `account/read` → `skills/list` → `model/list` - * round-trip produced a `CodexAppServerProviderSnapshot`, but the - * `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to - * kill the `codex app-server` subprocess with a `PlatformError`. The - * defect bubbled past `Effect.result` in `checkCodexProviderStatus`, - * died `refreshOneSource`, and `providersRef` never saw the snapshot. - * - * Strategy - * -------- - * 1. Make a fresh scope manually. - * 2. Run the body against that scope, capturing its Exit via - * `Effect.exit`. - * 3. Run the body inside an interruptible region, but capture the Exit from - * success, failure, defect, or interruption. - * 4. Close the scope, catching any cause (typed failure *or* defect) - * with a log. - * 5. Replay the captured Exit so typed body failures still surface and - * successes still return their value. - * - * The helper deliberately logs teardown causes at `Warning` level — - * silently swallowing them is dangerous because they usually indicate a - * real bug in a downstream Layer's finalizer. - * - * @module provider/Layers/scopedSafeTeardown - */ -import * as Effect from "effect/Effect"; -import * as Scope from "effect/Scope"; - -/** - * Run `effect` with a freshly made `Scope.Scope`, guaranteeing that - * teardown failures cannot override the body's Exit. - * - * Shape matches `Effect.scoped`: takes an effect whose env includes - * `Scope.Scope`, returns one whose env excludes it. - * - * @param label Short label for the warning log emitted when teardown - * fails. Use something like `"codex-probe"`. - */ -export const scopedSafeTeardown = - (label: string) => - (effect: Effect.Effect): Effect.Effect> => - Effect.uninterruptibleMask((restore) => - Effect.gen(function* () { - const scope = yield* Scope.make(); - - const bodyExit = yield* effect.pipe( - restore, - Effect.provideService(Scope.Scope, scope), - Effect.exit, - ); - - yield* Scope.close(scope, bodyExit).pipe( - Effect.catchCause((cause) => - Effect.logWarning(`${label} teardown errored; preserving body result`, cause), - ), - ); - return yield* bodyExit; - }), - ) as Effect.Effect>; diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 3d51a83504..03428fb80e 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -14,11 +14,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as Stream from "effect/Stream"; import { describe, expect } from "vite-plus/test"; -import { - AcpSessionRuntime, - selectAcpAgentAuthMethod, - type AcpSessionRequestLogEvent, -} from "./AcpSessionRuntime.ts"; +import * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; import type * as EffectAcpProtocol from "effect-acp/protocol"; const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); @@ -33,9 +29,9 @@ describe("AcpSessionRuntime", () => { { id: "api-key", name: "API key" }, ]; - expect(selectAcpAgentAuthMethod(methods)?.id).toBe("api-key"); - expect(selectAcpAgentAuthMethod(methods, "browser")?.id).toBe("browser"); - expect(selectAcpAgentAuthMethod(methods, "missing")).toBeUndefined(); + expect(AcpSessionRuntime.selectAcpAgentAuthMethod(methods)?.id).toBe("api-key"); + expect(AcpSessionRuntime.selectAcpAgentAuthMethod(methods, "browser")?.id).toBe("browser"); + expect(AcpSessionRuntime.selectAcpAgentAuthMethod(methods, "missing")).toBeUndefined(); }); it.effect("merges custom initialize client capabilities into the ACP handshake", () => { @@ -82,9 +78,9 @@ describe("AcpSessionRuntime", () => { }); it.effect("does not authenticate when an advertised method is not required", () => { - const requestEvents: Array = []; + const requestEvents: Array = []; return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime; + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; yield* runtime.start(); expect( @@ -113,9 +109,9 @@ describe("AcpSessionRuntime", () => { }); it.effect("authenticates and retries once after session creation returns auth_required", () => { - const requestEvents: Array = []; + const requestEvents: Array = []; return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime; + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; const started = yield* runtime.start(); expect(started.sessionId).toBe("mock-session-1"); @@ -518,8 +514,8 @@ describe("AcpSessionRuntime", () => { AcpSessionRuntime.layer({ authMethodId: "test", spawn: { - command: bunExe, - args: [mockAgentPath], + command: mockAgentCommand, + args: mockAgentArgs, }, cwd: process.cwd(), clientInfo: { name: "t3-test", version: "0.0.0" }, @@ -535,9 +531,9 @@ describe("AcpSessionRuntime", () => { }); it.effect("supports negotiated ACP session list, fork, resume, and close methods", () => { - const requestEvents: Array = []; + const requestEvents: Array = []; return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime; + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; const started = yield* runtime.start(); expect(started.initializeResult.agentCapabilities?.sessionCapabilities).toMatchObject({ list: {}, @@ -641,9 +637,9 @@ describe("AcpSessionRuntime", () => { ); it.effect("skips no-op session config writes when the requested value is already active", () => { - const requestEvents: Array = []; + const requestEvents: Array = []; return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime; + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; yield* runtime.start(); yield* runtime.setConfigOption("model", "default"); @@ -926,7 +922,7 @@ describe("AcpSessionRuntime", () => { expect(error.message).toContain("composer-2[fast=true]"); } - const recordedRequests = readFileSync(requestLogPath, "utf8") + const recordedRequests = NodeFS.readFileSync(requestLogPath, "utf8") .trim() .split("\n") .filter((line) => line.length > 0) @@ -955,7 +951,7 @@ describe("AcpSessionRuntime", () => { ), Effect.scoped, Effect.provide(NodeServices.layer), - Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))), + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))), ); }); }); diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 3c6c47a0fd..8390821895 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -1279,13 +1279,13 @@ export const make = ( ): Effect.Effect< AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope > => Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runtimeScope = yield* Scope.Scope; - const eventQueue = yield* Queue.unbounded(); + const eventQueue = yield* Queue.unbounded(); const modeStateRef = yield* Ref.make(undefined); const toolCallsRef = yield* Ref.make(new Map()); const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe( @@ -1638,7 +1638,6 @@ export const make = ( }); }), ); - const initializeClientCapabilities = { fs: { readTextFile: false, @@ -2054,6 +2053,14 @@ export const make = ( handleExtNotification: acp.handleExtNotification, start: () => start, getEvents: () => Stream.fromQueue(eventQueue), + drainEvents: Effect.gen(function* () { + const acknowledge = yield* Deferred.make(); + yield* Queue.offer(eventQueue, { + _tag: "EventStreamBarrier", + acknowledge, + }); + yield* Deferred.await(acknowledge); + }), getModeState: Ref.get(modeStateRef), getConfigOptions: Ref.get(configOptionsRef), loadSession: (sessionId, activationOptions) => @@ -2227,7 +2234,7 @@ export const make = ( request: (method, payload) => runLoggedRequest(method, payload, acp.raw.request(method, payload)), notify: acp.raw.notify, - } satisfies AcpSessionRuntimeShape; + } satisfies AcpSessionRuntime["Service"]; }); export const layer = ( diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.ts index 6842c37f7f..0e0705164a 100644 --- a/apps/server/src/provider/acp/GrokAcpSupport.ts +++ b/apps/server/src/provider/acp/GrokAcpSupport.ts @@ -22,7 +22,10 @@ const GROK_DRIVER_KIND = ProviderDriverKind.make("grok"); type GrokAcpRuntimeGrokSettings = Pick; -interface GrokAcpRuntimeInput extends Omit { +interface GrokAcpRuntimeInput extends Omit< + AcpSessionRuntime.AcpSessionRuntimeOptions, + "authMethodId" | "clientCapabilities" | "spawn" +> { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined; readonly environment?: NodeJS.ProcessEnv; diff --git a/apps/server/src/provider/codex/CodexDeveloperInstructions.ts b/apps/server/src/provider/codex/CodexDeveloperInstructions.ts deleted file mode 100644 index 76055f8b8b..0000000000 --- a/apps/server/src/provider/codex/CodexDeveloperInstructions.ts +++ /dev/null @@ -1,134 +0,0 @@ -export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) - -You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. - -## Mode rules (strict) - -You are in **Plan Mode** until a developer message explicitly ends it. - -Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. - -## Plan Mode vs update_plan tool - -Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`\` block. - -Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error. - -## Execution vs. mutation in Plan Mode - -You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. - -### Allowed (non-mutating, plan-improving) - -Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples: - -* Reading or searching files, configs, schemas, types, manifests, and docs -* Static analysis, inspection, and repo exploration -* Dry-run style commands when they do not edit repo-tracked files -* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files - -### Not allowed (mutating, plan-executing) - -Actions that implement the plan or change repo-tracked state. Examples: - -* Editing or writing files -* Running formatters or linters that rewrite files -* Applying patches, migrations, or codegen that updates repo-tracked files -* Side-effectful commands whose purpose is to carry out the plan rather than refine it - -When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it. - -## PHASE 1 - Ground in the environment (explore first, ask second) - -Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. - -Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. - -Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first. - -Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. - -## PHASE 2 - Intent chat (what they actually want) - -* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs. -* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask. - -## PHASE 3 - Implementation chat (what/how we'll build) - -* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints. - -## Asking questions - -Critical rules: - -* Strongly prefer using the \`request_user_input\` tool to ask any questions. -* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant. -* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool. - -You SHOULD ask many questions, but each question must: - -* materially change the spec/plan, OR -* confirm/lock an assumption, OR -* choose between meaningful tradeoffs. -* not be answerable by non-mutating commands. - -Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration. - -## Two kinds of unknowns (treat differently) - -1. **Discoverable facts** (repo/system truth): explore first. - - * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants). - * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent. - * If asking, present concrete candidates (paths/service names) + recommend one. - * Never ask questions you can answer from your environment (e.g., "where is this struct"). - -2. **Preferences/tradeoffs** (not discoverable): ask early. - - * These are intent or implementation preferences that cannot be derived from exploration. - * Provide 2-4 mutually exclusive options + a recommended default. - * If unanswered, proceed with the recommended option and record it as an assumption in the final plan. - -## Finalization rule - -Only output the final plan when it is decision complete and leaves no decisions to the implementer. - -When you present the official plan, wrap it in a \`\` block so the client can render it specially: - -1) The opening tag must be on its own line. -2) Start the plan content on the next line (no text on the same line as the tag). -3) The closing tag must be on its own line. -4) Use Markdown inside the block. -5) Keep the tags exactly as \`\` and \`\` (do not translate or rename them), even if the plan content is in another language. - -Example: - - -plan content - - -plan content should be human and agent digestible. The final plan must be plan-only and include: - -* A clear title -* A brief summary section -* Important changes or additions to public APIs/interfaces/types -* Test cases and scenarios -* Explicit assumptions and defaults chosen where needed - -Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. - -Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. -`; - -export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default - -You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. - -Your active mode changes only when new developer instructions with a different \`...\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan. - -## request_user_input availability - -The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error. - -In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. -`; diff --git a/apps/server/src/provider/codex/CodexSessionRuntime.test.ts b/apps/server/src/provider/codex/CodexSessionRuntime.test.ts deleted file mode 100644 index 69dbdcb9a1..0000000000 --- a/apps/server/src/provider/codex/CodexSessionRuntime.test.ts +++ /dev/null @@ -1,275 +0,0 @@ -import assert from "node:assert/strict"; - -import { Effect, Schema } from "effect"; -import { describe, it } from "vitest"; -import { ThreadId } from "@t3tools/contracts"; -import * as CodexErrors from "effect-codex-app-server/errors"; -import * as CodexRpc from "effect-codex-app-server/rpc"; - -import { - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, -} from "./CodexDeveloperInstructions.ts"; -import { - buildTurnStartParams, - isRecoverableThreadResumeError, - openCodexThread, -} from "./CodexSessionRuntime.ts"; - -function makeThreadOpenResponse( - threadId: string, -): CodexRpc.ClientRequestResponsesByMethod["thread/start"] { - return { - cwd: "/tmp/project", - model: "gpt-5.3-codex", - modelProvider: "openai", - approvalPolicy: "never", - approvalsReviewer: "user", - sandbox: { type: "danger-full-access" }, - thread: { - id: threadId, - createdAt: "2026-04-18T00:00:00.000Z", - source: { session: "cli" }, - turns: [], - status: { - state: "idle", - activeFlags: [], - }, - }, - } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"]; -} - -describe("buildTurnStartParams", () => { - it("includes plan collaboration mode when requested", () => { - const params = Effect.runSync( - buildTurnStartParams({ - threadId: "provider-thread-1", - runtimeMode: "full-access", - prompt: "Make a plan", - model: "gpt-5.3-codex", - effort: "medium", - interactionMode: "plan", - }), - ); - - assert.deepStrictEqual(params, { - threadId: "provider-thread-1", - approvalPolicy: "never", - sandboxPolicy: { - type: "dangerFullAccess", - }, - input: [ - { - type: "text", - text: "Make a plan", - }, - ], - model: "gpt-5.3-codex", - effort: "medium", - collaborationMode: { - mode: "plan", - settings: { - model: "gpt-5.3-codex", - reasoning_effort: "medium", - developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, - }, - }, - }); - }); - - it("includes default collaboration mode and image attachments", () => { - const params = Effect.runSync( - buildTurnStartParams({ - threadId: "provider-thread-1", - runtimeMode: "auto-accept-edits", - prompt: "Implement it", - model: "gpt-5.3-codex", - interactionMode: "default", - attachments: [ - { - type: "image", - url: "data:image/png;base64,abc", - }, - ], - }), - ); - - assert.deepStrictEqual(params, { - threadId: "provider-thread-1", - approvalPolicy: "on-request", - sandboxPolicy: { - type: "workspaceWrite", - }, - input: [ - { - type: "text", - text: "Implement it", - }, - { - type: "image", - url: "data:image/png;base64,abc", - }, - ], - model: "gpt-5.3-codex", - collaborationMode: { - mode: "default", - settings: { - model: "gpt-5.3-codex", - reasoning_effort: "medium", - developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - }, - }, - }); - }); - - it("omits collaboration mode when interaction mode is absent", () => { - const params = Effect.runSync( - buildTurnStartParams({ - threadId: "provider-thread-1", - runtimeMode: "approval-required", - prompt: "Review", - }), - ); - - assert.deepStrictEqual(params, { - threadId: "provider-thread-1", - approvalPolicy: "untrusted", - sandboxPolicy: { - type: "readOnly", - }, - input: [ - { - type: "text", - text: "Review", - }, - ], - }); - }); -}); - -describe("isRecoverableThreadResumeError", () => { - it("matches missing thread errors", () => { - assert.equal( - isRecoverableThreadResumeError( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "Thread does not exist", - }), - ), - true, - ); - }); - - it("ignores non-recoverable resume errors", () => { - assert.equal( - isRecoverableThreadResumeError( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "Permission denied", - }), - ), - false, - ); - }); - - it("ignores unrelated missing-resource errors that do not mention threads", () => { - assert.equal( - isRecoverableThreadResumeError( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "Config file not found", - }), - ), - false, - ); - assert.equal( - isRecoverableThreadResumeError( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "Model does not exist", - }), - ), - false, - ); - }); -}); - -describe("openCodexThread", () => { - it("falls back to thread/start when resume fails recoverably", async () => { - const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = []; - const started = makeThreadOpenResponse("fresh-thread"); - const client = { - request: ( - method: M, - payload: CodexRpc.ClientRequestParamsByMethod[M], - ) => { - calls.push({ method, payload }); - if (method === "thread/resume") { - return Effect.fail( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "thread not found", - }), - ); - } - return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]); - }, - }; - - const opened = await Effect.runPromise( - openCodexThread({ - client, - threadId: ThreadId.make("thread-1"), - runtimeMode: "full-access", - cwd: "/tmp/project", - requestedModel: "gpt-5.3-codex", - serviceTier: undefined, - resumeThreadId: "stale-thread", - }), - ); - - assert.equal(opened.thread.id, "fresh-thread"); - assert.deepStrictEqual( - calls.map((call) => call.method), - ["thread/resume", "thread/start"], - ); - }); - - it("propagates non-recoverable resume failures", async () => { - const client = { - request: ( - method: M, - _payload: CodexRpc.ClientRequestParamsByMethod[M], - ) => { - if (method === "thread/resume") { - return Effect.fail( - new CodexErrors.CodexAppServerRequestError({ - code: -32603, - errorMessage: "timed out waiting for server", - }), - ); - } - return Effect.succeed( - makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M], - ); - }, - }; - - await assert.rejects( - Effect.runPromise( - openCodexThread({ - client, - threadId: ThreadId.make("thread-1"), - runtimeMode: "full-access", - cwd: "/tmp/project", - requestedModel: "gpt-5.3-codex", - serviceTier: undefined, - resumeThreadId: "stale-thread", - }), - ), - (error: unknown) => - Schema.is(CodexErrors.CodexAppServerRequestError)(error) && - error.errorMessage === "timed out waiting for server", - ); - }); -}); diff --git a/apps/server/src/provider/codex/CodexSessionRuntime.ts b/apps/server/src/provider/codex/CodexSessionRuntime.ts deleted file mode 100644 index db5bd004c3..0000000000 --- a/apps/server/src/provider/codex/CodexSessionRuntime.ts +++ /dev/null @@ -1,1325 +0,0 @@ -import { randomUUID } from "node:crypto"; - -import { - ApprovalRequestId, - DEFAULT_MODEL_BY_PROVIDER, - EventId, - ProviderItemId, - type ProviderApprovalDecision, - type ProviderEvent, - type ProviderInteractionMode, - type ProviderRequestKind, - type ProviderSession, - type ProviderTurnStartResult, - type ProviderUserInputAnswers, - RuntimeMode, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import { normalizeModelSlug } from "@t3tools/shared/model"; -import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect"; -import * as SchemaIssue from "effect/SchemaIssue"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import * as CodexClient from "effect-codex-app-server/client"; -import * as CodexErrors from "effect-codex-app-server/errors"; -import * as CodexRpc from "effect-codex-app-server/rpc"; -import * as EffectCodexSchema from "effect-codex-app-server/schema"; - -import { buildCodexInitializeParams } from "../codexAppServer.ts"; -import { - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, -} from "./CodexDeveloperInstructions.ts"; - -const PROVIDER = "codex" as const; - -const ANSI_ESCAPE_CHAR = String.fromCharCode(27); -const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); -const CODEX_STDERR_LOG_REGEX = - /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/; -const BENIGN_ERROR_LOG_SNIPPETS = [ - "state db missing rollout path for thread", - "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back", -]; -const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ - "not found", - "missing thread", - "no such thread", - "unknown thread", - "does not exist", -]; - -export const CodexResumeCursorSchema = Schema.Struct({ - threadId: Schema.String, -}); -const CodexUserInputAnswerObject = Schema.Struct({ - answers: Schema.Array(Schema.String), -}); - -// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated -// `V2TurnStartParams` schema includes `collaborationMode` directly. -const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe( - Schema.fieldsAssign({ - collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode), - }), -); - -export type CodexTurnStartParamsWithCollaborationMode = - typeof CodexTurnStartParamsWithCollaborationMode.Type; -const formatSchemaIssue = SchemaIssue.makeFormatterDefault(); - -export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type; -type CodexThreadItem = - | EffectCodexSchema.V2ThreadReadResponse["thread"]["turns"][number]["items"][number] - | EffectCodexSchema.V2ThreadRollbackResponse["thread"]["turns"][number]["items"][number]; - -export interface CodexSessionRuntimeOptions { - readonly threadId: ThreadId; - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - readonly runtimeMode: RuntimeMode; - readonly model?: string; - readonly serviceTier?: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; - readonly resumeCursor?: CodexResumeCursor; -} - -export interface CodexSessionRuntimeSendTurnInput { - readonly input?: string; - readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; - readonly model?: string; - readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined; - readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined; - readonly interactionMode?: ProviderInteractionMode; -} - -export interface CodexThreadTurnSnapshot { - readonly id: TurnId; - readonly items: ReadonlyArray; -} - -export interface CodexThreadSnapshot { - readonly threadId: string; - readonly turns: ReadonlyArray; -} - -export interface CodexSessionRuntimeShape { - readonly start: () => Effect.Effect; - readonly getSession: Effect.Effect; - readonly sendTurn: ( - input: CodexSessionRuntimeSendTurnInput, - ) => Effect.Effect; - readonly interruptTurn: (turnId?: TurnId) => Effect.Effect; - readonly readThread: Effect.Effect; - readonly rollbackThread: ( - numTurns: number, - ) => Effect.Effect; - readonly respondToRequest: ( - requestId: ApprovalRequestId, - decision: ProviderApprovalDecision, - ) => Effect.Effect; - readonly respondToUserInput: ( - requestId: ApprovalRequestId, - answers: ProviderUserInputAnswers, - ) => Effect.Effect; - readonly events: Stream.Stream; - readonly close: Effect.Effect; -} - -export type CodexSessionRuntimeError = - | CodexErrors.CodexAppServerError - | CodexSessionRuntimePendingApprovalNotFoundError - | CodexSessionRuntimePendingUserInputNotFoundError - | CodexSessionRuntimeInvalidUserInputAnswersError - | CodexSessionRuntimeThreadIdMissingError; - -export class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass()( - "CodexSessionRuntimePendingApprovalNotFoundError", - { - requestId: Schema.String, - }, -) { - override get message(): string { - return `Unknown pending Codex approval request: ${this.requestId}`; - } -} - -export class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass()( - "CodexSessionRuntimePendingUserInputNotFoundError", - { - requestId: Schema.String, - }, -) { - override get message(): string { - return `Unknown pending Codex user input request: ${this.requestId}`; - } -} - -export class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass()( - "CodexSessionRuntimeInvalidUserInputAnswersError", - { - questionId: Schema.String, - }, -) { - override get message(): string { - return `Invalid Codex user input answers for question '${this.questionId}'`; - } -} - -export class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass()( - "CodexSessionRuntimeThreadIdMissingError", - { - threadId: Schema.String, - }, -) { - override get message(): string { - return `Codex session is missing a provider thread id for ${this.threadId}`; - } -} - -interface PendingApproval { - readonly requestId: ApprovalRequestId; - readonly jsonRpcId: string; - readonly requestKind: ProviderRequestKind; - readonly turnId: TurnId | undefined; - readonly itemId: ProviderItemId | undefined; - readonly decision: Deferred.Deferred; -} - -interface ApprovalCorrelation { - readonly requestId: ApprovalRequestId; - readonly requestKind: ProviderRequestKind; - readonly turnId: TurnId | undefined; - readonly itemId: ProviderItemId | undefined; -} - -interface PendingUserInput { - readonly requestId: ApprovalRequestId; - readonly turnId: TurnId | undefined; - readonly itemId: ProviderItemId | undefined; - readonly answers: Deferred.Deferred; -} - -type CodexServerNotification = { - readonly [M in CodexRpc.ServerNotificationMethod]: { - readonly method: M; - readonly params: CodexRpc.ServerNotificationParamsByMethod[M]; - }; -}[CodexRpc.ServerNotificationMethod]; - -function makeCodexServerNotification( - method: M, - params: CodexRpc.ServerNotificationParamsByMethod[M], -): CodexServerNotification { - return { method, params } as CodexServerNotification; -} - -function normalizeCodexModelSlug( - model: string | undefined | null, - preferredId?: string, -): string | undefined { - const normalized = normalizeModelSlug(model); - if (!normalized) { - return undefined; - } - if (preferredId?.endsWith("-codex") && preferredId !== normalized) { - return preferredId; - } - return normalized; -} - -function readResumeCursorThreadId( - resumeCursor: ProviderSession["resumeCursor"], -): string | undefined { - return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined; -} - -function runtimeModeToThreadConfig(input: RuntimeMode): { - readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval; - readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode; -} { - switch (input) { - case "approval-required": - return { - approvalPolicy: "untrusted", - sandbox: "read-only", - }; - case "auto-accept-edits": - return { - approvalPolicy: "on-request", - sandbox: "workspace-write", - }; - case "full-access": - default: - return { - approvalPolicy: "never", - sandbox: "danger-full-access", - }; - } -} - -function buildThreadStartParams(input: { - readonly cwd: string; - readonly runtimeMode: RuntimeMode; - readonly model: string | undefined; - readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; -}): EffectCodexSchema.V2ThreadStartParams { - const config = runtimeModeToThreadConfig(input.runtimeMode); - return { - cwd: input.cwd, - approvalPolicy: config.approvalPolicy, - sandbox: config.sandbox, - ...(input.model ? { model: input.model } : {}), - ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), - }; -} - -function runtimeModeToTurnSandboxPolicy( - input: RuntimeMode, -): EffectCodexSchema.V2TurnStartParams__SandboxPolicy { - switch (input) { - case "approval-required": - return { - type: "readOnly", - }; - case "auto-accept-edits": - return { - type: "workspaceWrite", - }; - case "full-access": - default: - return { - type: "dangerFullAccess", - }; - } -} - -function buildCodexCollaborationMode(input: { - readonly interactionMode?: ProviderInteractionMode; - readonly model?: string; - readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; -}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined { - if (input.interactionMode === undefined) { - return undefined; - } - const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex; - return { - mode: input.interactionMode, - settings: { - model, - reasoning_effort: input.effort ?? "medium", - developer_instructions: - input.interactionMode === "plan" - ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS - : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - }, - }; -} - -export function buildTurnStartParams(input: { - readonly threadId: string; - readonly runtimeMode: RuntimeMode; - readonly prompt?: string; - readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; - readonly model?: string; - readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier; - readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; - readonly interactionMode?: ProviderInteractionMode; -}): Effect.Effect< - CodexTurnStartParamsWithCollaborationMode, - CodexErrors.CodexAppServerProtocolParseError -> { - const turnInput: Array = []; - if (input.prompt) { - turnInput.push({ - type: "text", - text: input.prompt, - }); - } - for (const attachment of input.attachments ?? []) { - turnInput.push(attachment); - } - - const config = runtimeModeToThreadConfig(input.runtimeMode); - const collaborationMode = buildCodexCollaborationMode({ - ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), - ...(input.model ? { model: input.model } : {}), - ...(input.effort ? { effort: input.effort } : {}), - }); - - return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({ - threadId: input.threadId, - input: turnInput, - approvalPolicy: config.approvalPolicy, - sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode), - ...(input.model ? { model: input.model } : {}), - ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), - ...(input.effort ? { effort: input.effort } : {}), - ...(collaborationMode ? { collaborationMode } : {}), - }).pipe( - Effect.mapError((error) => toProtocolParseError("Invalid turn/start request payload", error)), - ); -} - -function classifyCodexStderrLine(rawLine: string): { readonly message: string } | null { - const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim(); - if (!line) { - return null; - } - - const match = line.match(CODEX_STDERR_LOG_REGEX); - if (match) { - const level = match[1]; - if (level && level !== "ERROR") { - return null; - } - if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) { - return null; - } - } - - return { message: line }; -} - -export function isRecoverableThreadResumeError(error: unknown): boolean { - const message = (error instanceof Error ? error.message : String(error)).toLowerCase(); - if (!message.includes("thread")) { - return false; - } - return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet)); -} - -type CodexThreadOpenResponse = - | CodexRpc.ClientRequestResponsesByMethod["thread/start"] - | CodexRpc.ClientRequestResponsesByMethod["thread/resume"]; - -type CodexThreadOpenMethod = "thread/start" | "thread/resume"; - -interface CodexThreadOpenClient { - readonly request: ( - method: M, - payload: CodexRpc.ClientRequestParamsByMethod[M], - ) => Effect.Effect; -} - -export const openCodexThread = (input: { - readonly client: CodexThreadOpenClient; - readonly threadId: ThreadId; - readonly runtimeMode: RuntimeMode; - readonly cwd: string; - readonly requestedModel: string | undefined; - readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; - readonly resumeThreadId: string | undefined; -}): Effect.Effect => { - const resumeThreadId = input.resumeThreadId; - const startParams = buildThreadStartParams({ - cwd: input.cwd, - runtimeMode: input.runtimeMode, - model: input.requestedModel, - serviceTier: input.serviceTier, - }); - - if (resumeThreadId === undefined) { - return input.client.request("thread/start", startParams); - } - - return input.client - .request("thread/resume", { - threadId: resumeThreadId, - ...startParams, - }) - .pipe( - Effect.catchIf(isRecoverableThreadResumeError, (error) => - Effect.logWarning("codex app-server thread resume fell back to fresh start", { - threadId: input.threadId, - requestedRuntimeMode: input.runtimeMode, - resumeThreadId, - recoverable: true, - cause: error.message, - }).pipe(Effect.andThen(input.client.request("thread/start", startParams))), - ), - ); -}; - -function readNotificationThreadId(notification: CodexServerNotification): string | undefined { - switch (notification.method) { - case "thread/started": - return notification.params.thread.id; - case "error": - case "thread/status/changed": - case "thread/archived": - case "thread/unarchived": - case "thread/closed": - case "thread/name/updated": - case "thread/tokenUsage/updated": - case "turn/started": - case "hook/started": - case "turn/completed": - case "hook/completed": - case "turn/diff/updated": - case "turn/plan/updated": - case "item/started": - case "item/autoApprovalReview/started": - case "item/autoApprovalReview/completed": - case "item/completed": - case "rawResponseItem/completed": - case "item/agentMessage/delta": - case "item/plan/delta": - case "item/commandExecution/outputDelta": - case "item/commandExecution/terminalInteraction": - case "item/fileChange/outputDelta": - case "serverRequest/resolved": - case "item/mcpToolCall/progress": - case "item/reasoning/summaryTextDelta": - case "item/reasoning/summaryPartAdded": - case "item/reasoning/textDelta": - case "thread/compacted": - case "thread/realtime/started": - case "thread/realtime/itemAdded": - case "thread/realtime/transcriptUpdated": - case "thread/realtime/outputAudio/delta": - case "thread/realtime/sdp": - case "thread/realtime/error": - case "thread/realtime/closed": - return notification.params.threadId; - default: - return undefined; - } -} - -function readRouteFields(notification: CodexServerNotification): { - readonly turnId: TurnId | undefined; - readonly itemId: ProviderItemId | undefined; -} { - switch (notification.method) { - case "thread/started": - return { - turnId: undefined, - itemId: undefined, - }; - case "turn/started": - case "turn/completed": - return { - turnId: TurnId.make(notification.params.turn.id), - itemId: undefined, - }; - case "error": - return { - turnId: TurnId.make(notification.params.turnId), - itemId: undefined, - }; - case "turn/diff/updated": - case "turn/plan/updated": - return { - turnId: TurnId.make(notification.params.turnId), - itemId: undefined, - }; - case "serverRequest/resolved": - return { - turnId: undefined, - itemId: undefined, - }; - case "item/started": - case "item/completed": - return { - turnId: TurnId.make(notification.params.turnId), - itemId: ProviderItemId.make(notification.params.item.id), - }; - case "item/agentMessage/delta": - case "item/plan/delta": - case "item/commandExecution/outputDelta": - case "item/commandExecution/terminalInteraction": - case "item/fileChange/outputDelta": - case "item/reasoning/summaryTextDelta": - case "item/reasoning/summaryPartAdded": - case "item/reasoning/textDelta": - return { - turnId: TurnId.make(notification.params.turnId), - itemId: ProviderItemId.make(notification.params.itemId), - }; - default: - return { - turnId: undefined, - itemId: undefined, - }; - } -} - -function rememberCollabReceiverTurns( - collabReceiverTurns: Map, - notification: CodexServerNotification, - parentTurnId: TurnId | undefined, -): void { - if (!parentTurnId) { - return; - } - - if (notification.method !== "item/started" && notification.method !== "item/completed") { - return; - } - - if (notification.params.item.type !== "collabAgentToolCall") { - return; - } - - for (const receiverThreadId of notification.params.item.receiverThreadIds) { - collabReceiverTurns.set(receiverThreadId, parentTurnId); - } -} - -function shouldSuppressChildConversationNotification( - method: CodexRpc.ServerNotificationMethod, -): boolean { - return ( - method === "thread/started" || - method === "thread/status/changed" || - method === "thread/archived" || - method === "thread/unarchived" || - method === "thread/closed" || - method === "thread/compacted" || - method === "thread/name/updated" || - method === "thread/tokenUsage/updated" || - method === "turn/started" || - method === "turn/completed" || - method === "turn/plan/updated" || - method === "item/plan/delta" - ); -} - -function toCodexUserInputAnswer( - questionId: string, - value: ProviderUserInputAnswers[string], -): Effect.Effect< - EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer, - CodexSessionRuntimeInvalidUserInputAnswersError -> { - if (typeof value === "string") { - return Effect.succeed({ answers: [value] }); - } - if (Array.isArray(value)) { - const answers = value.filter((entry): entry is string => typeof entry === "string"); - return Effect.succeed({ answers }); - } - if (Schema.is(CodexUserInputAnswerObject)(value)) { - return Effect.succeed({ answers: value.answers }); - } - return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId })); -} - -function toCodexUserInputAnswers( - answers: ProviderUserInputAnswers, -): Effect.Effect< - EffectCodexSchema.ToolRequestUserInputResponse["answers"], - CodexSessionRuntimeInvalidUserInputAnswersError -> { - return Effect.forEach( - Object.entries(answers), - ([questionId, value]) => - toCodexUserInputAnswer(questionId, value).pipe( - Effect.map((answer) => [questionId, answer] as const), - ), - { concurrency: 1 }, - ).pipe(Effect.map((entries) => Object.fromEntries(entries))); -} - -function toProtocolParseError( - detail: string, - cause: Schema.SchemaError, -): CodexErrors.CodexAppServerProtocolParseError { - return new CodexErrors.CodexAppServerProtocolParseError({ - detail: `${detail}: ${formatSchemaIssue(cause.issue)}`, - cause, - }); -} - -function currentProviderThreadId(session: ProviderSession): string | undefined { - return readResumeCursorThreadId(session.resumeCursor); -} - -function updateSession( - sessionRef: Ref.Ref, - updates: Partial, -): Effect.Effect { - return Ref.update(sessionRef, (session) => ({ - ...session, - ...updates, - updatedAt: new Date().toISOString(), - })); -} - -function parseThreadSnapshot( - response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse, -): CodexThreadSnapshot { - return { - threadId: response.thread.id, - turns: response.thread.turns.map((turn) => ({ - id: TurnId.make(turn.id), - items: turn.items, - })), - }; -} - -export const makeCodexSessionRuntime = ( - options: CodexSessionRuntimeOptions, -): Effect.Effect< - CodexSessionRuntimeShape, - CodexErrors.CodexAppServerError, - ChildProcessSpawner.ChildProcessSpawner | Scope.Scope -> => - Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const runtimeScope = yield* Scope.Scope; - const events = yield* Queue.unbounded(); - const pendingApprovalsRef = yield* Ref.make(new Map()); - const approvalCorrelationsRef = yield* Ref.make(new Map()); - const pendingUserInputsRef = yield* Ref.make(new Map()); - const collabReceiverTurnsRef = yield* Ref.make(new Map()); - const closedRef = yield* Ref.make(false); - - const child = yield* spawner - .spawn( - ChildProcess.make(options.binaryPath, ["app-server"], { - cwd: options.cwd, - ...(options.homePath ? { env: { ...process.env, CODEX_HOME: options.homePath } } : {}), - shell: process.platform === "win32", - }), - ) - .pipe( - Effect.provideService(Scope.Scope, runtimeScope), - Effect.mapError( - (cause) => - new CodexErrors.CodexAppServerSpawnError({ - command: `${options.binaryPath} app-server`, - cause, - }), - ), - ); - - const clientContext = yield* CodexClient.layerChildProcess(child).pipe( - Layer.build, - Effect.provideService(Scope.Scope, runtimeScope), - ); - const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( - Effect.provide(clientContext), - ); - const serverNotifications = yield* Queue.unbounded(); - - const initialSession = { - provider: PROVIDER, - status: "connecting", - runtimeMode: options.runtimeMode, - cwd: options.cwd, - ...(options.model ? { model: options.model } : {}), - threadId: options.threadId, - ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}), - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - } satisfies ProviderSession; - const sessionRef = yield* Ref.make(initialSession); - const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid); - - const emitEvent = (event: Omit) => - offerEvent({ - id: EventId.make(randomUUID()), - provider: PROVIDER, - createdAt: new Date().toISOString(), - ...event, - }); - - const emitSessionEvent = (method: string, message: string) => - emitEvent({ - kind: "session", - threadId: options.threadId, - method, - message, - }); - - const settlePendingApprovals = (decision: ProviderApprovalDecision) => - Ref.get(pendingApprovalsRef).pipe( - Effect.flatMap((pendingApprovals) => - Effect.forEach( - Array.from(pendingApprovals.values()), - (pendingApproval) => - Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore), - { discard: true }, - ), - ), - ); - - const settlePendingUserInputs = (answers: ProviderUserInputAnswers) => - Ref.get(pendingUserInputsRef).pipe( - Effect.flatMap((pendingUserInputs) => - Effect.forEach( - Array.from(pendingUserInputs.values()), - (pendingUserInput) => - Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore), - { discard: true }, - ), - ), - ); - - const handleRawNotification = (notification: CodexServerNotification) => - Effect.gen(function* () { - const payload = notification.params; - const route = readRouteFields(notification); - const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef); - const childParentTurnId = (() => { - const providerConversationId = readNotificationThreadId(notification); - return providerConversationId - ? collabReceiverTurns.get(providerConversationId) - : undefined; - })(); - - rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId); - if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) { - yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); - return; - } - - let requestId: ApprovalRequestId | undefined; - let requestKind: ProviderRequestKind | undefined; - let turnId = childParentTurnId ?? route.turnId; - let itemId = route.itemId; - - if (notification.method === "serverRequest/resolved") { - const rawRequestId = - typeof notification.params.requestId === "string" - ? notification.params.requestId - : String(notification.params.requestId); - const correlation = rawRequestId - ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId) - : undefined; - if (correlation) { - requestId = correlation.requestId; - requestKind = correlation.requestKind; - turnId = correlation.turnId ?? turnId; - itemId = correlation.itemId ?? itemId; - yield* Ref.update(approvalCorrelationsRef, (current) => { - const next = new Map(current); - next.delete(rawRequestId); - return next; - }); - } - } - - yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); - yield* emitEvent({ - kind: "notification", - threadId: options.threadId, - method: notification.method, - ...(turnId ? { turnId } : {}), - ...(itemId ? { itemId } : {}), - ...(requestId ? { requestId } : {}), - ...(requestKind ? { requestKind } : {}), - ...(notification.method === "item/agentMessage/delta" - ? { textDelta: notification.params.delta } - : {}), - ...(payload !== undefined ? { payload } : {}), - }); - }); - - const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId); - - yield* client.handleServerNotification("thread/started", (payload) => - currentSessionProviderThreadId.pipe( - Effect.flatMap((providerThreadId) => { - if (providerThreadId && payload.thread.id !== providerThreadId) { - return Effect.void; - } - return updateSession(sessionRef, { - resumeCursor: { threadId: payload.thread.id }, - }); - }), - ), - ); - - yield* client.handleServerNotification("turn/started", (payload) => - currentSessionProviderThreadId.pipe( - Effect.flatMap((providerThreadId) => { - if (providerThreadId && payload.threadId !== providerThreadId) { - return Effect.void; - } - return updateSession(sessionRef, { - status: "running", - activeTurnId: TurnId.make(payload.turn.id), - }); - }), - ), - ); - - yield* client.handleServerNotification("turn/completed", (payload) => - currentSessionProviderThreadId.pipe( - Effect.flatMap((providerThreadId) => { - if (providerThreadId && payload.threadId !== providerThreadId) { - return Effect.void; - } - const lastError = - payload.turn.status === "failed" && "error" in payload.turn && payload.turn.error - ? payload.turn.error.message - : undefined; - return updateSession(sessionRef, { - status: payload.turn.status === "failed" ? "error" : "ready", - activeTurnId: undefined, - ...(lastError ? { lastError } : {}), - }); - }), - ), - ); - - yield* client.handleServerNotification("error", (payload) => - currentSessionProviderThreadId.pipe( - Effect.flatMap((providerThreadId) => { - const payloadThreadId = payload.threadId; - if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) { - return Effect.void; - } - const errorMessage = payload.error.message; - const willRetry = payload.willRetry; - return updateSession(sessionRef, { - status: willRetry ? "running" : "error", - ...(errorMessage ? { lastError: errorMessage } : {}), - }); - }), - ), - ); - - yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) => - Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); - const turnId = TurnId.make(payload.turnId); - const itemId = ProviderItemId.make(payload.itemId); - const decision = yield* Deferred.make(); - - yield* Ref.update(pendingApprovalsRef, (current) => { - const next = new Map(current); - next.set(requestId, { - requestId, - jsonRpcId: payload.approvalId ?? payload.itemId, - requestKind: "command", - turnId, - itemId, - decision, - }); - return next; - }); - yield* Ref.update(approvalCorrelationsRef, (current) => { - const next = new Map(current); - next.set(payload.approvalId ?? payload.itemId, { - requestId, - requestKind: "command", - turnId, - itemId, - }); - return next; - }); - - yield* emitEvent({ - kind: "request", - threadId: options.threadId, - method: "item/commandExecution/requestApproval", - requestId, - requestKind: "command", - ...(turnId ? { turnId } : {}), - ...(itemId ? { itemId } : {}), - payload, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingApprovalsRef, (current) => { - const next = new Map(current); - next.delete(requestId); - return next; - }), - ), - ); - return { - decision: resolved, - } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse; - }), - ); - - yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) => - Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); - const turnId = TurnId.make(payload.turnId); - const itemId = ProviderItemId.make(payload.itemId); - const decision = yield* Deferred.make(); - - yield* Ref.update(pendingApprovalsRef, (current) => { - const next = new Map(current); - next.set(requestId, { - requestId, - jsonRpcId: payload.itemId, - requestKind: "file-change", - turnId, - itemId, - decision, - }); - return next; - }); - yield* Ref.update(approvalCorrelationsRef, (current) => { - const next = new Map(current); - next.set(payload.itemId, { - requestId, - requestKind: "file-change", - turnId, - itemId, - }); - return next; - }); - - yield* emitEvent({ - kind: "request", - threadId: options.threadId, - method: "item/fileChange/requestApproval", - requestId, - requestKind: "file-change", - ...(turnId ? { turnId } : {}), - ...(itemId ? { itemId } : {}), - payload, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingApprovalsRef, (current) => { - const next = new Map(current); - next.delete(requestId); - return next; - }), - ), - ); - return { - decision: resolved, - } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse; - }), - ); - - yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => - Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); - const turnId = TurnId.make(payload.turnId); - const itemId = ProviderItemId.make(payload.itemId); - const answers = yield* Deferred.make(); - - yield* Ref.update(pendingUserInputsRef, (current) => { - const next = new Map(current); - next.set(requestId, { - requestId, - turnId, - itemId, - answers, - }); - return next; - }); - - yield* emitEvent({ - kind: "request", - threadId: options.threadId, - method: "item/tool/requestUserInput", - requestId, - ...(turnId ? { turnId } : {}), - ...(itemId ? { itemId } : {}), - payload, - }); - - const resolvedAnswers = yield* Deferred.await(answers).pipe( - Effect.ensuring( - Ref.update(pendingUserInputsRef, (current) => { - const next = new Map(current); - next.delete(requestId); - return next; - }), - ), - ); - - return { - answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe( - Effect.mapError((error) => - CodexErrors.CodexAppServerRequestError.invalidParams(error.message, { - questionId: error.questionId, - }), - ), - ), - } satisfies EffectCodexSchema.ToolRequestUserInputResponse; - }), - ); - - yield* client.handleUnknownServerRequest((method) => - Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)), - ); - - const registerServerNotification = (method: M) => - client.handleServerNotification(method, (params) => - Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe( - Effect.asVoid, - ), - ); - - yield* Effect.forEach( - Object.values( - CodexRpc.SERVER_NOTIFICATION_METHODS, - ) as ReadonlyArray, - registerServerNotification, - { concurrency: 1, discard: true }, - ); - - yield* Stream.fromQueue(serverNotifications).pipe( - Stream.runForEach(handleRawNotification), - Effect.forkIn(runtimeScope), - ); - - const stderrRemainderRef = yield* Ref.make(""); - yield* child.stderr.pipe( - Stream.decodeText(), - Stream.runForEach((chunk) => - Ref.modify(stderrRemainderRef, (current) => { - const combined = current + chunk; - const lines = combined.split("\n"); - const remainder = lines.pop() ?? ""; - return [lines.map((line) => line.replace(/\r$/, "")), remainder] as const; - }).pipe( - Effect.flatMap((lines) => - Effect.forEach( - lines, - (line) => { - const classified = classifyCodexStderrLine(line); - if (!classified) { - return Effect.void; - } - return emitEvent({ - kind: "notification", - threadId: options.threadId, - method: "process/stderr", - message: classified.message, - }); - }, - { discard: true }, - ), - ), - ), - ), - Effect.forkIn(runtimeScope), - ); - - yield* child.exitCode.pipe( - Effect.flatMap((exitCode) => - Ref.get(closedRef).pipe( - Effect.flatMap((closed) => { - if (closed) { - return Effect.void; - } - const nextStatus = exitCode === 0 ? "closed" : "error"; - return updateSession(sessionRef, { - status: nextStatus, - activeTurnId: undefined, - }).pipe( - Effect.andThen( - emitSessionEvent( - "session/exited", - exitCode === 0 - ? "Codex App Server exited." - : `Codex App Server exited with code ${exitCode}.`, - ), - ), - ); - }), - ), - ), - Effect.forkIn(runtimeScope), - ); - - const start = Effect.fn("CodexSessionRuntime.start")(function* () { - yield* emitSessionEvent("session/connecting", "Starting Codex App Server session."); - yield* client.request("initialize", buildCodexInitializeParams()); - yield* client.notify("initialized", undefined); - - const requestedModel = normalizeCodexModelSlug(options.model); - - const opened = yield* openCodexThread({ - client, - threadId: options.threadId, - runtimeMode: options.runtimeMode, - cwd: options.cwd, - requestedModel, - serviceTier: options.serviceTier, - resumeThreadId: readResumeCursorThreadId(options.resumeCursor), - }); - - const providerThreadId = opened.thread.id; - const session = { - ...(yield* Ref.get(sessionRef)), - status: "ready", - cwd: opened.cwd, - model: opened.model, - resumeCursor: { threadId: providerThreadId }, - updatedAt: new Date().toISOString(), - } satisfies ProviderSession; - yield* Ref.set(sessionRef, session); - yield* emitSessionEvent("session/ready", "Codex App Server session ready."); - return session; - }); - - const readProviderThreadId = Effect.gen(function* () { - const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef)); - if (!providerThreadId) { - return yield* new CodexSessionRuntimeThreadIdMissingError({ - threadId: options.threadId, - }); - } - return providerThreadId; - }); - - const close = Effect.gen(function* () { - const alreadyClosed = yield* Ref.getAndSet(closedRef, true); - if (alreadyClosed) { - return; - } - yield* settlePendingApprovals("cancel"); - yield* settlePendingUserInputs({}); - yield* updateSession(sessionRef, { - status: "closed", - activeTurnId: undefined, - }); - yield* emitSessionEvent("session/closed", "Session stopped"); - yield* Scope.close(runtimeScope, Exit.void); - yield* Queue.shutdown(serverNotifications); - yield* Queue.shutdown(events); - }); - - return { - start, - getSession: Ref.get(sessionRef), - sendTurn: (input) => - Effect.gen(function* () { - const providerThreadId = yield* readProviderThreadId; - const normalizedModel = normalizeCodexModelSlug( - input.model ?? (yield* Ref.get(sessionRef)).model, - ); - const params = yield* buildTurnStartParams({ - threadId: providerThreadId, - runtimeMode: options.runtimeMode, - ...(input.input ? { prompt: input.input } : {}), - ...(input.attachments ? { attachments: input.attachments } : {}), - ...(normalizedModel ? { model: normalizedModel } : {}), - ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), - ...(input.effort ? { effort: input.effort } : {}), - ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), - }); - const rawResponse = yield* client.raw.request("turn/start", params); - const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)( - rawResponse, - ).pipe( - Effect.mapError((error) => - toProtocolParseError("Invalid turn/start response payload", error), - ), - ); - const turnId = TurnId.make(response.turn.id); - yield* updateSession(sessionRef, { - status: "running", - activeTurnId: turnId, - ...(normalizedModel ? { model: normalizedModel } : {}), - }); - const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef)); - return { - threadId: options.threadId, - turnId, - ...(resumedProviderThreadId - ? { resumeCursor: { threadId: resumedProviderThreadId } } - : {}), - } satisfies ProviderTurnStartResult; - }), - interruptTurn: (turnId) => - Effect.gen(function* () { - const providerThreadId = yield* readProviderThreadId; - const session = yield* Ref.get(sessionRef); - const effectiveTurnId = turnId ?? session.activeTurnId; - if (!effectiveTurnId) { - return; - } - yield* client.request("turn/interrupt", { - threadId: providerThreadId, - turnId: effectiveTurnId, - }); - }), - readThread: Effect.gen(function* () { - const providerThreadId = yield* readProviderThreadId; - const response = yield* client.request("thread/read", { - threadId: providerThreadId, - includeTurns: true, - }); - return parseThreadSnapshot(response); - }), - rollbackThread: (numTurns) => - Effect.gen(function* () { - const providerThreadId = yield* readProviderThreadId; - const response = yield* client.request("thread/rollback", { - threadId: providerThreadId, - numTurns, - }); - yield* updateSession(sessionRef, { - status: "ready", - activeTurnId: undefined, - }); - return parseThreadSnapshot(response); - }), - respondToRequest: (requestId, decision) => - Effect.gen(function* () { - const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId); - if (!pending) { - return yield* new CodexSessionRuntimePendingApprovalNotFoundError({ - requestId, - }); - } - yield* Ref.update(pendingApprovalsRef, (current) => { - const next = new Map(current); - next.delete(requestId); - return next; - }); - yield* Deferred.succeed(pending.decision, decision); - yield* emitEvent({ - kind: "notification", - threadId: options.threadId, - method: "item/requestApproval/decision", - requestId: pending.requestId, - requestKind: pending.requestKind, - ...(pending.turnId ? { turnId: pending.turnId } : {}), - ...(pending.itemId ? { itemId: pending.itemId } : {}), - payload: { - requestId: pending.requestId, - requestKind: pending.requestKind, - decision, - }, - }); - }), - respondToUserInput: (requestId, answers) => - Effect.gen(function* () { - const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId); - if (!pending) { - return yield* new CodexSessionRuntimePendingUserInputNotFoundError({ - requestId, - }); - } - const codexAnswers = yield* toCodexUserInputAnswers(answers); - yield* Ref.update(pendingUserInputsRef, (current) => { - const next = new Map(current); - next.delete(requestId); - return next; - }); - yield* Deferred.succeed(pending.answers, answers); - yield* emitEvent({ - kind: "notification", - threadId: options.threadId, - method: "item/tool/requestUserInput/answered", - requestId: pending.requestId, - ...(pending.turnId ? { turnId: pending.turnId } : {}), - ...(pending.itemId ? { itemId: pending.itemId } : {}), - payload: { - answers: codexAnswers, - }, - }); - }), - events: Stream.fromQueue(events), - close, - } satisfies CodexSessionRuntimeShape; - }); diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts deleted file mode 100644 index 4332b6f8d3..0000000000 --- a/apps/server/src/provider/codexAppServer.ts +++ /dev/null @@ -1,243 +0,0 @@ -import type { - ModelCapabilities, - ServerProviderModel, - ServerProviderSkill, -} from "@t3tools/contracts"; -import { Effect, Layer } from "effect"; -import * as CodexClient from "effect-codex-app-server/client"; -import type * as EffectCodexSchema from "effect-codex-app-server/schema"; -import type { Mutable } from "effect/Types"; - -export interface CodexAppServerProviderSnapshot { - readonly account: EffectCodexSchema.V2GetAccountResponse; - readonly version: string | undefined; - readonly models: ReadonlyArray; - readonly skills: ReadonlyArray; -} - -const REASONING_EFFORT_LABELS: Record< - EffectCodexSchema.V2ModelListResponse__ReasoningEffort, - string -> = { - none: "None", - minimal: "Minimal", - low: "Low", - medium: "Medium", - high: "High", - xhigh: "Extra High", -}; - -export function codexAccountAuthLabel(account: EffectCodexSchema.V2GetAccountResponse["account"]) { - if (!account) return undefined; - if (account.type === "apiKey") return "OpenAI API Key"; - - switch (account.planType) { - case "free": - return "ChatGPT Free Subscription"; - case "go": - return "ChatGPT Go Subscription"; - case "plus": - return "ChatGPT Plus Subscription"; - case "pro": - return "ChatGPT Pro Subscription"; - case "team": - return "ChatGPT Team Subscription"; - case "self_serve_business_usage_based": - case "business": - return "ChatGPT Business Subscription"; - case "enterprise_cbp_usage_based": - case "enterprise": - return "ChatGPT Enterprise Subscription"; - case "edu": - return "ChatGPT Edu Subscription"; - case "unknown": - return "ChatGPT Subscription"; - default: - account.planType satisfies never; - return undefined; - } -} - -function mapCodexModelCapabilities( - model: EffectCodexSchema.V2ModelListResponse__Model, -): ModelCapabilities { - return { - reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({ - value: reasoningEffort, - label: REASONING_EFFORT_LABELS[reasoningEffort], - ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}), - })), - supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"), - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }; -} - -const toDisplayName = (model: EffectCodexSchema.V2ModelListResponse__Model): string => { - // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash - return model.displayName - .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT' - .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase()); -}; - -function parseCodexModelListResponse( - response: EffectCodexSchema.V2ModelListResponse, -): ReadonlyArray { - return response.data.map((model) => ({ - slug: model.model, - name: toDisplayName(model), - isCustom: false, - capabilities: mapCodexModelCapabilities(model), - })); -} - -function appendCustomCodexModels( - models: ReadonlyArray, - customModels: ReadonlyArray, -): ReadonlyArray { - if (customModels.length === 0) { - return models; - } - - const seen = new Set(models.map((model) => model.slug)); - const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null; - const customEntries: ServerProviderModel[] = []; - for (const rawModel of customModels) { - const slug = rawModel.trim(); - if (!slug || seen.has(slug)) { - continue; - } - seen.add(slug); - customEntries.push({ - slug, - name: slug, - isCustom: true, - capabilities: fallbackCapabilities, - }); - } - return customEntries.length === 0 ? models : [...models, ...customEntries]; -} - -function parseCodexSkillsListResponse( - response: EffectCodexSchema.V2SkillsListResponse, - cwd: string, -): ReadonlyArray { - const matchingEntry = response.data.find((entry) => entry.cwd === cwd); - const skills = matchingEntry - ? matchingEntry.skills - : response.data.flatMap((entry) => entry.skills); - - return skills.map((skill) => { - const shortDescription = - skill.shortDescription ?? skill.interface?.shortDescription ?? undefined; - - const parsedSkill: Mutable = { - name: skill.name, - path: skill.path, - enabled: skill.enabled, - }; - - if (skill.description) { - parsedSkill.description = skill.description; - } - if (skill.scope) { - parsedSkill.scope = skill.scope; - } - if (skill.interface?.displayName) { - parsedSkill.displayName = skill.interface.displayName; - } - if (shortDescription) { - parsedSkill.shortDescription = shortDescription; - } - - return parsedSkill; - }); -} - -export function buildCodexInitializeParams(): EffectCodexSchema.V1InitializeParams { - return { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: true, - }, - }; -} - -const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* ( - client: CodexClient.CodexAppServerClientShape, -) { - const models: ServerProviderModel[] = []; - let cursor: string | null | undefined = undefined; - - do { - const response: EffectCodexSchema.V2ModelListResponse = yield* client.request( - "model/list", - cursor ? { cursor } : {}, - ); - models.push(...parseCodexModelListResponse(response)); - cursor = response.nextCursor; - } while (cursor); - - return models; -}); - -export const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")( - function* (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - readonly customModels?: ReadonlyArray; - }) { - const clientContext = yield* Layer.build( - CodexClient.layerCommand({ - command: input.binaryPath, - args: ["app-server"], - cwd: input.cwd, - ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}), - }), - ); - const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( - Effect.provide(clientContext), - ); - - const initialize = yield* client.request("initialize", buildCodexInitializeParams()); - yield* client.notify("initialized", undefined); - - // Extract the version string after the first '/' in userAgent, up to the next space or the end - const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); - const version = versionMatch ? versionMatch[1] : undefined; - - const accountResponse = yield* client.request("account/read", {}); - if (!accountResponse.account && accountResponse.requiresOpenaiAuth) { - return { - account: accountResponse, - version, - models: appendCustomCodexModels([], input.customModels ?? []), - skills: [], - } satisfies CodexAppServerProviderSnapshot; - } - - const [skillsResponse, models] = yield* Effect.all( - [ - client.request("skills/list", { - cwds: [input.cwd], - }), - requestAllCodexModels(client), - ], - { concurrency: "unbounded" }, - ); - - return { - account: accountResponse, - version, - models: appendCustomCodexModels(models, input.customModels ?? []), - skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), - } satisfies CodexAppServerProviderSnapshot; - }, - Effect.scoped, -); diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index 3be65d723f..d2b6b52e8f 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -31,7 +31,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly getSettings: Effect.Effect; readonly streamSettings: Stream.Stream; readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean; - readonly initialSnapshot: (settings: Settings) => ServerProvider; + readonly initialSnapshot: (settings: Settings) => Effect.Effect; readonly checkProvider: Effect.Effect; readonly enrichSnapshot?: (input: { readonly settings: Settings; @@ -40,14 +40,20 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; }) => Effect.Effect; readonly refreshInterval?: Duration.Input; -}): Effect.fn.Return { +}): Effect.fn.Return< + ServerProviderShape, + ServerSettingsError, + Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService +> { + const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const serverSettings = yield* ServerSettingsService; const refreshSemaphore = yield* Semaphore.make(1); const changesPubSub = yield* Effect.acquireRelease( PubSub.unbounded(), PubSub.shutdown, ); const initialSettings = yield* input.getSettings; - const initialSnapshot = input.initialSnapshot(initialSettings); + const initialSnapshot = yield* input.initialSnapshot(initialSettings); const snapshotStateRef = yield* Ref.make({ snapshot: initialSnapshot, enrichmentGeneration: 0, @@ -141,6 +147,42 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( return yield* applySnapshot(nextSettings, { forceRefresh: true }); }); + const hasProviderStatusDemand = Effect.gen(function* () { + const state = yield* Ref.get(snapshotStateRef); + const instanceId = state.snapshot.instanceId; + const [genericDemand, instanceDemand] = yield* Effect.all([ + backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }), + backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }), + ]); + return genericDemand || instanceDemand; + }); + + const getRefreshInterval = + input.refreshInterval !== undefined + ? Effect.succeed(input.refreshInterval) + : serverSettings.getSettings.pipe( + Effect.map( + (settings) => + resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval, + ), + Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL), + ); + + const refreshIntervalChanges = yield* Queue.sliding(1); + if (input.refreshInterval === undefined) { + const serverSettingsChanges = yield* serverSettings.subscribeChanges; + yield* serverSettingsChanges.pipe( + Stream.map((settings) => + Duration.toMillis( + resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval, + ), + ), + Stream.changes, + Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)), + Effect.forkScoped, + ); + } + yield* Stream.runForEach(input.streamSettings, (nextSettings) => Effect.asVoid(applySnapshot(nextSettings)), ).pipe(Effect.forkScoped); @@ -177,11 +219,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( ); return { - getSnapshot: input.getSettings.pipe( - Effect.flatMap(applySnapshot), - Effect.tapError(Effect.logError), - Effect.orDie, - ), + maintenanceCapabilities: input.maintenanceCapabilities, + getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie), get streamChanges() { return Stream.fromPubSub(changesPubSub); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 5552b48ada..1f392923b1 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -44,6 +44,7 @@ import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environme import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import { forkParked } from "../serverActivation.ts"; export class AgentAwarenessRelay extends Context.Service< AgentAwarenessRelay, @@ -183,7 +184,7 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: { // Compact, log-safe view of the fields the awareness phase ladder reads. export function describeThreadShellForAwareness( - thread: Option.Option, + thread: Option.Option, ): Record { if (Option.isNone(thread)) { return { found: false }; @@ -191,13 +192,11 @@ export function describeThreadShellForAwareness( const shell = thread.value; return { found: true, - sessionStatus: shell.session?.status ?? null, - sessionActiveTurnId: shell.session?.activeTurnId ?? null, - latestTurnId: shell.latestTurn?.turnId ?? null, - latestTurnState: shell.latestTurn?.state ?? null, - latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null, - hasPendingApprovals: shell.hasPendingApprovals, - hasPendingUserInput: shell.hasPendingUserInput, + status: shell.status, + activeRunId: shell.activeRunId ?? null, + latestRunId: shell.latestRunId ?? null, + pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null, + hasActionableProposedPlan: shell.hasActionableProposedPlan, }; } @@ -586,7 +585,7 @@ export const make = Effect.gen(function* () { Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")), ), ); - yield* Effect.forkScoped( + yield* forkParked( Stream.runForEach(threads.streamDomainEvents, (event) => { const threadId = eventThreadId(event); if (!shouldPublishAgentAwarenessEvent(event)) { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index c53ab2816b..e576f454cc 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,7 +33,7 @@ import * as GitHubCli from "./sourceControl/GitHubCli.ts"; import * as GitLabCli from "./sourceControl/GitLabCli.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts"; -import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts"; +import { layer as ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as McpHttpServer from "./mcp/McpHttpServer.ts"; import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts"; @@ -91,21 +91,32 @@ import { } from "./orchestration-v2/runtimeLayer.ts"; import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; +import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; +import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; +import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; +import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; +import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import { clearPersistedServerRuntimeState, makePersistedServerRuntimeState, persistServerRuntimeState, } from "./serverRuntimeState.ts"; +import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts"; import { projectHttpApiLayer } from "./project/http.ts"; import * as NetService from "@t3tools/shared/Net"; import * as RelayClient from "@t3tools/shared/relayClient"; import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale"; +import { forkParked, ServerActivation } from "./serverActivation.ts"; // Effect's default preemptive shutdown waits 20s before finalizing request scopes. // T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer // already closes the websocket gracefully. Do not add an artificial drain before // those finalizers get a chance to run. const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0; +const ResourceAttributionLayerLive = ResourceAttribution.layer; +const ApplicationObservabilityLive = ObservabilityLive.pipe( + Layer.provideMerge(ResourceAttributionLayerLive), +); const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -294,14 +305,12 @@ const WorkspaceLayerLive = Layer.mergeAll( WorkspaceFileSystemLayerLive, ); -const OrchestrationV2RuntimeLayerLive = OrchestrationV2LayerLive.pipe( - Layer.provide(CheckpointStoreLive), - Layer.provide(GitCoreLive), - Layer.provide(PersistenceLayerLive), - Layer.provide(ServerSettingsLive), +const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe( + Layer.provide(WorkspacePaths.layer), + Layer.provide(T3ProjectFileLoader.layer), ); -const AuthLayerLive = ServerAuthLive.pipe( +const AuthLayerLive = EnvironmentAuth.layer.pipe( Layer.provideMerge(PersistenceLayerLive), Layer.provide(ServerSecretStore.layer), ); @@ -328,6 +337,7 @@ const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe( const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe( // Core Services Layer.provideMerge(OrchestrationApplicationLayerLive), + Layer.provideMerge(ServerSettingsLayerLive), Layer.provideMerge(SourceControlProviderRegistryLayerLive), Layer.provideMerge(GitLayerLive), Layer.provideMerge(VcsLayerLive), @@ -344,6 +354,11 @@ const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe( ); const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( + // Shared native/canonical NDJSON writers used by both the per-instance + // V2 drivers and the orchestration runtime. Provide resource attribution so + // the rewritten telemetry pipeline can account for logical NDJSON writes. + // Provided once at the runtime level so every consumer sees the same + // logger instances. Layer.provideMerge(ProviderEventLoggersLive), // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but @@ -357,12 +372,16 @@ const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( Layer.provideMerge(RepositoryIdentityResolver.layer), Layer.provideMerge(ServerEnvironment.layer), Layer.provideMerge(AuthLayerLive), - Layer.provideMerge(OrchestrationV2RuntimeLayerLive), - - // Misc. - Layer.provideMerge(AnalyticsServiceLayerLive), - Layer.provideMerge(OpenLive), - Layer.provideMerge(ServerLifecycleEventsLive), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge( + Layer.mergeAll( + CloudCliTokenManager.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(ExternalLauncher.layer), + ), + CloudManagedEndpointRuntimeLive, + ), + ), ); const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe( @@ -389,6 +408,7 @@ export const makeRoutesLayer = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), Layer.provide(connectHttpApiLayer), + Layer.provide(orchestrationHttpApiLayer), Layer.provide(projectHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), @@ -398,8 +418,14 @@ export const makeRoutesLayer = Layer.mergeAll( staticAndDevRouteLayer, websocketRpcRouteLayer, ), - McpHttpServer.layer, -).pipe(Layer.provide(browserApiCorsLayer)); + McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)), +).pipe( + Layer.provide(PreviewAutomationBroker.layer), + Layer.provide(ServerSelfUpdate.layer), + Layer.provide(commandReadinessLayer), + Layer.provide(browserApiCorsLayer), + Layer.provide(httpCompressionLayer), +); export const makeServerLayer = Layer.unwrap( Effect.gen(function* () { @@ -603,8 +629,9 @@ export const makeServerLayer = Layer.unwrap( ); return serverApplicationLayer.pipe( - Layer.provideMerge(RuntimeServicesLive), + Layer.provideMerge(runtimeServicesLive), Layer.provideMerge(McpSessionRegistry.layer.pipe(Layer.provide(ServerEnvironment.layer))), + Layer.provide(activationLayer), Layer.provideMerge(serverRelayBrokerTracingLayer), Layer.provideMerge(HttpServerLive), Layer.provide(ApplicationObservabilityLive), diff --git a/apps/server/src/serverActivation.ts b/apps/server/src/serverActivation.ts index c068d55e7e..2132697353 100644 --- a/apps/server/src/serverActivation.ts +++ b/apps/server/src/serverActivation.ts @@ -1,6 +1,7 @@ import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import type * as Fiber from "effect/Fiber"; import type * as Scope from "effect/Scope"; export class ServerActivation extends Context.Reference | undefined>( @@ -8,19 +9,24 @@ export class ServerActivation extends Context.Reference | un { defaultValue: () => undefined }, ) {} -/** Forks a long-running root before commit and proves it is parked at the activation boundary. */ -export const forkParked = ( +/** Forks a long-running root before commit, returning it after it reaches the activation boundary. */ +export const forkParkedFiber = ( effect: Effect.Effect, -): Effect.Effect => +): Effect.Effect, never, Scope.Scope | R> => Effect.gen(function* () { const activation = yield* ServerActivation; if (activation === undefined) { - yield* Effect.forkScoped(effect); - return; + return yield* Effect.forkScoped(effect); } const parked = yield* Deferred.make(); - yield* Effect.forkScoped( + const fiber = yield* Effect.forkScoped( Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)), ); yield* Deferred.await(parked); + return fiber; }); + +/** Forks a long-running root before commit and proves it is parked at the activation boundary. */ +export const forkParked = ( + effect: Effect.Effect, +): Effect.Effect => forkParkedFiber(effect).pipe(Effect.asVoid); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 046448a4c6..56f847be26 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,10 +1,12 @@ import { assert, it } from "@effect/vitest"; import { DEFAULT_MODEL, ProviderInstanceId } from "@t3tools/contracts"; +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 Ref from "effect/Ref"; +import * as ServerConfig from "./config.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; it("uses the canonical Codex model for auto-bootstrap", () => { @@ -95,3 +97,43 @@ it.effect("queues commands until startup signals readiness", () => }), ), ); + +it.effect("enqueueCommand fails queued work when readiness fails", () => + Effect.scoped( + Effect.gen(function* () { + const commandGate = yield* ServerRuntimeStartup.makeCommandGate; + const failure = yield* Deferred.make(); + + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) + .pipe(Effect.forkScoped); + + yield* commandGate.failCommandReady( + new ServerRuntimeStartup.ServerRuntimeStartupError({ + mode: "web", + host: "127.0.0.1", + port: 3773, + cause: new Error("test startup failure"), + }), + ); + + const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); + assert.equal(error.message, "Server runtime startup failed before command readiness."); + }), + ), +); + +it.effect("resolveWelcomeBase derives cwd and project name from server config", () => + Effect.gen(function* () { + const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe( + Effect.provideService(ServerConfig.ServerConfig, { + cwd: "/tmp/startup-project", + } as never), + ); + + assert.deepStrictEqual(welcome, { + cwd: "/tmp/startup-project", + projectName: "startup-project", + }); + }), +); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 73638c9415..99af107696 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -23,6 +23,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as ServerConfig from "./config.ts"; +import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; @@ -36,6 +37,7 @@ import * as ProjectService from "./project/ProjectService.ts"; import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerSettings from "./serverSettings.ts"; +import { forkParked, forkParkedFiber } from "./serverActivation.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; @@ -286,6 +288,12 @@ const runStartupPhase = (phase: string, effect: Effect.Effect) Effect.withSpan(`server.startup.${phase}`), ); +interface StartupOptions { + readonly activate?: Effect.Effect; + readonly awaitAuxiliaryParked?: Effect.Effect; + readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect; +} + export const startEffectWorkerWithRelay = Effect.fn( "ServerRuntimeStartup.startEffectWorkerWithRelay", )(function* (input: { @@ -293,7 +301,7 @@ export const startEffectWorkerWithRelay = Effect.fn( readonly startRelay: Effect.Effect; readonly workerFiberRef: Ref.Ref | null>; }) { - const workerFiber = yield* input.runWorker.pipe(Effect.forkScoped); + const workerFiber = yield* forkParkedFiber(input.runWorker); yield* Ref.set(input.workerFiberRef, workerFiber); yield* input.startRelay.pipe( Effect.onExit((exit) => { @@ -355,232 +363,257 @@ export function runOrderedV2StartupPhases< }); } -export const make = Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const keybindings = yield* Keybindings.Keybindings; - const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; - const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; - const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; - const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; - const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; - const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; - const crypto = yield* Crypto.Crypto; +export const make = (options?: StartupOptions) => + Effect.gen(function* () { + const serverConfig = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; + const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; + const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const crypto = yield* Crypto.Crypto; + const launcher = yield* ServiceLauncherClient.ServiceLauncherClient; - const commandGate = yield* makeCommandGate; - const httpListening = yield* Deferred.make(); - const effectWorkerFiber = yield* Ref.make | null>(null); + const commandGate = yield* makeCommandGate; + const httpListening = yield* Deferred.make(); + const effectWorkerFiber = yield* Ref.make | null>(null); - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - yield* commandGate.failCommandReady( - new ServerRuntimeStartupError({ - mode: serverConfig.mode, - host: serverConfig.host ?? null, - port: serverConfig.port, - cause: "Server runtime is shutting down.", - }), - ); - const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null); - if (workerFiber !== null) { - yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); - } - yield* providerSessions.shutdown; - const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); - yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("V2 orchestration shutdown reconciliation failed", { - cause: Cause.pretty(cause), - }), - ), - ), - ); - - yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void)); - - yield* Effect.logDebug("startup phase: starting server settings runtime"); - yield* runStartupPhase( - "settings.start", - serverSettings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start server settings runtime", { - path: error.settingsPath, - operation: error.operation, - providerInstanceId: error.providerInstanceId, - environmentVariable: error.environmentVariable, - cause: error.cause, + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* commandGate.failCommandReady( + new ServerRuntimeStartupError({ + mode: serverConfig.mode, + host: serverConfig.host ?? null, + port: serverConfig.port, + cause: "Server runtime is shutting down.", + }), + ); + const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null); + if (workerFiber !== null) { + yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); + } + yield* providerSessions.shutdown; + const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); + yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("V2 orchestration shutdown reconciliation failed", { + cause: Cause.pretty(cause), }), ), - Effect.forkScoped, ), ); - const welcomeBase = yield* resolveWelcomeBase; - const environment = yield* serverEnvironment.getDescriptor; - const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount; - if (legacyMigrationThreadCount > 0) { - yield* lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "running", - totalThreadCount: legacyMigrationThreadCount, - }, - }); - } - const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({ - importLegacyShells: runStartupPhase( - "orchestration-v2.legacy-v1.import-shells", - legacyV1ThreadImporter.reconcileShells.pipe( - Effect.tap((summary) => - summary.importedThreadCount === 0 - ? Effect.void - : Effect.logInfo("Imported legacy v1 thread shells", summary), + const startup = Effect.gen(function* () { + yield* Effect.logDebug("startup phase: starting keybindings runtime"); + yield* runStartupPhase( + "keybindings.start", + keybindings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start keybindings runtime", { + path: error.configPath, + detail: error.detail, + cause: error.cause, + }), ), ), - ), - verify: runStartupPhase( - "orchestration-v2.projections.verify", - projectionMaintenance.verify.pipe( - Effect.tap((verification) => - verification.valid - ? Effect.void - : Effect.logWarning( - "V2 orchestration projection metadata or structure is invalid; rebuilding", - { - expectedSequence: verification.expectedSequence, - projectionSequence: verification.projectionSequence, - schemaVersion: verification.schemaVersion, - missingThreadCount: verification.missingThreadIds.length, - unexpectedThreadCount: verification.unexpectedThreadIds.length, - unreadableThreadCount: verification.unreadableThreadIds.length, - }, - ), + ); + + yield* Effect.logDebug("startup phase: starting server settings runtime"); + yield* runStartupPhase( + "settings.start", + serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + operation: error.operation, + providerInstanceId: error.providerInstanceId, + environmentVariable: error.environmentVariable, + cause: error.cause, + }), ), ), - ), - rebuild: runStartupPhase( - "orchestration-v2.projections.rebuild", - projectionMaintenance.rebuild, - ), - recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), - startEffectWorker: runStartupPhase( - "orchestration-v2.effect-worker.start", - startEffectWorkerWithRelay({ - runWorker: EffectWorker.runDaemon, - startRelay: agentAwarenessRelay.start(), - workerFiberRef: effectWorkerFiber, - }), - ), - autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd - ? runStartupPhase( - "welcome.autobootstrap", - resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)), - ) - : Effect.succeed({}) - ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)), - }); - yield* Effect.logInfo("V2 orchestration recovery completed", recovery); + ); - yield* Effect.logDebug("Accepting commands"); - yield* commandGate.signalCommandReady; - const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe( - Effect.tap((summary) => - summary.importedThreadCount === 0 - ? Effect.void - : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary), - ), - ); - yield* ( - legacyMigrationThreadCount > 0 - ? importPendingTranscripts.pipe( - Effect.tap(() => - lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "complete", - totalThreadCount: legacyMigrationThreadCount, - }, - }), - ), - ) - : importPendingTranscripts - ).pipe(Effect.forkScoped); - - // Off the startup path: the first run after an upgrade deletes the whole - // superseded-event and legacy-v1 backlog (potentially millions of rows, - // paced in small batches), and nothing at boot depends on it. - yield* projectionMaintenance.compactEventStore.pipe( - Effect.tap((summary) => - summary.deletedEventCount === 0 && summary.deletedReceiptCount === 0 - ? Effect.void - : Effect.logInfo("Compacted orchestration event store", summary), - ), - Effect.tap((summary) => - // Freed pages are reused, so the file stops growing regardless; only - // an offline VACUUM shrinks it, which is not safe to run on the - // synchronous sqlite connection while serving. - summary.reclaimableBytes >= 512 * 1024 * 1024 - ? Effect.logInfo( - "state.sqlite has substantial reclaimable free space; an offline VACUUM would shrink the file", - { reclaimableBytes: summary.reclaimableBytes }, - ) - : Effect.void, - ), - Effect.catch((cause) => Effect.logWarning("Unable to compact the event store", { cause })), - Effect.forkScoped, - ); - - yield* Effect.logDebug("startup phase: publishing welcome event", { - environmentId: environment.environmentId, - cwd: welcomeBase.cwd, - projectName: welcomeBase.projectName, - bootstrapProjectId: bootstrapTargets.bootstrapProjectId, - bootstrapThreadId: bootstrapTargets.bootstrapThreadId, - }); - yield* runStartupPhase( - "welcome.publish", - lifecycleEvents.publish({ - version: 1, - type: "welcome", - payload: { - environment, - ...welcomeBase, - ...bootstrapTargets, - }, - }), - ); - }).pipe( - Effect.annotateSpans({ - "server.mode": serverConfig.mode, - "server.port": serverConfig.port, - "server.host": serverConfig.host ?? "default", - }), - Effect.withSpan("server.startup", { kind: "server", root: true }), - ); - - yield* Effect.forkScoped( - Effect.gen(function* () { - const startupExit = yield* Effect.exit(startup); - if (Exit.isFailure(startupExit)) { - const error = new ServerRuntimeStartupError({ - mode: serverConfig.mode, - host: serverConfig.host ?? null, - port: serverConfig.port, - cause: startupExit.cause, + const welcomeBase = yield* resolveWelcomeBase; + const environment = yield* serverEnvironment.getDescriptor; + const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount; + if (legacyMigrationThreadCount > 0) { + yield* lifecycleEvents.publish({ + version: 1, + type: "legacyThreadMigration", + payload: { + status: "running", + totalThreadCount: legacyMigrationThreadCount, + }, }); - yield* Effect.logError("server runtime startup failed", { - cause: Cause.pretty(startupExit.cause), - }); - yield* commandGate.failCommandReady(error); - return; } + const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({ + importLegacyShells: runStartupPhase( + "orchestration-v2.legacy-v1.import-shells", + legacyV1ThreadImporter.reconcileShells.pipe( + Effect.tap((summary) => + summary.importedThreadCount === 0 + ? Effect.void + : Effect.logInfo("Imported legacy v1 thread shells", summary), + ), + ), + ), + verify: runStartupPhase( + "orchestration-v2.projections.verify", + projectionMaintenance.verify.pipe( + Effect.tap((verification) => + verification.valid + ? Effect.void + : Effect.logWarning( + "V2 orchestration projection metadata or structure is invalid; rebuilding", + { + expectedSequence: verification.expectedSequence, + projectionSequence: verification.projectionSequence, + schemaVersion: verification.schemaVersion, + missingThreadCount: verification.missingThreadIds.length, + unexpectedThreadCount: verification.unexpectedThreadIds.length, + unreadableThreadCount: verification.unreadableThreadIds.length, + }, + ), + ), + ), + ), + rebuild: runStartupPhase( + "orchestration-v2.projections.rebuild", + projectionMaintenance.rebuild, + ), + recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), + startEffectWorker: runStartupPhase( + "orchestration-v2.effect-worker.start", + startEffectWorkerWithRelay({ + runWorker: EffectWorker.runDaemon, + startRelay: agentAwarenessRelay.start(), + workerFiberRef: effectWorkerFiber, + }), + ), + autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd + ? runStartupPhase( + "welcome.autobootstrap", + resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)), + ) + : Effect.succeed({}) + ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)), + }); + yield* Effect.logInfo("V2 orchestration recovery completed", recovery); + + const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe( + Effect.tap((summary) => + summary.importedThreadCount === 0 + ? Effect.void + : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary), + ), + ); + yield* ( + legacyMigrationThreadCount > 0 + ? importPendingTranscripts.pipe( + Effect.tap(() => + lifecycleEvents.publish({ + version: 1, + type: "legacyThreadMigration", + payload: { + status: "complete", + totalThreadCount: legacyMigrationThreadCount, + }, + }), + ), + ) + : importPendingTranscripts + ).pipe(forkParked); + + // Off the startup path: the first run after an upgrade deletes the whole + // superseded-event and legacy-v1 backlog (potentially millions of rows, + // paced in small batches), and nothing at boot depends on it. + yield* projectionMaintenance.compactEventStore.pipe( + Effect.tap((summary) => + summary.deletedEventCount === 0 && summary.deletedReceiptCount === 0 + ? Effect.void + : Effect.logInfo("Compacted orchestration event store", summary), + ), + Effect.tap((summary) => + // Freed pages are reused, so the file stops growing regardless; only + // an offline VACUUM shrinks it, which is not safe to run on the + // synchronous sqlite connection while serving. + summary.reclaimableBytes >= 512 * 1024 * 1024 + ? Effect.logInfo( + "state.sqlite has substantial reclaimable free space; an offline VACUUM would shrink the file", + { reclaimableBytes: summary.reclaimableBytes }, + ) + : Effect.void, + ), + Effect.catch((cause) => Effect.logWarning("Unable to compact the event store", { cause })), + forkParked, + ); + + yield* forkParked( + Effect.gen(function* () { + yield* Effect.logDebug("startup phase: recording startup heartbeat"); + yield* recordStartupHeartbeat.pipe( + Effect.annotateSpans({ "startup.phase": "heartbeat.record" }), + Effect.withSpan("server.startup.heartbeat.record"), + Effect.ignoreCause({ log: true }), + ); + if (serverConfig.startupPresentation === "headless") { + yield* Effect.logDebug("startup phase: headless access info"); + const accessInfo = yield* issueHeadlessServeAccessInfo(); + yield* runStartupPhase( + "headless.output", + Console.log(formatHeadlessServeOutput(accessInfo)), + ); + } else { + yield* Effect.logDebug("startup phase: browser open check"); + const startupBrowserTarget = yield* resolveStartupBrowserTarget; + if (serverConfig.mode !== "desktop") { + yield* Effect.logInfo( + "Authentication required. Open T3 Code using the pairing URL.", + ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget })); + } + yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); + } + }), + ); yield* Effect.logDebug("startup phase: waiting for http listener"); yield* runStartupPhase("http.wait", Deferred.await(httpListening)); + yield* runStartupPhase( + "auxiliary-roots.parked", + options?.awaitAuxiliaryParked ?? Effect.void, + ); + + const updateOutcome = yield* launcher.prepareTrial; + + yield* Effect.logDebug("startup phase: publishing welcome event", { + environmentId: environment.environmentId, + cwd: welcomeBase.cwd, + projectName: welcomeBase.projectName, + bootstrapProjectId: bootstrapTargets.bootstrapProjectId, + bootstrapThreadId: bootstrapTargets.bootstrapThreadId, + }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: { + environment, + ...welcomeBase, + ...bootstrapTargets, + }, + }), + ); + + yield* options?.activate ?? Effect.void; + yield* Effect.logDebug("Accepting commands"); + yield* commandGate.signalCommandReady; yield* Effect.logDebug("startup phase: publishing ready event"); yield* runStartupPhase( "ready.publish", @@ -615,7 +648,7 @@ export const make = Effect.gen(function* () { cause: startupExit.cause, }); return Effect.logError("server runtime startup failed", { - cause: startupExit.cause, + cause: Cause.pretty(startupExit.cause), }).pipe( Effect.andThen(commandGate.failCommandReady(error)), Effect.andThen(options?.abort?.(error) ?? Effect.void), diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index d29acf458e..2798faf6f0 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -182,14 +182,6 @@ export const layerTest = (overrides: DeepPartial = {}) => const ServerSettingsJson = fromLenientJson(ServerSettings); const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson); -const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"]; - -/** - * Ensure the `textGenerationModelSelection` points to an enabled provider. - * If the selected provider is disabled, fall back to the first enabled - * provider with its default model. This is applied at read-time so the - * persisted preference is preserved for when a provider is re-enabled. - */ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings { return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) ? settings diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts new file mode 100644 index 0000000000..378ad745c3 --- /dev/null +++ b/apps/server/src/ws.test.ts @@ -0,0 +1,25 @@ +import { assert, it } from "@effect/vitest"; +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 TestClock from "effect/testing/TestClock"; + +import { resolveAvailableEditorsForConfig } from "./ws.ts"; + +it.effect("does not block server config when editor discovery never resolves", () => + Effect.gen(function* () { + const discoveryInterrupted = yield* Deferred.make(); + const responseFiber = yield* resolveAvailableEditorsForConfig( + Effect.never.pipe( + Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)), + ), + ).pipe(Effect.forkChild); + + yield* TestClock.adjust(Duration.seconds(5)); + + const availableEditors = yield* Fiber.join(responseFiber); + yield* Deferred.await(discoveryInterrupted); + assert.deepEqual(availableEditors, []); + }), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 9ad0c53fbf..a8655249e4 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -14,6 +14,7 @@ import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, AuthAccessStreamError, type AuthAccessStreamEvent, + type ApplicationStoredEvent, type AuthEnvironmentScope, AuthSessionId, CommandId, @@ -22,6 +23,7 @@ import { type GitManagerServiceError, type MessageId, OrchestrationGetFullThreadDiffError, + OrchestrationSearchThreadsError, OrchestrationGetTurnDiffError, ORCHESTRATION_V2_WS_METHODS, OrchestrationV2DispatchCommandError, @@ -29,6 +31,7 @@ import { OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, type OrchestrationProjectShell, + type OrchestrationV2ShellSnapshot, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, @@ -41,12 +44,15 @@ import { ProjectMutationError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, + type ServerSelfUpdateError, + type ServerSelfUpdateProgressEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, ChatAttachmentId, PersistChatAttachmentsError, + RpcClientId, EnvironmentAuthorizationError, ThreadId, type TerminalAttachStreamEvent, @@ -56,6 +62,7 @@ import { WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; +import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http"; import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -131,6 +138,16 @@ import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; import * as RelayClient from "@t3tools/shared/relayClient"; +const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5); + +export const resolveAvailableEditorsForConfig = ( + discovery: Effect.Effect, E, R>, +) => + discovery.pipe( + Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT), + Effect.map(Option.getOrElse(() => [])), + ); + function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } @@ -308,74 +325,20 @@ function projectFileFailureContext( const PROVIDER_STATUS_DEBOUNCE_MS = 200; -const RPC_REQUIRED_SCOPE = new Map([ - [ORCHESTRATION_V2_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope], - [ORCHESTRATION_V2_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.getThreadProjection, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.launchThread, AuthOrchestrationOperateScope], - [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.subscribeShell, AuthOrchestrationReadScope], - [ORCHESTRATION_V2_WS_METHODS.subscribeThread, AuthOrchestrationReadScope], - [WS_METHODS.serverGetConfig, AuthOrchestrationReadScope], - [WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope], - [WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope], - [WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope], - [WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope], - [WS_METHODS.serverGetSettings, AuthOrchestrationReadScope], - [WS_METHODS.serverUpdateSettings, AuthOrchestrationOperateScope], - [WS_METHODS.serverDiscoverSourceControl, AuthOrchestrationReadScope], - [WS_METHODS.serverGetTraceDiagnostics, AuthOrchestrationReadScope], - [WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope], - [WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope], - [WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope], - [WS_METHODS.scheduledTasksList, AuthOrchestrationReadScope], - [WS_METHODS.scheduledTasksSubscribe, AuthOrchestrationReadScope], - [WS_METHODS.scheduledTasksUpsert, AuthOrchestrationOperateScope], - [WS_METHODS.scheduledTasksSetEnabled, AuthOrchestrationOperateScope], - [WS_METHODS.scheduledTasksDelete, AuthOrchestrationOperateScope], - [WS_METHODS.scheduledTasksRunNow, AuthOrchestrationOperateScope], - [WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope], - [WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope], - [WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope], - [WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope], - [WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope], - [WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope], - [WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope], - [WS_METHODS.projectsMutate, AuthOrchestrationOperateScope], - [WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope], - [WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope], - [WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope], - [WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope], - [WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope], - [WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope], - [WS_METHODS.vcsPull, AuthOrchestrationOperateScope], - [WS_METHODS.gitRunStackedAction, AuthOrchestrationOperateScope], - [WS_METHODS.gitResolvePullRequest, AuthOrchestrationOperateScope], - [WS_METHODS.gitPreparePullRequestThread, AuthOrchestrationOperateScope], - [WS_METHODS.vcsListRefs, AuthOrchestrationReadScope], - [WS_METHODS.vcsCreateWorktree, AuthOrchestrationOperateScope], - [WS_METHODS.vcsRemoveWorktree, AuthOrchestrationOperateScope], - [WS_METHODS.vcsCreateRef, AuthOrchestrationOperateScope], - [WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope], - [WS_METHODS.vcsInit, AuthOrchestrationOperateScope], - [WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope], - [WS_METHODS.terminalOpen, AuthTerminalOperateScope], - [WS_METHODS.terminalAttach, AuthTerminalOperateScope], - [WS_METHODS.terminalWrite, AuthTerminalOperateScope], - [WS_METHODS.terminalResize, AuthTerminalOperateScope], - [WS_METHODS.terminalClear, AuthTerminalOperateScope], - [WS_METHODS.terminalRestart, AuthTerminalOperateScope], - [WS_METHODS.terminalClose, AuthTerminalOperateScope], - [WS_METHODS.subscribeTerminalEvents, AuthTerminalOperateScope], - [WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope], - [WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope], - [WS_METHODS.subscribeServerLifecycle, AuthOrchestrationReadScope], - [WS_METHODS.subscribeAuthAccess, AuthAccessReadScope], -]); - const ServerWsRpcGroup = WsRpcGroup; +// When a resuming client's cursor is more than this many events behind the +// current head, skip the per-event catch-up replay and send a fresh shell +// snapshot instead. Replaying each intervening event costs a shell refetch; +// past this gap a single O(active-threads) snapshot is cheaper and bounded. +// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT). +const SHELL_RESUME_MAX_GAP = 1_000; + +// Same bound for thread resume. The replay reads the *global* event range and +// filters per-thread afterwards, so a stale cursor far behind the head would +// otherwise decode every intervening event's payload — reconnects with cursors +// hundreds of thousands of events behind have OOM-killed servers on large +// databases. Past this gap the client is reset with a fresh thread snapshot. +const THREAD_RESUME_MAX_GAP = 1_000; function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, @@ -417,7 +380,10 @@ function toAuthAccessStreamEvent( } } -const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => +const makeWsRpcLayer = ( + currentSession: EnvironmentAuth.AuthenticatedSession, + previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], +) => ServerWsRpcGroup.toLayer( Effect.gen(function* () { const currentSessionId = currentSession.sessionId; @@ -466,11 +432,11 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const terminalManager = yield* TerminalManager.TerminalManager; - const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker; const previewManager = yield* PreviewManager.PreviewManager; const portDiscovery = yield* PortScanner.PortDiscovery; const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; + const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; const config = yield* ServerConfig.ServerConfig; const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -478,10 +444,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const rpcClientIds = yield* Ref.make(new Set()); + yield* Effect.addFinalizer(() => + Ref.get(rpcClientIds).pipe( + Effect.flatMap((clientIds) => + Effect.forEach( + clientIds, + (clientId) => backgroundPolicy.removeRpcClient(currentSessionId, clientId), + { + discard: true, + }, + ), + ), + Effect.ignore, + ), + ); const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; const automaticGitFetchInterval = serverSettings.getSettings.pipe( - Effect.map((settings) => settings.automaticGitFetchInterval), + Effect.map( + (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval, + ), Effect.catch((cause) => Effect.logWarning("Failed to read automatic Git fetch interval setting", { detail: cause.message, @@ -494,6 +478,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const sessions = yield* SessionStore.SessionStore; const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; + const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; const relayClient = yield* RelayClient.RelayClient; const authorizationError = (requiredScope: AuthEnvironmentScope) => new EnvironmentAuthorizationError({ @@ -514,13 +499,6 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => currentSession.scopes.includes(requiredScope) ? stream : Stream.fail(authorizationError(requiredScope)); - const requiredScopeForMethod = (method: string): AuthEnvironmentScope => { - const requiredScope = RPC_REQUIRED_SCOPE.get(method); - if (requiredScope === undefined) { - throw new Error(`RPC method ${method} has no declared authorization scope.`); - } - return requiredScope; - }; const observeRpcEffect = ( method: string, effect: Effect.Effect, @@ -528,7 +506,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ) => instrumentRpcEffect( method, - authorizeEffect(requiredScopeForMethod(method), effect), + authorizeEffect(requiredScopeForRpcMethod(method), effect), traceAttributes, ); const observeRpcStream = ( @@ -538,7 +516,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ) => instrumentRpcStream( method, - authorizeStream(requiredScopeForMethod(method), stream), + authorizeStream(requiredScopeForRpcMethod(method), stream), traceAttributes, ); const observeRpcStreamEffect = ( @@ -552,7 +530,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ) => instrumentRpcStreamEffect( method, - authorizeEffect(requiredScopeForMethod(method), effect), + authorizeEffect(requiredScopeForRpcMethod(method), effect), traceAttributes, ); const loadAuthAccessSnapshot = () => @@ -611,7 +589,11 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subscribeThread")( - function* (input: { readonly threadId: ThreadId }) { + function* (input: { + readonly threadId: ThreadId; + readonly afterSequence?: number; + readonly requestCompletionMarker?: boolean; + }) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId, }); @@ -626,6 +608,80 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ), ); + const eventStreamFrom = (afterSequence: number) => + threadManagement + .streamStoredEventsFrom({ + threadId: input.threadId, + afterSequence, + }) + .pipe( + Stream.map((stored) => ({ + kind: "event" as const, + sequence: stored.sequence, + event: stored.event, + })), + Stream.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed while streaming orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + + const replayThrough = (afterSequence: number, throughSequence: number) => + applicationEvents + .readAgentEvents({ + threadId: input.threadId, + afterSequence, + throughSequence, + }) + .pipe( + Stream.map((stored) => ({ + kind: "event" as const, + sequence: stored.sequence, + event: stored.event, + })), + Stream.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed while replaying orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + + const completionMarker = + input.requestCompletionMarker === true + ? Stream.make({ kind: "synchronized" as const }) + : Stream.empty; + + // When the client already holds the projection (cached, or loaded over + // HTTP) it passes that snapshot's sequence, and we resume by replaying + // persisted events after it instead of re-sending the (potentially + // multi-KB) snapshot frame over the socket. The event sink subscribes + // to live events before reading the persisted tail, so no event + // published during the replay window is lost; overlapping events are + // deduped by sequence on the client. + if (input.afterSequence !== undefined) { + const highWater = yield* applicationEvents.latestAgentSequence(input.threadId).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`, + cause, + }), + ), + ); + return Stream.concat( + Stream.concat(replayThrough(input.afterSequence, highWater), completionMarker), + eventStreamFrom(highWater), + ); + } + const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe( Effect.mapError( (cause) => @@ -638,40 +694,25 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ); const { projection, snapshotSequence } = snapshot; - const liveStream = threadManagement - .streamStoredEventsFrom({ - threadId: input.threadId, - afterSequence: snapshotSequence, - }) - .pipe( - Stream.map((stored) => ({ - kind: "event" as const, - sequence: stored.sequence, - event: stored.event, - })), - Stream.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed while streaming orchestration V2 thread ${input.threadId}`, - cause, - }), - ), - ); - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshotSequence, - projection, - }), - liveStream, + Stream.concat( + Stream.make({ + kind: "snapshot" as const, + snapshotSequence, + projection, + }), + completionMarker, + ), + eventStreamFrom(snapshotSequence), ); }, ); const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( - function* () { + function* (input: { + readonly afterSequence?: number; + readonly requestCompletionMarker?: boolean; + }) { const enrichmentChanges = yield* projectEnrichment.subscribeChanges; const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () { const base = yield* sql.withTransaction( @@ -693,15 +734,32 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots, }; }); - const snapshot = yield* loadSnapshot().pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed to load the application shell snapshot", - cause, - }), - ), - ); + const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* ( + stored: Extract, + ) { + if (stored.type === "project.deleted") { + return { + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }; + } + const project = yield* projectionSnapshotQuery.getProjectShellById( + stored.payload.projectId, + ); + return Option.match(project, { + onNone: () => ({ + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }), + onSome: (value) => ({ + kind: "project.updated" as const, + sequence: stored.sequence, + project: value, + }), + }); + }); // Coalescing makes each per-thread shell read represent every event // for that thread in the current window; reading only the affected @@ -722,6 +780,17 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => }), { concurrency: 8 }, ); + }); + + const toShellStream = (stream: Stream.Stream) => + stream.pipe( + Stream.groupedWithin(512, Duration.millis(50)), + Stream.mapEffect((events) => projectShellItems(Array.from(events))), + Stream.flatMap(Stream.fromIterable), + ); + + const liveFrom = (afterSequence: number) => + toShellStream(applicationEvents.streamApplicationEvents({ afterSequence })); const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe( Stream.filter((change) => change.repositoryIdentityResolved), @@ -787,7 +856,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const highWater = yield* applicationEvents.latestApplicationSequence; const replayGap = highWater - input.afterSequence; - if (replayGap < 0 || replayGap > 1_000) { + if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) { return composeShellStreamWithEnrichment({ initial, tail: completionThenLive(loaded.snapshot.snapshotSequence), @@ -1020,6 +1089,20 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ), { "rpc.aggregate": "orchestration" }, ), + [ORCHESTRATION_V2_WS_METHODS.searchThreads]: (input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.searchThreads, + projectionSnapshotQuery.searchThreads(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationSearchThreadsError({ + message: "Failed to search threads", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => observeRpcEffect( ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, @@ -1099,10 +1182,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => subscribeOrchestrationV2ArchivedShell(), { "rpc.aggregate": "orchestration" }, ), - [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) => + [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) => observeRpcStreamEffect( ORCHESTRATION_V2_WS_METHODS.subscribeShell, - subscribeOrchestrationV2Shell(), + subscribeOrchestrationV2Shell(input), { "rpc.aggregate": "orchestrationV2", }, @@ -1143,6 +1226,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => "rpc.aggregate": "scheduledTasks", "scheduled_task.id": input.id, }), + [WS_METHODS.serverProbe]: (_input) => + observeRpcEffect(WS_METHODS.serverProbe, Effect.succeed({}), { + "rpc.aggregate": "server", + }), [WS_METHODS.serverGetConfig]: (_input) => observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { "rpc.aggregate": "server", diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index bee0a686d9..35187faeab 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -14,6 +14,9 @@ import { resolveBranchToolbarValue, resolveLockedWorkspaceLabel, resolveWorkspaceDisplayName, + resolveLocalCheckoutBranchMismatch, + resolvePreviousWorktreeLabel, + resolvePreviousWorktreeSeed, shouldIncludeBranchPickerItem, shouldShowComposerContextStrip, shouldShowEnvironmentIndicator, diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index c41e59aadb..d22df2ba68 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -81,6 +81,53 @@ export function resolveWorkspaceDisplayName(path: string | null): string | null return normalizedPath.split(/[\\/]/).at(-1) ?? normalizedPath; } +export interface PreviousWorktreeSeed { + branch: string | null; + worktreePath: string; +} + +// The most recently touched worktree in the project that the composer isn't +// already pointing at. Backs the "Previous worktree" entry in the workspace +// selector so a follow-up thread can hop back into the worktree you just +// worked in without hunting for its branch. Archived threads don't compete — +// the rest of the UI hides them, so their worktrees shouldn't resurface here. +export function resolvePreviousWorktreeSeed(input: { + threads: ReadonlyArray<{ + branch: string | null; + worktreePath: string | null; + updatedAt: string; + archivedAt?: string | null; + }>; + currentWorktreePath: string | null; +}): PreviousWorktreeSeed | null { + let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null; + for (const thread of input.threads) { + if ( + !thread.worktreePath || + thread.worktreePath === input.currentWorktreePath || + (thread.archivedAt ?? null) !== null + ) { + continue; + } + const updatedAt = toSortableTimestamp(thread.updatedAt); + if (updatedAt === null) { + continue; + } + if (latest === null || updatedAt > latest.updatedAt) { + latest = { + branch: thread.branch, + worktreePath: thread.worktreePath, + updatedAt, + }; + } + } + return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath }; +} + +export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string { + return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree"; +} + export function resolveEffectiveEnvMode(input: { activeWorktreePath: string | null; hasServerThread: boolean; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 6976408406..dc302d3c88 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -12,7 +12,7 @@ import { import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; -import { useProject, useThreadShell } from "../state/entities"; +import { useProject, useThreadShell, useThreadShellsForProjectRefs } from "../state/entities"; import { useIsMobile } from "../hooks/useMediaQuery"; import { type EnvMode, @@ -336,7 +336,6 @@ export const BranchToolbar = memo(function BranchToolbar({ const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); - const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const activeProjectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) @@ -415,6 +414,8 @@ export const BranchToolbar = memo(function BranchToolbar({ activeWorktreePath={activeWorktreePath} workspaceRoot={activeProject.workspaceRoot} onEnvModeChange={onEnvModeChange} + previousWorktreeLabel={previousWorktreeLabel} + onUsePreviousWorktree={onUsePreviousWorktree} /> ) : null} {panelSection !== "workspace" ? ( @@ -439,12 +440,20 @@ export const BranchToolbar = memo(function BranchToolbar({ } return ( +<<<<<<< HEAD
+<<<<<<< HEAD {isMobile && showGitControls ? ( +======= +======= +
+>>>>>>> 2152c2ebce (fix: reconcile rebase with latest main) + {isMobile ? ( +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) {branchPrTooltip} ) : null} - } - className={cn( - "min-w-0 text-muted-foreground/70 hover:text-foreground/80", - displayMode === "panel" && THREAD_DETAILS_PANEL_ROW_CLASS, - )} - disabled={isInitialBranchesLoadPending || isBranchActionPending} + handleBranchContextMenu(event, resolvedActiveBranch)} > - } className={cn( - "size-3 shrink-0 opacity-70", - displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS, - )} - /> - - {triggerLabel} - - - + + + {triggerLabel} + + + + {displayMode === "panel" && branchPr && branchPrStatus ? ( void; displayMode?: "toolbar" | "panel"; + previousWorktreeLabel?: string | null; + onUsePreviousWorktree?: () => void; } export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({ @@ -44,10 +46,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe workspaceRoot = null, onEnvModeChange, displayMode = "toolbar", + previousWorktreeLabel, + onUsePreviousWorktree, }: BranchToolbarEnvModeSelectorProps) { const workspacePath = displayMode === "panel" ? (activeWorktreePath ?? workspaceRoot) : null; const workspaceDisplayName = resolveWorkspaceDisplayName(workspacePath); const workspaceKind = activeWorktreePath ? "Worktree" : "Project folder"; + const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree); const envModeItems = useMemo( () => [ { @@ -59,14 +64,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe ? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }] : []), ], - [activeWorktreePath, workspaceDisplayName], + [activeWorktreePath, previousWorktreeLabel, showPreviousWorktree, workspaceDisplayName], ); if (envLocked) { const lockedRow = ( diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx index 4aa5d29307..30b04345fc 100644 --- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -24,7 +24,7 @@ interface BranchToolbarEnvironmentSelectorProps { envLocked: boolean; environmentId: EnvironmentId; availableEnvironments: readonly EnvironmentOption[]; - onEnvironmentChange: (environmentId: EnvironmentId) => void; + onEnvironmentChange?: (environmentId: EnvironmentId) => void; displayMode?: "toolbar" | "panel"; } @@ -52,17 +52,21 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir return ( {activeEnvironment?.isPrimary ? ( ) : ( )} {activeEnvironment?.isPrimary ? ( ) : ( )} ({ - useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }), - useGitStatuses: () => new Map(), - refreshGitStatus: () => Promise.resolve(null), - resetGitStatusStateForTests: () => undefined, -})); - -const THREAD_ID = "thread-browser-test" as ThreadId; -const THREAD_TITLE = "Browser test thread"; -const ARCHIVED_SECONDARY_THREAD_ID = "thread-secondary-project-archived" as ThreadId; -const PROJECT_ID = "project-1" as ProjectId; -const SECOND_PROJECT_ID = "project-2" as ProjectId; -const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); -const REMOTE_ENVIRONMENT_ID = EnvironmentId.make("environment-remote"); -const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID); -const THREAD_KEY = scopedThreadKey(THREAD_REF); -const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; -const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`; -const PROJECT_LOGICAL_KEY = deriveLogicalProjectKeyFromSettings( - { - environmentId: LOCAL_ENVIRONMENT_ID, - id: PROJECT_ID, - cwd: "/repo/project", - repositoryIdentity: null, - }, - { - sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode, - sidebarProjectGroupingOverrides: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingOverrides, - }, -); -const NOW_ISO = "2026-03-04T12:00:00.000Z"; -const BASE_TIME_MS = Date.parse(NOW_ISO); -const ATTACHMENT_SVG = ""; -const ADD_PROJECT_SUBMENU_PLACEHOLDER = "Enter path (e.g. ~/projects/my-app)"; - -interface TestFixture { - snapshot: OrchestrationReadModel; - serverConfig: ServerConfig; - welcome: ServerLifecycleWelcomePayload; -} - -let fixture: TestFixture; -const rpcHarness = new BrowserWsRpcHarness(); -const wsRequests = rpcHarness.requests; -let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null; -const wsLink = ws.link(/ws(s)?:\/\/.*/); - -interface ViewportSpec { - name: string; - width: number; - height: number; - textTolerancePx: number; - attachmentTolerancePx: number; -} - -const DEFAULT_VIEWPORT: ViewportSpec = { - name: "desktop", - width: 960, - height: 1_100, - textTolerancePx: 44, - attachmentTolerancePx: 56, -}; -const WIDE_FOOTER_VIEWPORT: ViewportSpec = { - name: "wide-footer", - width: 1_400, - height: 1_100, - textTolerancePx: 44, - attachmentTolerancePx: 56, -}; -const COMPACT_FOOTER_VIEWPORT: ViewportSpec = { - name: "compact-footer", - width: 430, - height: 932, - textTolerancePx: 56, - attachmentTolerancePx: 56, -}; - -interface MountedChatView { - [Symbol.asyncDispose]: () => Promise; - cleanup: () => Promise; - setViewport: (viewport: ViewportSpec) => Promise; - setContainerSize: (viewport: Pick) => Promise; - router: ReturnType; -} - -function isoAt(offsetSeconds: number): string { - return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString(); -} - -function createBaseServerConfig(): ServerConfig { - return { - environment: { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }, - auth: { - policy: "loopback-browser", - bootstrapMethods: ["one-time-token"], - sessionMethods: ["browser-session-cookie", "bearer-session-token"], - sessionCookieName: "t3_session", - }, - cwd: "/repo/project", - keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", - keybindings: [], - issues: [], - providers: [ - { - provider: "codex", - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: NOW_ISO, - models: [], - slashCommands: [], - skills: [], - }, - ], - availableEditors: [], - observability: { - logsDirectoryPath: "/repo/project/.t3/logs", - localTracingEnabled: true, - otlpTracesEnabled: false, - otlpMetricsEnabled: false, - }, - settings: { - ...DEFAULT_SERVER_SETTINGS, - ...DEFAULT_CLIENT_SETTINGS, - }, - }; -} - -function createMockEnvironmentApi(input: { - browse: EnvironmentApi["filesystem"]["browse"]; - dispatchCommand: EnvironmentApi["orchestration"]["dispatchCommand"]; -}): EnvironmentApi { - return { - terminal: {} as EnvironmentApi["terminal"], - projects: {} as EnvironmentApi["projects"], - filesystem: { - browse: input.browse, - }, - git: {} as EnvironmentApi["git"], - orchestration: { - dispatchCommand: input.dispatchCommand, - getTurnDiff: (() => { - throw new Error("Not implemented in browser test."); - }) as EnvironmentApi["orchestration"]["getTurnDiff"], - getFullThreadDiff: (() => { - throw new Error("Not implemented in browser test."); - }) as EnvironmentApi["orchestration"]["getFullThreadDiff"], - subscribeShell: (() => () => undefined) as EnvironmentApi["orchestration"]["subscribeShell"], - subscribeThread: (() => () => - undefined) as EnvironmentApi["orchestration"]["subscribeThread"], - }, - orchestrationV2: { - dispatchCommand: (() => { - throw new Error("Not implemented in browser test."); - }) as EnvironmentApi["orchestrationV2"]["dispatchCommand"], - getThreadProjection: (() => { - throw new Error("Not implemented in browser test."); - }) as EnvironmentApi["orchestrationV2"]["getThreadProjection"], - subscribeShell: (() => () => - undefined) as EnvironmentApi["orchestrationV2"]["subscribeShell"], - subscribeThread: (() => () => - undefined) as EnvironmentApi["orchestrationV2"]["subscribeThread"], - }, - }; -} - -function createUserMessage(options: { - id: MessageId; - text: string; - offsetSeconds: number; - attachments?: Array<{ - type: "image"; - id: string; - name: string; - mimeType: string; - sizeBytes: number; - }>; -}) { - return { - id: options.id, - role: "user" as const, - text: options.text, - ...(options.attachments ? { attachments: options.attachments } : {}), - turnId: null, - streaming: false, - createdAt: isoAt(options.offsetSeconds), - updatedAt: isoAt(options.offsetSeconds + 1), - }; -} - -function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) { - return { - id: options.id, - role: "assistant" as const, - text: options.text, - turnId: null, - streaming: false, - createdAt: isoAt(options.offsetSeconds), - updatedAt: isoAt(options.offsetSeconds + 1), - }; -} - -function createTerminalContext(input: { - id: string; - terminalLabel: string; - lineStart: number; - lineEnd: number; - text: string; -}): TerminalContextDraft { - return { - id: input.id, - threadId: THREAD_ID, - terminalId: `terminal-${input.id}`, - terminalLabel: input.terminalLabel, - lineStart: input.lineStart, - lineEnd: input.lineEnd, - text: input.text, - createdAt: NOW_ISO, - }; -} - -function createSnapshotForTargetUser(options: { - targetMessageId: MessageId; - targetText: string; - targetAttachmentCount?: number; - sessionStatus?: OrchestrationSessionStatus; -}): OrchestrationReadModel { - const messages: Array = []; - - for (let index = 0; index < 22; index += 1) { - const isTarget = index === 3; - const userId = `msg-user-${index}` as MessageId; - const assistantId = `msg-assistant-${index}` as MessageId; - const attachments = - isTarget && (options.targetAttachmentCount ?? 0) > 0 - ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({ - type: "image" as const, - id: `attachment-${attachmentIndex + 1}`, - name: `attachment-${attachmentIndex + 1}.png`, - mimeType: "image/png", - sizeBytes: 128, - previewUrl: `/attachments/attachment-${attachmentIndex + 1}`, - })) - : undefined; - - messages.push( - createUserMessage({ - id: isTarget ? options.targetMessageId : userId, - text: isTarget ? options.targetText : `filler user message ${index}`, - offsetSeconds: messages.length * 3, - ...(attachments ? { attachments } : {}), - }), - ); - messages.push( - createAssistantMessage({ - id: assistantId, - text: `assistant filler ${index}`, - offsetSeconds: messages.length * 3, - }), - ); - } - - return { - snapshotSequence: 1, - projects: [ - { - id: PROJECT_ID, - title: "Project", - workspaceRoot: "/repo/project", - defaultModelSelection: { - provider: "codex", - model: "gpt-5", - }, - scripts: [], - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - deletedAt: null, - }, - ], - threads: [ - { - id: THREAD_ID, - projectId: PROJECT_ID, - title: THREAD_TITLE, - modelSelection: { - provider: "codex", - model: "gpt-5", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "main", - worktreePath: null, - latestTurn: null, - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - archivedAt: null, - deletedAt: null, - messages, - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: THREAD_ID, - status: options.sessionStatus ?? "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: NOW_ISO, - }, - }, - ], - updatedAt: NOW_ISO, - }; -} - -function buildFixture(snapshot: OrchestrationReadModel): TestFixture { - return { - snapshot, - serverConfig: createBaseServerConfig(), - welcome: { - environment: { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }, - cwd: "/repo/project", - projectName: "Project", - bootstrapProjectId: PROJECT_ID, - bootstrapThreadId: THREAD_ID, - }, - }; -} - -function addThreadToSnapshot( - snapshot: OrchestrationReadModel, - threadId: ThreadId, -): OrchestrationReadModel { - return { - ...snapshot, - snapshotSequence: snapshot.snapshotSequence + 1, - threads: [ - ...snapshot.threads, - { - id: threadId, - projectId: PROJECT_ID, - title: "New thread", - modelSelection: { - provider: "codex", - model: "gpt-5", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "main", - worktreePath: null, - latestTurn: null, - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - archivedAt: null, - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: NOW_ISO, - }, - }, - ], - }; -} - -function toShellThread(thread: OrchestrationReadModel["threads"][number]) { - return { - id: thread.id, - projectId: thread.projectId, - title: thread.title, - modelSelection: thread.modelSelection, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - branch: thread.branch, - worktreePath: thread.worktreePath, - latestTurn: thread.latestTurn, - createdAt: thread.createdAt, - updatedAt: thread.updatedAt, - archivedAt: thread.archivedAt, - session: thread.session, - latestUserMessageAt: - thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - }; -} - -function toShellSnapshot(snapshot: OrchestrationReadModel) { - return { - snapshotSequence: snapshot.snapshotSequence, - projects: snapshot.projects.map((project) => ({ - id: project.id, - title: project.title, - workspaceRoot: project.workspaceRoot, - repositoryIdentity: project.repositoryIdentity ?? null, - defaultModelSelection: project.defaultModelSelection, - scripts: project.scripts, - createdAt: project.createdAt, - updatedAt: project.updatedAt, - })), - threads: snapshot.threads.map(toShellThread), - updatedAt: snapshot.updatedAt, - }; -} - -function updateThreadSessionInSnapshot( - snapshot: OrchestrationReadModel, - threadId: ThreadId, - session: OrchestrationReadModel["threads"][number]["session"], -): OrchestrationReadModel { - return { - ...snapshot, - snapshotSequence: snapshot.snapshotSequence + 1, - threads: snapshot.threads.map((thread) => - thread.id === threadId - ? { - ...thread, - session, - updatedAt: NOW_ISO, - } - : thread, - ), - }; -} - -function sendShellThreadUpsert( - threadId: ThreadId, - options?: { - readonly session?: OrchestrationReadModel["threads"][number]["session"]; - }, -): void { - const thread = fixture.snapshot.threads.find((entry) => entry.id === threadId); - if (!thread) { - throw new Error(`Expected thread ${threadId} in snapshot.`); - } - - const shellThread = - options?.session !== undefined - ? toShellThread({ ...thread, session: options.session }) - : toShellThread(thread); - rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeShell, { - kind: "thread-upserted", - sequence: fixture.snapshot.snapshotSequence, - thread: shellThread, - }); -} - -async function waitForWsClient(): Promise { - await vi.waitFor( - () => { - expect( - wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.subscribeShell), - ).toBe(true); - expect( - wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle), - ).toBe(true); - expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( - true, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -function threadRefFor(threadId: ThreadId) { - return scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); -} - -function threadKeyFor(threadId: ThreadId): string { - return scopedThreadKey(threadRefFor(threadId)); -} - -function composerDraftFor(target: string) { - const { draftsByThreadKey } = useComposerDraftStore.getState(); - return draftsByThreadKey[target] ?? draftsByThreadKey[threadKeyFor(target as ThreadId)]; -} - -function draftIdFromPath(pathname: string) { - const segments = pathname.split("/"); - const draftId = segments[segments.length - 1]; - if (!draftId) { - throw new Error(`Expected thread path, received "${pathname}".`); - } - return DraftId.make(draftId); -} - -function draftThreadIdFor(draftId: ReturnType): ThreadId { - const draftSession = useComposerDraftStore.getState().getDraftSession(draftId); - if (!draftSession) { - throw new Error(`Expected draft session for "${draftId}".`); - } - return draftSession.threadId; -} - -function serverThreadPath(threadId: ThreadId): string { - return `/${LOCAL_ENVIRONMENT_ID}/${threadId}`; -} - -async function waitForAppBootstrap(): Promise { - await vi.waitFor( - () => { - expect(getServerConfig()).not.toBeNull(); - expect(selectBootstrapCompleteForActiveEnvironment(useStore.getState())).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function materializePromotedDraftThreadViaDomainEvent(threadId: ThreadId): Promise { - await waitForWsClient(); - fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); - fixture.snapshot = updateThreadSessionInSnapshot(fixture.snapshot, threadId, null); - sendShellThreadUpsert(threadId, { session: null }); -} - -async function startPromotedServerThreadViaDomainEvent(threadId: ThreadId): Promise { - fixture.snapshot = updateThreadSessionInSnapshot(fixture.snapshot, threadId, { - threadId, - status: "running", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: `turn-${threadId}` as TurnId, - lastError: null, - updatedAt: NOW_ISO, - }); - sendShellThreadUpsert(threadId); -} - -async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { - await materializePromotedDraftThreadViaDomainEvent(threadId); - await startPromotedServerThreadViaDomainEvent(threadId); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftThreadsByThreadKey[threadKeyFor(threadId)]).toBe( - undefined, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -function createDraftOnlySnapshot(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-target" as MessageId, - targetText: "draft thread", - }); - return { - ...snapshot, - threads: [], - }; -} - -function createProjectlessSnapshot(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-projectless-target" as MessageId, - targetText: "projectless", - }); - return { - ...snapshot, - projects: [], - threads: [], - }; -} - -function withProjectScripts( - snapshot: OrchestrationReadModel, - scripts: OrchestrationReadModel["projects"][number]["scripts"], -): OrchestrationReadModel { - return { - ...snapshot, - projects: snapshot.projects.map((project) => - project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project, - ), - }; -} - -function setDraftThreadWithoutWorktree(): void { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); -} - -function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-plan-target" as MessageId, - targetText: "plan thread", - }); - const planMarkdown = [ - "# Ship plan mode follow-up", - "", - "- Step 1: capture the thread-open trace", - "- Step 2: identify the main-thread bottleneck", - "- Step 3: keep collapsed cards cheap", - "- Step 4: render the full markdown only on demand", - "- Step 5: preserve export and save actions", - "- Step 6: add regression coverage", - "- Step 7: verify route transitions stay responsive", - "- Step 8: confirm no server-side work changed", - "- Step 9: confirm short plans still render normally", - "- Step 10: confirm long plans stay collapsed by default", - "- Step 11: confirm preview text is still useful", - "- Step 12: confirm plan follow-up flow still works", - "- Step 13: confirm timeline virtualization still behaves", - "- Step 14: confirm theme styling still looks correct", - "- Step 15: confirm save dialog behavior is unchanged", - "- Step 16: confirm download behavior is unchanged", - "- Step 17: confirm code fences do not parse until expand", - "- Step 18: confirm preview truncation ends cleanly", - "- Step 19: confirm markdown links still open in editor after expand", - "- Step 20: confirm deep hidden detail only appears after expand", - "", - "```ts", - "export const hiddenPlanImplementationDetail = 'deep hidden detail only after expand';", - "```", - ].join("\n"); - - return { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - proposedPlans: [ - { - id: "plan-browser-test", - turnId: null, - planMarkdown, - implementedAt: null, - implementationThreadId: null, - createdAt: isoAt(1_000), - updatedAt: isoAt(1_001), - }, - ], - updatedAt: isoAt(1_001), - }) - : thread, - ), - }; -} - -function createSnapshotWithSecondaryProject(options?: { - includeSecondaryThread?: boolean; - includeArchivedSecondaryThread?: boolean; -}): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-secondary-project-target" as MessageId, - targetText: "secondary project", - }); - const includeSecondaryThread = options?.includeSecondaryThread ?? true; - const includeArchivedSecondaryThread = options?.includeArchivedSecondaryThread ?? true; - const secondaryThreads: OrchestrationReadModel["threads"] = includeSecondaryThread - ? [ - { - id: "thread-secondary-project" as ThreadId, - projectId: SECOND_PROJECT_ID, - title: "Release checklist", - modelSelection: { provider: "codex", model: "gpt-5" }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "release/docs-portal", - worktreePath: null, - latestTurn: null, - createdAt: isoAt(30), - updatedAt: isoAt(31), - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: "thread-secondary-project" as ThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: isoAt(31), - }, - archivedAt: null, - }, - ] - : []; - const archivedSecondaryThreads: OrchestrationReadModel["threads"] = includeArchivedSecondaryThread - ? [ - { - id: ARCHIVED_SECONDARY_THREAD_ID, - projectId: SECOND_PROJECT_ID, - title: "Archived Docs Notes", - modelSelection: { provider: "codex", model: "gpt-5" }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "release/docs-archive", - worktreePath: null, - latestTurn: null, - createdAt: isoAt(24), - updatedAt: isoAt(25), - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: ARCHIVED_SECONDARY_THREAD_ID, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: isoAt(25), - }, - archivedAt: isoAt(26), - }, - ] - : []; - - return { - ...snapshot, - projects: [ - ...snapshot.projects, - { - id: SECOND_PROJECT_ID, - title: "Docs Portal", - workspaceRoot: "/repo/clients/docs-portal", - defaultModelSelection: { provider: "codex", model: "gpt-5" }, - scripts: [], - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - deletedAt: null, - }, - ], - threads: [...snapshot.threads, ...secondaryThreads, ...archivedSecondaryThreads], - }; -} - -function createSnapshotWithPendingUserInput(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-pending-input-target" as MessageId, - targetText: "question thread", - }); - - return { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - interactionMode: "plan", - activities: [ - { - id: EventId.make("activity-user-input-requested"), - tone: "info", - kind: "user-input.requested", - summary: "User input requested", - payload: { - requestId: "req-browser-user-input", - questions: [ - { - id: "scope", - header: "Scope", - question: "What should this change cover?", - options: [ - { - label: "Tight", - description: "Touch only the footer layout logic.", - }, - { - label: "Broad", - description: "Also adjust the related composer controls.", - }, - ], - }, - { - id: "risk", - header: "Risk", - question: "How aggressive should the imaginary plan be?", - options: [ - { - label: "Conservative", - description: "Favor reliability and low-risk changes.", - }, - { - label: "Balanced", - description: "Mix quick wins with one structural improvement.", - }, - ], - }, - ], - }, - turnId: null, - sequence: 1, - createdAt: isoAt(1_000), - }, - ], - updatedAt: isoAt(1_000), - }) - : thread, - ), - }; -} - -function createSnapshotWithPlanFollowUpPrompt(options?: { - modelSelection?: { provider: "codex"; model: string }; - planMarkdown?: string; -}): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-plan-follow-up-target" as MessageId, - targetText: "plan follow-up thread", - }); - const modelSelection = options?.modelSelection ?? { - provider: "codex" as const, - model: "gpt-5", - }; - const planMarkdown = - options?.planMarkdown ?? "# Follow-up plan\n\n- Keep the composer footer stable on resize."; - - return { - ...snapshot, - projects: snapshot.projects.map((project) => - project.id === PROJECT_ID ? { ...project, defaultModelSelection: modelSelection } : project, - ), - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - modelSelection, - interactionMode: "plan", - latestTurn: { - turnId: "turn-plan-follow-up" as TurnId, - state: "completed", - requestedAt: isoAt(1_000), - startedAt: isoAt(1_001), - completedAt: isoAt(1_010), - assistantMessageId: null, - }, - proposedPlans: [ - { - id: "plan-follow-up-browser-test", - turnId: "turn-plan-follow-up" as TurnId, - planMarkdown, - implementedAt: null, - implementationThreadId: null, - createdAt: isoAt(1_002), - updatedAt: isoAt(1_003), - }, - ], - session: { - ...thread.session, - status: "ready", - updatedAt: isoAt(1_010), - }, - updatedAt: isoAt(1_010), - }) - : thread, - ), - }; -} - -function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { - const customResult = customWsRpcResolver?.(body); - if (customResult !== undefined) { - return customResult; - } - const tag = body._tag; - if (tag === WS_METHODS.serverGetConfig) { - return fixture.serverConfig; - } - if (tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: 1, - branches: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - }; - } - if (tag === WS_METHODS.projectsSearchEntries) { - return { - entries: [], - truncated: false, - }; - } - if (tag === WS_METHODS.shellOpenInEditor) { - return null; - } - if (tag === WS_METHODS.terminalOpen) { - return { - threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID, - terminalId: typeof body.terminalId === "string" ? body.terminalId : "default", - cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project", - worktreePath: - typeof body.worktreePath === "string" - ? body.worktreePath - : body.worktreePath === null - ? null - : null, - status: "running", - pid: 123, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: NOW_ISO, - }; - } - return {}; -} - -const worker = setupWorker( - wsLink.addEventListener("connection", ({ client }) => { - void rpcHarness.connect(client); - client.addEventListener("message", (event) => { - const rawData = event.data; - if (typeof rawData !== "string") return; - void rpcHarness.onMessage(rawData); - }); - }), - ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth), - http.get("*/attachments/:attachmentId", () => - HttpResponse.text(ATTACHMENT_SVG, { - headers: { - "Content-Type": "image/svg+xml", - }, - }), - ), - http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })), -); - -async function nextFrame(): Promise { - await new Promise((resolve) => { - window.requestAnimationFrame(() => resolve()); - }); -} - -async function waitForLayout(): Promise { - await nextFrame(); - await nextFrame(); - await nextFrame(); -} - -async function setViewport(viewport: ViewportSpec): Promise { - await page.viewport(viewport.width, viewport.height); - await waitForLayout(); -} - -async function waitForProductionStyles(): Promise { - await vi.waitFor( - () => { - expect( - getComputedStyle(document.documentElement).getPropertyValue("--background").trim(), - ).not.toBe(""); - expect(getComputedStyle(document.body).marginTop).toBe("0px"); - }, - { - timeout: 4_000, - interval: 16, - }, - ); -} - -async function waitForElement( - query: () => T | null, - errorMessage: string, -): Promise { - let element: T | null = null; - await vi.waitFor( - () => { - element = query(); - expect(element, errorMessage).toBeTruthy(); - }, - { - timeout: 8_000, - interval: 16, - }, - ); - if (!element) { - throw new Error(errorMessage); - } - return element; -} - -async function waitForURL( - router: ReturnType, - predicate: (pathname: string) => boolean, - errorMessage: string, -): Promise { - let pathname = ""; - await vi.waitFor( - () => { - pathname = router.state.location.pathname; - expect(predicate(pathname), errorMessage).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - return pathname; -} - -async function waitForComposerEditor(): Promise { - return waitForElement( - () => document.querySelector('[contenteditable="true"]'), - "Unable to find composer editor.", - ); -} - -async function pressComposerKey(key: string): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const keydownEvent = new KeyboardEvent("keydown", { - key, - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(keydownEvent); - if (keydownEvent.defaultPrevented) { - await waitForLayout(); - return; - } - - const beforeInputEvent = new InputEvent("beforeinput", { - data: key, - inputType: "insertText", - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(beforeInputEvent); - if (beforeInputEvent.defaultPrevented) { - await waitForLayout(); - return; - } - - if ( - typeof document.execCommand === "function" && - document.execCommand("insertText", false, key) - ) { - await waitForLayout(); - return; - } - - const selection = window.getSelection(); - if (!selection || selection.rangeCount === 0) { - throw new Error("Unable to resolve composer selection for text input."); - } - const range = selection.getRangeAt(0); - range.deleteContents(); - const textNode = document.createTextNode(key); - range.insertNode(textNode); - range.setStartAfter(textNode); - range.collapse(true); - selection.removeAllRanges(); - selection.addRange(range); - composerEditor.dispatchEvent( - new InputEvent("input", { - data: key, - inputType: "insertText", - bubbles: true, - }), - ); - await waitForLayout(); -} - -async function pressComposerUndo(): Promise { - const composerEditor = await waitForComposerEditor(); - const useMetaForMod = isMacPlatform(navigator.platform); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "z", - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); -} - -async function waitForComposerText(expectedText: string): Promise { - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe( - expectedText, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function setComposerSelectionByTextOffsets(options: { - start: number; - end: number; - direction?: "forward" | "backward"; -}): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const resolvePoint = (targetOffset: number) => { - const traversedRef = { value: 0 }; - - const visitNode = (node: Node): { node: Node; offset: number } | null => { - if (node.nodeType === Node.TEXT_NODE) { - const textLength = node.textContent?.length ?? 0; - if (targetOffset <= traversedRef.value + textLength) { - return { - node, - offset: Math.max(0, Math.min(targetOffset - traversedRef.value, textLength)), - }; - } - traversedRef.value += textLength; - return null; - } - - if (node instanceof HTMLBRElement) { - const parent = node.parentNode; - if (!parent) { - return null; - } - const siblingIndex = Array.prototype.indexOf.call(parent.childNodes, node); - if (targetOffset <= traversedRef.value) { - return { node: parent, offset: siblingIndex }; - } - if (targetOffset <= traversedRef.value + 1) { - return { node: parent, offset: siblingIndex + 1 }; - } - traversedRef.value += 1; - return null; - } - - if (node instanceof Element || node instanceof DocumentFragment) { - for (const child of node.childNodes) { - const point = visitNode(child); - if (point) { - return point; - } - } - } - - return null; - }; - - return ( - visitNode(composerEditor) ?? { - node: composerEditor, - offset: composerEditor.childNodes.length, - } - ); - }; - - const startPoint = resolvePoint(options.start); - const endPoint = resolvePoint(options.end); - const selection = window.getSelection(); - if (!selection) { - throw new Error("Unable to resolve window selection."); - } - selection.removeAllRanges(); - - if (options.direction === "backward" && "setBaseAndExtent" in selection) { - selection.setBaseAndExtent(endPoint.node, endPoint.offset, startPoint.node, startPoint.offset); - await waitForLayout(); - return; - } - - const range = document.createRange(); - range.setStart(startPoint.node, startPoint.offset); - range.setEnd(endPoint.node, endPoint.offset); - selection.addRange(range); - await waitForLayout(); -} - -async function selectAllComposerContent(): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const selection = window.getSelection(); - if (!selection) { - throw new Error("Unable to resolve window selection."); - } - selection.removeAllRanges(); - const range = document.createRange(); - range.selectNodeContents(composerEditor); - selection.addRange(range); - await waitForLayout(); -} - -async function waitForComposerMenuItem(itemId: string): Promise { - return waitForElement( - () => document.querySelector(`[data-composer-item-id="${itemId}"]`), - `Unable to find composer menu item "${itemId}".`, - ); -} -async function waitForSendButton(): Promise { - return waitForElement( - () => document.querySelector('button[aria-label="Send message"]'), - "Unable to find send button.", - ); -} - -function findComposerProviderModelPicker(): HTMLButtonElement | null { - return document.querySelector('[data-chat-provider-model-picker="true"]'); -} - -function findButtonByText(text: string): HTMLButtonElement | null { - return (Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === text, - ) ?? null) as HTMLButtonElement | null; -} - -async function waitForButtonByText(text: string): Promise { - return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); -} - -function findButtonContainingText(text: string): HTMLButtonElement | null { - return (Array.from(document.querySelectorAll("button")).find((button) => - button.textContent?.includes(text), - ) ?? null) as HTMLButtonElement | null; -} - -async function waitForButtonContainingText(text: string): Promise { - return waitForElement( - () => findButtonContainingText(text), - `Unable to find button containing "${text}".`, - ); -} - -async function waitForSelectItemContainingText(text: string): Promise { - return waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="select-item"]')).find((item) => - item.textContent?.includes(text), - ) ?? null, - `Unable to find select item containing "${text}".`, - ); -} - -async function expectComposerActionsContained(): Promise { - const footer = await waitForElement( - () => document.querySelector('[data-chat-composer-footer="true"]'), - "Unable to find composer footer.", - ); - const actions = await waitForElement( - () => document.querySelector('[data-chat-composer-actions="right"]'), - "Unable to find composer actions container.", - ); - - await vi.waitFor( - () => { - const footerRect = footer.getBoundingClientRect(); - const actionButtons = Array.from(actions.querySelectorAll("button")); - expect(actionButtons.length).toBeGreaterThanOrEqual(1); - - const buttonRects = actionButtons.map((button) => button.getBoundingClientRect()); - const firstTop = buttonRects[0]?.top ?? 0; - - for (const rect of buttonRects) { - expect(rect.right).toBeLessThanOrEqual(footerRect.right + 0.5); - expect(rect.bottom).toBeLessThanOrEqual(footerRect.bottom + 0.5); - expect(Math.abs(rect.top - firstTop)).toBeLessThanOrEqual(1.5); - } - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function waitForInteractionModeButton( - expectedLabel: "Build" | "Plan", -): Promise { - return waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === expectedLabel, - ) as HTMLButtonElement | null, - `Unable to find ${expectedLabel} interaction mode button.`, - ); -} - -async function waitForServerConfigToApply(): Promise { - await vi.waitFor( - () => { - expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( - true, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - await waitForLayout(); -} - -function dispatchChatNewShortcut(): void { - const useMetaForMod = isMacPlatform(navigator.platform); - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "o", - shiftKey: true, - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); -} - -async function triggerChatNewShortcutUntilPath( - router: ReturnType, - predicate: (pathname: string) => boolean, - errorMessage: string, -): Promise { - let pathname = router.state.location.pathname; - const deadline = Date.now() + 8_000; - while (Date.now() < deadline) { - dispatchChatNewShortcut(); - await waitForLayout(); - pathname = router.state.location.pathname; - if (predicate(pathname)) { - return pathname; - } - } - throw new Error(`${errorMessage} Last path: ${pathname}`); -} - -async function openCommandPaletteFromTrigger(): Promise { - const trigger = page.getByTestId("command-palette-trigger"); - await expect.element(trigger).toBeInTheDocument(); - await trigger.click(); - await waitForElement( - () => document.querySelector('[data-testid="command-palette"]'), - "Command palette should have opened from the sidebar trigger.", - ); -} - -async function waitForNewThreadShortcutLabel(): Promise { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - await newThreadButton.hover(); - const shortcutLabel = isMacPlatform(navigator.platform) - ? "New thread (⇧⌘O)" - : "New thread (Ctrl+Shift+O)"; - await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument(); -} - -async function waitForCommandPaletteShortcutLabel(): Promise { - await waitForElement( - () => document.querySelector('[data-testid="command-palette-trigger"] kbd'), - "Command palette shortcut label did not render.", - ); -} - -async function waitForCommandPaletteInput(placeholder: string): Promise { - return waitForElement( - () => document.querySelector(`input[placeholder="${placeholder}"]`) as HTMLInputElement | null, - `Command palette input with placeholder "${placeholder}" did not render.`, - ); -} - -function getCommandPaletteLegendEntries(): string[] { - const footer = document.querySelector('[data-slot="command-footer"]'); - if (!footer) { - return []; - } - - return Array.from(footer.querySelectorAll('[data-slot="kbd-group"]')) - .map((group) => - Array.from(group.children) - .map((child) => child.textContent?.trim() ?? "") - .filter((value) => value.length > 0) - .join(" "), - ) - .filter((value) => value.length > 0); -} - -async function dispatchInputKey( - input: HTMLInputElement, - init: Pick, -): Promise { - input.focus(); - input.dispatchEvent( - new KeyboardEvent("keydown", { - bubbles: true, - cancelable: true, - ...init, - }), - ); - await waitForLayout(); -} - -async function mountChatView(options: { - viewport: ViewportSpec; - snapshot: OrchestrationReadModel; - configureFixture?: (fixture: TestFixture) => void; - resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined; - initialPath?: string; -}): Promise { - fixture = buildFixture(options.snapshot); - options.configureFixture?.(fixture); - customWsRpcResolver = options.resolveRpc ?? null; - await setViewport(options.viewport); - await waitForProductionStyles(); - - const host = document.createElement("div"); - host.style.position = "fixed"; - host.style.top = "0"; - host.style.left = "0"; - host.style.width = "100vw"; - host.style.height = "100vh"; - host.style.display = "grid"; - host.style.overflow = "hidden"; - document.body.append(host); - - const router = getRouter( - createMemoryHistory({ - initialEntries: [options.initialPath ?? `/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`], - }), - ); - - const screen = await render( - - - , - { - container: host, - }, - ); - - await waitForWsClient(); - await waitForAppBootstrap(); - await waitForLayout(); - - const cleanup = async () => { - customWsRpcResolver = null; - await screen.unmount(); - host.remove(); - await waitForLayout(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - setViewport: async (viewport: ViewportSpec) => { - await setViewport(viewport); - await waitForProductionStyles(); - }, - setContainerSize: async (viewport) => { - host.style.width = `${viewport.width}px`; - host.style.height = `${viewport.height}px`; - await waitForLayout(); - }, - router, - }; -} - -describe("ChatView timeline estimator parity (full app)", () => { - beforeAll(async () => { - fixture = buildFixture( - createSnapshotForTargetUser({ - targetMessageId: "msg-user-bootstrap" as MessageId, - targetText: "bootstrap", - }), - ); - await worker.start({ - onUnhandledRequest: "bypass", - quiet: true, - serviceWorker: { - url: "/mockServiceWorker.js", - }, - }); - }); - - afterAll(async () => { - await rpcHarness.disconnect(); - await worker.stop(); - }); - - beforeEach(async () => { - await rpcHarness.reset({ - resolveUnary: resolveWsRpc, - getInitialStreamValues: (request) => { - if (request._tag === WS_METHODS.subscribeServerLifecycle) { - return [ - { - version: 1, - sequence: 1, - type: "welcome", - payload: fixture.welcome, - }, - ]; - } - if (request._tag === WS_METHODS.subscribeServerConfig) { - return [ - { - version: 1, - type: "snapshot", - config: fixture.serverConfig, - }, - ]; - } - if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) { - return [ - { - kind: "snapshot", - snapshot: toShellSnapshot(fixture.snapshot), - }, - ]; - } - if (request._tag === ORCHESTRATION_WS_METHODS.subscribeThread) { - const thread = fixture.snapshot.threads.find((entry) => entry.id === request.threadId); - return thread - ? [ - { - kind: "snapshot", - snapshot: { - snapshotSequence: fixture.snapshot.snapshotSequence, - thread, - }, - }, - ] - : []; - } - return []; - }, - }); - await __resetLocalApiForTests(); - await setViewport(DEFAULT_VIEWPORT); - localStorage.clear(); - document.body.innerHTML = ""; - wsRequests.length = 0; - customWsRpcResolver = null; - __resetEnvironmentApiOverridesForTests(); - resetSavedEnvironmentRegistryStoreForTests(); - resetSavedEnvironmentRuntimeStoreForTests(); - Reflect.deleteProperty(window, "desktopBridge"); - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - stickyActiveProvider: null, - }); - useCommandPaletteStore.setState({ - open: false, - openIntent: null, - }); - useStore.setState({ - activeEnvironmentId: null, - environmentStateById: {}, - }); - useUiStateStore.setState({ - projectExpandedById: {}, - projectOrder: [], - threadLastVisitedAtById: {}, - }); - useTerminalStateStore.persist.clearStorage(); - useTerminalStateStore.setState({ - terminalStateByThreadKey: {}, - terminalLaunchContextByThreadKey: {}, - terminalEventEntriesByKey: {}, - nextTerminalEventId: 1, - }); - }); - - afterEach(() => { - customWsRpcResolver = null; - document.body.innerHTML = ""; - }); - it("re-expands the bootstrap project using its logical key", async () => { - useUiStateStore.setState({ - projectExpandedById: { - [PROJECT_LOGICAL_KEY]: false, - }, - projectOrder: [PROJECT_LOGICAL_KEY], - threadLastVisitedAtById: {}, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-bootstrap-project-expand" as MessageId, - targetText: "bootstrap project expand", - }), - }); - - try { - await vi.waitFor( - () => { - expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows an explicit empty state for projects without threads in the sidebar", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - }); - - try { - await expect.element(page.getByText("No threads yet")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd for draft threads without a worktree path", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-launch-context-target" as MessageId, - targetText: "launch context worktree override", - }); - const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID); - if (targetThread) { - Object.assign(targetThread, { - branch: "feature/branch", - worktreePath: "/repo/worktrees/feature-branch", - }); - } - - useTerminalStateStore.setState({ - terminalStateByThreadKey: { - [THREAD_KEY]: { - terminalOpen: true, - terminalHeight: 280, - terminalIds: ["default"], - runningTerminalIds: [], - activeTerminalId: "default", - terminalGroups: [{ id: "group-default", terminalIds: ["default"] }], - activeTerminalGroupId: "group-default", - }, - }, - terminalLaunchContextByThreadKey: { - [THREAD_KEY]: { - cwd: "/repo/project", - worktreePath: null, - }, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot, - }); - - try { - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalOpen, - ) as - | { - _tag: string; - cwd?: string; - worktreePath?: string | null; - env?: Record; - } - | undefined; - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.terminalOpen, - cwd: "/repo/project", - worktreePath: null, - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - }, - }); - expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode-insiders", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd with Trae when it is the only available editor", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["trae"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "trae", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows Kiro in the open picker menu and opens the project cwd with it", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["kiro"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const menuButton = await waitForElement( - () => document.querySelector('button[aria-label="Copy options"]'), - "Unable to find Open picker button.", - ); - (menuButton as HTMLButtonElement).click(); - - const kiroItem = await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("Kiro"), - ) ?? null, - "Unable to find Kiro menu item.", - ); - (kiroItem as HTMLElement).click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "kiro", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("filters the open picker menu and opens VSCodium from the menu", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders", "vscodium"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const menuButton = await waitForElement( - () => document.querySelector('button[aria-label="Copy options"]'), - "Unable to find Open picker button.", - ); - (menuButton as HTMLButtonElement).click(); - - await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("VS Code Insiders"), - ) ?? null, - "Unable to find VS Code Insiders menu item.", - ); - - expect( - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) => - item.textContent?.includes("Zed"), - ), - ).toBe(false); - - const vscodiumItem = await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("VSCodium"), - ) ?? null, - "Unable to find VSCodium menu item.", - ); - (vscodiumItem as HTMLElement).click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscodium", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to the first installed editor when the stored favorite is unavailable", async () => { - localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium")); - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode-insiders", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("runs project scripts from local draft threads at the project cwd", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "lint", - name: "Lint", - command: "bun run lint", - icon: "lint", - runOnWorktreeCreate: false, - }, - ]), - }); - - try { - const runButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.title === "Run Lint", - ) as HTMLButtonElement | null, - "Unable to find Run Lint button.", - ); - runButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalOpen, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.terminalOpen, - threadId: THREAD_ID, - cwd: "/repo/project", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const writeRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalWrite, - ); - expect(writeRequest).toMatchObject({ - _tag: WS_METHODS.terminalWrite, - threadId: THREAD_ID, - data: "bun run lint\r", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("runs project scripts from worktree draft threads at the worktree cwd", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "feature/draft", - worktreePath: "/repo/worktrees/feature-draft", - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "test", - name: "Test", - command: "bun run test", - icon: "test", - runOnWorktreeCreate: false, - }, - ]), - }); - - try { - const runButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.title === "Run Test", - ) as HTMLButtonElement | null, - "Unable to find Run Test button.", - ); - runButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalOpen, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.terminalOpen, - threadId: THREAD_ID, - cwd: "/repo/worktrees/feature-draft", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft", - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("lets the server own setup after preparing a pull request worktree thread", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitResolvePullRequest) { - return { - pullRequest: { - number: 1359, - title: "Add thread archiving and settings navigation", - url: "https://github.com/pingdotgg/t3code/pull/1359", - baseBranch: "main", - headBranch: "archive-settings-overhaul", - state: "open", - }, - }; - } - if (body._tag === WS_METHODS.gitPreparePullRequestThread) { - return { - pullRequest: { - number: 1359, - title: "Add thread archiving and settings navigation", - url: "https://github.com/pingdotgg/t3code/pull/1359", - baseBranch: "main", - headBranch: "archive-settings-overhaul", - state: "open", - }, - branch: "archive-settings-overhaul", - worktreePath: "/repo/worktrees/pr-1359", - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "main", - ) as HTMLButtonElement | null, - "Unable to find branch selector button.", - ); - branchButton.click(); - - const branchInput = await waitForElement( - () => document.querySelector('input[placeholder="Search branches..."]'), - "Unable to find branch search input.", - ); - branchInput.focus(); - await page.getByPlaceholder("Search branches...").fill("1359"); - - const checkoutItem = await waitForElement( - () => - Array.from(document.querySelectorAll("span")).find( - (element) => element.textContent?.trim() === "Checkout Pull Request", - ) as HTMLSpanElement | null, - "Unable to find checkout pull request option.", - ); - checkoutItem.click(); - - const worktreeButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Worktree", - ) as HTMLButtonElement | null, - "Unable to find Worktree button.", - ); - worktreeButton.click(); - - await vi.waitFor( - () => { - const prepareRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.gitPreparePullRequestThread, - ); - expect(prepareRequest).toMatchObject({ - _tag: WS_METHODS.gitPreparePullRequestThread, - cwd: "/repo/project", - reference: "1359", - mode: "worktree", - threadId: THREAD_ID, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", - ), - ).toBe(false); - } finally { - await mounted.cleanup(); - } - }); - - it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => { - useTerminalStateStore.setState({ - terminalStateByThreadKey: {}, - }); - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand, - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - createThread?: { projectId?: string }; - prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; - runSetupScript?: boolean; - }; - } - | undefined; - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.turn.start", - bootstrap: { - createThread: { - projectId: PROJECT_ID, - }, - prepareWorktree: { - projectCwd: "/repo/project", - baseBranch: "main", - branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), - }, - runSetupScript: true, - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe( - false, - ); - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalWrite && - request.threadId === THREAD_ID && - request.data === "bun install\r", - ), - ).toBe(false); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => { - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, - ), - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: 1, - branches: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("New worktree")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const turnStartRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.turn.start", - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - createThread?: { projectId?: string }; - prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; - runSetupScript?: boolean; - }; - } - | undefined; - - expect(turnStartRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.turn.start", - bootstrap: { - prepareWorktree: { - projectCwd: "/repo/project", - baseBranch: "main", - branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), - }, - runSetupScript: true, - }, - }); - expect(turnStartRequest?.bootstrap?.createThread).toBeUndefined(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("updates the selected worktree base branch on empty server threads", async () => { - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, - ), - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: 2, - branches: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - await page.getByText("From main", { exact: true }).click(); - await page.getByText("release/next", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From release/next")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const turnStartRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.turn.start", - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - prepareWorktree?: { baseBranch?: string }; - }; - } - | undefined; - - expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("release/next"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("clears pending worktree overrides when switching empty server threads", async () => { - const secondThreadId = "thread-browser-test-second" as ThreadId; - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const snapshotWithSecondThread = addThreadToSnapshot(snapshot, secondThreadId); - const snapshotWithTwoThreads = { - ...snapshotWithSecondThread, - threads: snapshotWithSecondThread.threads.map((thread) => { - if (thread.id === THREAD_ID) { - return Object.assign({}, thread, { session: null, title: "Thread alpha" }); - } - if (thread.id === secondThreadId) { - return Object.assign({}, thread, { session: null, title: "Thread beta" }); - } - return thread; - }), - }; - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: snapshotWithTwoThreads, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: 2, - branches: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - await page.getByText("From main", { exact: true }).click(); - await page.getByText("release/next", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From release/next")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - await mounted.router.navigate({ - to: "/$environmentId/$threadId", - params: { - environmentId: LOCAL_ENVIRONMENT_ID, - threadId: secondThreadId, - }, - }); - - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(secondThreadId), - "Route should switch to the second empty server thread.", - ); - - await vi.waitFor( - () => { - expect(findButtonByText("Current checkout")).toBeTruthy(); - expect(findButtonByText("From release/next")).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From main")).toBeTruthy(); - expect(findButtonByText("From release/next")).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows the send state once bootstrap dispatch is in flight", async () => { - useTerminalStateStore.setState({ - terminalStateByThreadKey: {}, - }); - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - let resolveDispatch!: (value: { sequence: number }) => void; - const dispatchPromise = new Promise<{ sequence: number }>((resolve) => { - resolveDispatch = resolve; - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return dispatchPromise; - } - return undefined; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - expect( - wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand), - ).toBe(true); - expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy(); - expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 }); - await mounted.cleanup(); - } - }); - - it("toggles plan mode with Shift+Tab only while the composer is focused", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-target-hotkey" as MessageId, - targetText: "hotkey target", - }), - }); - - try { - const initialModeButton = await waitForInteractionModeButton("Build"); - expect(initialModeButton.title).toContain("enter plan mode"); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); - - expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode"); - - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor( - async () => { - expect((await waitForInteractionModeButton("Plan")).title).toContain( - "return to normal build mode", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor( - async () => { - expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("uses the active draft route session when changing the base branch", async () => { - const staleDraftId = draftIdFromPath("/draft/draft-stale-branch-session"); - const activeDraftId = draftIdFromPath("/draft/draft-active-branch-session"); - - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [staleDraftId]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: `${PROJECT_DRAFT_KEY}:stale`, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - [activeDraftId]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [`${PROJECT_DRAFT_KEY}:stale`]: staleDraftId, - [PROJECT_DRAFT_KEY]: activeDraftId, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - initialPath: `/draft/${activeDraftId}`, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: 2, - branches: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "From main", - ) as HTMLButtonElement | null, - 'Unable to find branch selector button with "From main".', - ); - branchButton.click(); - - const branchOption = await waitForElement( - () => - Array.from(document.querySelectorAll("span")).find( - (element) => element.textContent?.trim() === "release/next", - ) as HTMLSpanElement | null, - 'Unable to find the "release/next" branch option.', - ); - branchOption.click(); - - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().getDraftSession(activeDraftId)?.branch).toBe( - "release/next", - ); - expect(useComposerDraftStore.getState().getDraftSession(staleDraftId)?.branch).toBe( - "main", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const updatedButton = Array.from(document.querySelectorAll("button")).find((button) => - button.textContent?.trim().includes("From release/next"), - ); - expect(updatedButton).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the new worktree branch picker anchored at the top when opening with a preselected branch", async () => { - const draftId = DraftId.make("draft-branch-picker-scroll-regression"); - const branches = [ - { - name: "feature/current", - current: true, - isDefault: false, - worktreePath: null, - }, - { - name: "main", - current: false, - isDefault: true, - worktreePath: null, - }, - ...Array.from({ length: 48 }, (_, index) => ({ - name: `feature/${String(index).padStart(2, "0")}`, - current: false, - isDefault: false, - worktreePath: null, - })), - { - name: "feature/selected", - current: false, - isDefault: false, - worktreePath: null, - }, - ]; - - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [draftId]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "feature/selected", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: draftId, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - initialPath: `/draft/${draftId}`, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitListBranches) { - return { - isRepo: true, - hasOriginRemote: true, - nextCursor: null, - totalCount: branches.length, - branches, - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "From feature/selected", - ) as HTMLButtonElement | null, - 'Unable to find branch selector button with "From feature/selected".', - ); - branchButton.click(); - - await waitForElement( - () => document.querySelector('input[placeholder="Search branches..."]'), - "Unable to find branch search input.", - ); - - const popup = await waitForElement( - () => document.querySelector('[data-slot="combobox-popup"]'), - "Unable to find the branch picker popup.", - ); - - await vi.waitFor( - () => { - const popupSpans = Array.from(popup.querySelectorAll("span")); - expect( - popupSpans.some((element) => element.textContent?.trim() === "feature/current"), - ).toBe(true); - expect(popupSpans.some((element) => element.textContent?.trim() === "main")).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("surrounds selected plain text and preserves the inner selection for repeated wrapping", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-basic" as MessageId, - targetText: "surround basic", - }), - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected"); - await waitForComposerText("selected"); - await setComposerSelectionByTextOffsets({ start: 0, end: "selected".length }); - await pressComposerKey("("); - await waitForComposerText("(selected)"); - - await pressComposerKey("["); - await waitForComposerText("([selected])"); - } finally { - await mounted.cleanup(); - } - }); - - it("leaves collapsed-caret typing unchanged for surround symbols", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-collapsed" as MessageId, - targetText: "surround collapsed", - }), - }); - - try { - await waitForComposerText("selected"); - await setComposerSelectionByTextOffsets({ - start: "selected".length, - end: "selected".length, - }); - await pressComposerKey("("); - await waitForComposerText("selected("); - } finally { - await mounted.cleanup(); - } - }); - - it("supports symmetric and backward-selection surrounds", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "backward"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-backward" as MessageId, - targetText: "surround backward", - }), - }); - - try { - await waitForComposerText("backward"); - await setComposerSelectionByTextOffsets({ - start: 0, - end: "backward".length, - direction: "backward", - }); - await pressComposerKey("*"); - await waitForComposerText("*backward*"); - } finally { - await mounted.cleanup(); - } - }); - - it("supports option-produced surround symbols like guillemets", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-guillemet" as MessageId, - targetText: "surround guillemet", - }), - }); - - try { - await waitForComposerText("quoted"); - await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length }); - await pressComposerKey("«"); - await waitForComposerText("«quoted»"); - } finally { - await mounted.cleanup(); - } - }); - - it("supports dead-key composition that resolves to another surround symbol without an extra undo step", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-dead-quote" as MessageId, - targetText: "surround dead quote", - }), - }); - - try { - await waitForComposerText("quoted"); - await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length }); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Dead", - bubbles: true, - cancelable: true, - }), - ); - composerEditor.dispatchEvent( - new InputEvent("beforeinput", { - data: "'", - inputType: "insertCompositionText", - bubbles: true, - cancelable: true, - }), - ); - const resolvedInputEvent = new InputEvent("beforeinput", { - data: "'", - inputType: "insertText", - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(resolvedInputEvent); - expect(resolvedInputEvent.defaultPrevented).toBe(true); - await waitForComposerText("'quoted'"); - await pressComposerUndo(); - await waitForComposerText("quoted"); - } finally { - await mounted.cleanup(); - } - }); - - it("surrounds text after a mention using the correct expanded offsets", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-after-mention" as MessageId, - targetText: "surround after mention", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("package.json"); - }, - { timeout: 8_000, interval: 16 }, - ); - await waitForComposerText("hi @package.json there"); - await setComposerSelectionByTextOffsets({ - start: "hi package.json ".length, - end: "hi package.json there".length, - }); - await pressComposerKey("("); - await waitForComposerText("hi @package.json (there)"); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to normal replacement when the selection includes a mention token", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there "); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-token" as MessageId, - targetText: "surround token", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("package.json"); - }, - { timeout: 8_000, interval: 16 }, - ); - await selectAllComposerContent(); - await pressComposerKey("("); - await waitForComposerText("("); - } finally { - await mounted.cleanup(); - } - }); - - it("shows runtime mode descriptions in the desktop composer access select", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - }); - - try { - const runtimeModeSelect = await waitForButtonByText("Full access"); - runtimeModeSelect.click(); - - expect((await waitForSelectItemContainingText("Supervised")).textContent).toContain( - "Ask before commands and file changes", - ); - - const autoAcceptItem = await waitForSelectItemContainingText("Auto-accept edits"); - expect(autoAcceptItem.textContent).toContain("Auto-approve edits"); - expect((await waitForSelectItemContainingText("Full access")).textContent).toContain( - "Allow commands and edits without prompts", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps removed terminal context pills removed when a new one is added", async () => { - const removedLabel = "Terminal 1 lines 1-2"; - const addedLabel = "Terminal 2 lines 9-10"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-removed", - terminalLabel: "Terminal 1", - lineStart: 1, - lineEnd: 2, - text: "bun i\nno changes", - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-terminal-pill-backspace" as MessageId, - targetText: "terminal pill backspace target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const store = useComposerDraftStore.getState(); - const currentPrompt = store.draftsByThreadKey[THREAD_KEY]?.prompt ?? ""; - const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0); - store.setPrompt(THREAD_REF, nextPrompt.prompt); - store.removeTerminalContext(THREAD_REF, "ctx-removed"); - - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]).toBeUndefined(); - expect(document.body.textContent).not.toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-added", - terminalLabel: "Terminal 2", - lineStart: 9, - lineEnd: 10, - text: "git status\nOn branch main", - }), - ); - - await vi.waitFor( - () => { - const draft = useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]; - expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]); - expect(document.body.textContent).toContain(addedLabel); - expect(document.body.textContent).not.toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("disables send when the composer only contains an expired terminal pill", async () => { - const expiredLabel = "Terminal 1 line 4"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-expired-only", - terminalLabel: "Terminal 1", - lineStart: 4, - lineEnd: 4, - text: "", - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-expired-pill-disabled" as MessageId, - targetText: "expired pill disabled target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(expiredLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(true); - } finally { - await mounted.cleanup(); - } - }); - - it("warns when sending text while omitting expired terminal pills", async () => { - const expiredLabel = "Terminal 1 line 4"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-expired-send-warning", - terminalLabel: "Terminal 1", - lineStart: 4, - lineEnd: 4, - text: "", - }), - ); - useComposerDraftStore - .getState() - .setPrompt(THREAD_REF, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-expired-pill-warning" as MessageId, - targetText: "expired pill warning target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(expiredLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain( - "Expired terminal context omitted from message", - ); - expect(document.body.textContent).not.toContain(expiredLabel); - expect(document.body.textContent).toContain("yoowaddup"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows a pointer cursor for the running stop button", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-stop-button-cursor" as MessageId, - targetText: "stop button cursor target", - sessionStatus: "running", - }), - }); - - try { - const stopButton = await waitForElement( - () => document.querySelector('button[aria-label="Stop generation"]'), - "Unable to find stop generation button.", - ); - - expect(getComputedStyle(stopButton).cursor).toBe("pointer"); - } finally { - await mounted.cleanup(); - } - }); - - it("hides the archive action when the pointer leaves a thread row", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-archive-hover-test" as MessageId, - targetText: "archive hover target", - }), - }); - - try { - const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); - - await expect.element(threadRow).toBeInTheDocument(); - const archiveButton = await waitForElement( - () => - document.querySelector(`[data-testid="thread-archive-${THREAD_ID}"]`), - "Unable to find archive button.", - ); - const archiveAction = archiveButton.parentElement; - expect( - archiveAction, - "Archive button should render inside a visibility wrapper.", - ).not.toBeNull(); - expect(getComputedStyle(archiveAction!).opacity).toBe("0"); - - await threadRow.hover(); - await vi.waitFor( - () => { - expect(getComputedStyle(archiveAction!).opacity).toBe("1"); - }, - { timeout: 4_000, interval: 16 }, - ); - - await page.getByTestId("composer-editor").hover(); - await vi.waitFor( - () => { - expect(getComputedStyle(archiveAction!).opacity).toBe("0"); - }, - { timeout: 4_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("exposes the full thread title on the sidebar row tooltip", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-thread-tooltip-target" as MessageId, - targetText: "thread tooltip target", - }), - }); - - try { - const threadTitle = page.getByTestId(`thread-title-${THREAD_ID}`); - - await expect.element(threadTitle).toBeInTheDocument(); - await threadTitle.hover(); - - await vi.waitFor( - () => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip).not.toBeNull(); - expect(tooltip?.textContent).toContain(THREAD_TITLE); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows the confirm archive action after clicking the archive button", async () => { - localStorage.setItem( - "t3code:client-settings:v1", - JSON.stringify({ - ...DEFAULT_CLIENT_SETTINGS, - confirmThreadArchive: true, - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-archive-confirm-test" as MessageId, - targetText: "archive confirm target", - }), - }); - - try { - const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); - - await expect.element(threadRow).toBeInTheDocument(); - await threadRow.hover(); - - const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`); - await expect.element(archiveButton).toBeInTheDocument(); - await archiveButton.click(); - - const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`); - await expect.element(confirmButton).toBeInTheDocument(); - await expect.element(confirmButton).toBeVisible(); - } finally { - localStorage.removeItem("t3code:client-settings:v1"); - await mounted.cleanup(); - } - }); - - it("canonicalizes promoted draft threads to the server thread route", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-test" as MessageId, - targetText: "new thread selection test", - }), - }); - - try { - // Wait for the sidebar to render with the project. - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - // The route should change to a new draft thread ID. - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - const newThreadId = draftThreadIdFor(newDraftId); - - // The composer editor should be present for the new draft thread. - await waitForComposerEditor(); - - // `thread.created` should only mark the draft as promoting; it should - // not navigate away until the server thread has actual runtime state. - await materializePromotedDraftThreadViaDomainEvent(newThreadId); - expect(mounted.router.state.location.pathname).toBe(newThreadPath); - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - - // Once the server thread starts, the route should canonicalize. - await startPromotedServerThreadViaDomainEvent(newThreadId); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftThreadsByThreadKey[newDraftId]).toBe( - undefined, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - // The route should switch to the canonical server thread path. - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(newThreadId), - "Promoted drafts should canonicalize to the server thread route.", - ); - - // The composer should remain usable after canonicalization, regardless of - // whether the promoted thread is still visibly empty or has already - // entered the running state. - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("canonicalizes stale promoted draft routes to the server thread route", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-hydration-race-test" as MessageId, - targetText: "draft hydration race test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - const newThreadId = draftThreadIdFor(newDraftId); - - await promoteDraftThreadViaDomainEvent(newThreadId); - - await mounted.router.navigate({ - to: "/draft/$draftId", - params: { draftId: newDraftId }, - }); - - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(newThreadId), - "Stale promoted draft routes should canonicalize to the server thread path.", - ); - - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a fresh worktree draft from an existing worktree thread when the default mode is worktree", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId, - targetText: "new thread worktree default test", - }), - threads: createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId, - targetText: "new thread worktree default test", - }).threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - branch: "feature/existing", - worktreePath: "/repo/.t3/worktrees/existing", - }) - : thread, - ), - }, - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - }; - }, - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should change to a new draft thread.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(useComposerDraftStore.getState().getDraftSession(newDraftId)).toMatchObject({ - envMode: "worktree", - worktreePath: null, - }); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new draft instead of reusing a promoting draft thread", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-promoting-draft-new-thread-test" as MessageId, - targetText: "promoting draft new thread test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const firstDraftPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should change to the first draft thread.", - ); - const firstDraftId = draftIdFromPath(firstDraftPath); - const firstThreadId = draftThreadIdFor(firstDraftId); - - await materializePromotedDraftThreadViaDomainEvent(firstThreadId); - expect(mounted.router.state.location.pathname).toBe(firstDraftPath); - - await newThreadButton.click(); - - const secondDraftPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path) && path !== firstDraftPath, - "Route should change to a second draft thread instead of reusing the promoting draft.", - ); - expect(draftIdFromPath(secondDraftPath)).not.toBe(firstDraftId); - } finally { - await mounted.cleanup(); - } - }); - - it("snapshots sticky codex settings into a new draft thread", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "medium", - fastMode: true, - }, - }, - }, - stickyActiveProvider: "codex", - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sticky-codex-traits-test" as MessageId, - targetText: "sticky codex traits test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(composerDraftFor(newDraftId)).toMatchObject({ - modelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - fastMode: true, - }, - }, - }, - activeProvider: "codex", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("hydrates the provider alongside a sticky claude model", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - claudeAgent: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - fastMode: true, - }, - }, - }, - stickyActiveProvider: "claudeAgent", - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sticky-claude-model-test" as MessageId, - targetText: "sticky claude model test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new sticky claude draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(composerDraftFor(newDraftId)).toMatchObject({ - modelSelectionByProvider: { - claudeAgent: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - fastMode: true, - }, - }, - }, - activeProvider: "claudeAgent", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to defaults when no sticky composer settings exist", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-default-codex-traits-test" as MessageId, - targetText: "default codex traits test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(composerDraftFor(newDraftId)).toBe(undefined); - } finally { - await mounted.cleanup(); - } - }); - - it("prefers draft state over sticky composer settings and defaults", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "medium", - fastMode: true, - }, - }, - }, - stickyActiveProvider: "codex", - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-codex-traits-precedence-test" as MessageId, - targetText: "draft codex traits precedence test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const threadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a sticky draft thread UUID.", - ); - const draftId = draftIdFromPath(threadPath); - - expect(composerDraftFor(draftId)).toMatchObject({ - modelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - fastMode: true, - }, - }, - }, - activeProvider: "codex", - }); - - useComposerDraftStore.getState().setModelSelection(draftId, { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "low", - fastMode: true, - }, - }); - - await newThreadButton.click(); - - await waitForURL( - mounted.router, - (path) => path === threadPath, - "New-thread should reuse the existing project draft thread.", - ); - expect(composerDraftFor(draftId)).toMatchObject({ - modelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "low", - fastMode: true, - }, - }, - }, - activeProvider: "codex", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new thread from the global chat.new shortcut", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-chat-shortcut-test" as MessageId, - targetText: "chat shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "o", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForNewThreadShortcutLabel(); - await waitForServerConfigToApply(); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - await waitForLayout(); - await triggerChatNewShortcutUntilPath( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the shortcut.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not consume chat.new when there is no project context", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createProjectlessSnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "o", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - dispatchChatNewShortcut(); - await waitForLayout(); - - expect(mounted.router.state.location.pathname).toBe(serverThreadPath(THREAD_ID)); - expect(Object.keys(useComposerDraftStore.getState().draftThreadsByThreadKey)).toHaveLength(0); - } finally { - await mounted.cleanup(); - } - }); - - it("renders the configurable shortcut and runs a command from the sidebar trigger", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-shortcut-test" as MessageId, - targetText: "command palette shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await expect - .element(palette.getByText("New thread in Project", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("New thread in Project", { exact: true }).click(); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the command palette.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("filters command palette results as the user types", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-search-test" as MessageId, - targetText: "command palette search test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("settings"); - await expect.element(palette.getByText("Open settings", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("New thread in Project", { exact: true })) - .not.toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("adds a project from browse mode with Enter when no directory is highlighted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId, - targetText: "command palette add project enter", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [ - { name: "alpha", fullPath: "~/Development/alpha" }, - { name: "beta", fullPath: "~/Development/beta" }, - ], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); - - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development", - title: "Development", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project with Enter.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens add project browse mode from the sidebar add button", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sidebar-add-project-trigger" as MessageId, - targetText: "sidebar add project trigger", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await expect.element(browseInput).toHaveValue("~/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && request.partialPath === "~/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("starts add project browse mode from the configured base directory", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sidebar-add-project-custom-base-dir" as MessageId, - targetText: "sidebar add project custom base directory", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - addProjectBaseDirectory: "~/Development", - }, - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [{ name: "codething", fullPath: "~/Development/codething" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await expect.element(browseInput).toHaveValue("~/Development/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && - request.partialPath === "~/Development/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows create-folder affordances for missing project paths", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-create-missing-project" as MessageId, - targetText: "command palette create missing project", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Desktop/") { - return { - parentPath: "~/Desktop/", - entries: [{ name: "existing", fullPath: "~/Desktop/existing" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Desktop", fullPath: "~/Desktop" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); - await page.getByTestId("sidebar-add-project-trigger").click(); - - await expect.element(palette).toBeInTheDocument(); - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project"); - - await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) - .toBeInTheDocument(); - await expect.element(palette.getByText("Will create this folder")).not.toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - createWorkspaceRootIfMissing?: boolean; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Desktop/fresh-project", - title: "fresh-project", - createWorkspaceRootIfMissing: true, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not show create affordances for an existing directory with a trailing slash", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-existing-trailing-directory" as MessageId, - targetText: "command palette existing trailing directory", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/codex/") { - return { - parentPath: "~/Development/codex/", - entries: [{ name: "Codex.app", fullPath: "~/Development/codex/Codex.app" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); - await page.getByTestId("sidebar-add-project-trigger").click(); - - await expect.element(palette).toBeInTheDocument(); - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && - request.partialPath === "~/Development/codex/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) - .not.toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development/codex", - title: "codex", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("selects an environment before browsing when multiple environments are available", async () => { - const remoteBrowseMock = vi.fn(async ({ partialPath }: { partialPath: string }) => { - if (partialPath === "~/workspaces/") { - return { - parentPath: "~/workspaces/", - entries: [{ name: "codething", fullPath: "~/workspaces/codething" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "workspaces", fullPath: "~/workspaces" }], - }; - }); - const remoteDispatchMock = vi.fn(async () => ({ - sequence: fixture.snapshot.snapshotSequence + 1, - })); - - __setEnvironmentApiOverrideForTests( - REMOTE_ENVIRONMENT_ID, - createMockEnvironmentApi({ - browse: remoteBrowseMock, - dispatchCommand: remoteDispatchMock, - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-multi-env" as MessageId, - targetText: "command palette add project multi env", - }), - }); - - try { - await waitForServerConfigToApply(); - useSavedEnvironmentRegistryStore.getState().upsert({ - environmentId: REMOTE_ENVIRONMENT_ID, - label: "Staging", - httpBaseUrl: "https://staging.example.test", - wsBaseUrl: "wss://staging.example.test/ws", - createdAt: NOW_ISO, - lastConnectedAt: NOW_ISO, - }); - useSavedEnvironmentRuntimeStore.getState().patch(REMOTE_ENVIRONMENT_ID, { - connectionState: "connected", - authState: "authenticated", - descriptor: { - ...fixture.serverConfig.environment, - environmentId: REMOTE_ENVIRONMENT_ID, - label: "Staging", - }, - serverConfig: { - ...fixture.serverConfig, - environment: { - ...fixture.serverConfig.environment, - environmentId: REMOTE_ENVIRONMENT_ID, - label: "Staging", - }, - settings: { - ...fixture.serverConfig.settings, - addProjectBaseDirectory: "~/workspaces", - }, - }, - connectedAt: NOW_ISO, - }); - - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("This device", { exact: true }).first()) - .toBeInTheDocument(); - await palette.getByText("Staging", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await expect.element(browseInput).toHaveValue("~/workspaces/"); - - await vi.waitFor( - () => { - expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/workspaces/"); - await vi.waitFor( - () => { - expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" }); - }, - { timeout: 8_000, interval: 16 }, - ); - await expect.element(palette.getByText("codething", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - expect(remoteDispatchMock).toHaveBeenCalledWith( - expect.objectContaining({ - type: "project.create", - workspaceRoot: "~/workspaces", - title: "workspaces", - }), - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a remote project.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("picks a local project from the native file manager", async () => { - const pickFolder = vi.fn().mockResolvedValue("/Users/julius/Projects/finder-picked"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-file-manager" as MessageId, - targetText: "command palette add project file manager", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Applications/") { - return { - parentPath: "~/Applications/", - entries: [{ name: "Utilities", fullPath: "~/Applications/Utilities" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Applications", fullPath: "~/Applications" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - window.desktopBridge = { - pickFolder, - setTheme: vi.fn().mockResolvedValue(undefined), - } as unknown as NonNullable; - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await browseInput.fill("~/Applications/access"); - - const fileManagerLabel = isMacPlatform(navigator.platform) - ? "Open in Finder" - : navigator.platform.toLowerCase().startsWith("win") - ? "Open in Explorer" - : "Open in Files"; - await palette.getByRole("button", { name: fileManagerLabel }).click(); - - await vi.waitFor( - () => { - expect(pickFolder).toHaveBeenCalledWith({ initialPath: "~/Applications" }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "/Users/julius/Projects/finder-picked", - title: "finder-picked", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project from the native file manager.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("adds a project from browse mode with Mod+Enter when a directory is highlighted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-mod-enter" as MessageId, - targetText: "command palette add project mod enter", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [ - { name: "alpha", fullPath: "~/Development/alpha" }, - { name: "beta", fullPath: "~/Development/beta" }, - ], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "ArrowDown" }); - - const addButtonLabel = isMacPlatform(navigator.platform) - ? "Add (\u2318 Enter)" - : "Add (Ctrl Enter)"; - await vi.waitFor( - () => { - const legendEntries = getCommandPaletteLegendEntries(); - expect(legendEntries).toContain("Enter Select"); - }, - { timeout: 8_000, interval: 16 }, - ); - await expect - .element(palette.getByRole("button", { name: addButtonLabel })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { - key: "Enter", - metaKey: isMacPlatform(navigator.platform), - ctrlKey: !isMacPlatform(navigator.platform), - }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development", - title: "Development", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project with Mod+Enter.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps project-context thread matches available when searching by project name", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("Release checklist", { exact: true })) - .toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("searches projects by path and opens the latest thread for that project", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("Docs Portal", { exact: true }).click(); - - const nextPath = await waitForURL( - mounted.router, - (path) => path === serverThreadPath("thread-secondary-project" as ThreadId), - "Route should have changed to the latest thread for the selected project.", - ); - expect(nextPath).toBe(serverThreadPath("thread-secondary-project" as ThreadId)); - expect( - useComposerDraftStore - .getState() - .getDraftThread(threadRefFor("thread-secondary-project" as ThreadId)), - ).toBeNull(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new thread from project search when no active project thread exists", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject({ includeSecondaryThread: false }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("Docs Portal", { exact: true }).click(); - - const nextPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the project search result.", - ); - const nextDraftId = draftIdFromPath(nextPath); - const draftThread = useComposerDraftStore.getState().getDraftSession(nextDraftId); - expect(draftThread?.projectId).toBe(SECOND_PROJECT_ID); - expect(draftThread?.envMode).toBe("worktree"); - } finally { - await mounted.cleanup(); - } - }); - - it("filters archived threads out of command palette search results", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs-archive"); - await expect - .element(palette.getByText("Archived Docs Notes", { exact: true })) - .not.toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a fresh draft after the previous draft thread is promoted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId, - targetText: "promoted draft shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "o", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - await waitForServerConfigToApply(); - await newThreadButton.click(); - - const promotedThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a promoted draft thread UUID.", - ); - const promotedDraftId = draftIdFromPath(promotedThreadPath); - const promotedThreadId = draftThreadIdFor(promotedDraftId); - - await promoteDraftThreadViaDomainEvent(promotedThreadId); - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(promotedThreadId), - "Promoted drafts should canonicalize to the server thread route before a fresh draft is created.", - ); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().getDraftThread(promotedDraftId)).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - await waitForLayout(); - - const freshThreadPath = await triggerChatNewShortcutUntilPath( - mounted.router, - (path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath, - "Shortcut should create a fresh draft instead of reusing the promoted thread.", - ); - expect(freshThreadPath).not.toBe(promotedThreadPath); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps long proposed plans lightweight until the user expands them", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithLongProposedPlan(), - }); - - try { - await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Expand plan", - ) as HTMLButtonElement | null, - "Unable to find Expand plan button.", - ); - - expect(document.body.textContent).not.toContain("deep hidden detail only after expand"); - - const expandButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Expand plan", - ) as HTMLButtonElement | null, - "Unable to find Expand plan button.", - ); - expandButton.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("deep hidden detail only after expand"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("uses the active worktree path when saving a proposed plan to the workspace", async () => { - const snapshot = createSnapshotWithLongProposedPlan(); - const threads = snapshot.threads.slice(); - const targetThreadIndex = threads.findIndex((thread) => thread.id === THREAD_ID); - const targetThread = targetThreadIndex >= 0 ? threads[targetThreadIndex] : undefined; - if (targetThread) { - threads[targetThreadIndex] = { - ...targetThread, - worktreePath: "/repo/worktrees/plan-thread", - }; - } - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads, - }, - }); - - try { - const planActionsButton = await waitForElement( - () => document.querySelector('button[aria-label="Plan actions"]'), - "Unable to find proposed plan actions button.", - ); - planActionsButton.click(); - - const saveToWorkspaceItem = await waitForElement( - () => - (Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find( - (item) => item.textContent?.trim() === "Save to workspace", - ) ?? null) as HTMLElement | null, - 'Unable to find "Save to workspace" menu item.', - ); - saveToWorkspaceItem.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain( - "Enter a path relative to /repo/worktrees/plan-thread.", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps pending-question footer actions inside the composer after a real resize", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPendingUserInput(), - }); - - try { - const firstOption = await waitForButtonContainingText("Tight"); - firstOption.click(); - - await waitForButtonByText("Previous"); - await waitForButtonByText("Submit answers"); - - await mounted.setContainerSize(COMPACT_FOOTER_VIEWPORT); - await expectComposerActionsContained(); - } finally { - await mounted.cleanup(); - } - }); - - it("submits pending user input after the final option selection resolves the draft answers", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithPendingUserInput(), - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - const firstOption = await waitForButtonContainingText("Tight"); - firstOption.click(); - - const finalOption = await waitForButtonContainingText("Conservative"); - finalOption.click(); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.user-input.respond", - ) as - | { - _tag: string; - type?: string; - requestId?: string; - answers?: Record; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.user-input.respond", - requestId: "req-browser-user-input", - answers: { - scope: "Tight", - risk: "Conservative", - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt(), - }); - - try { - const footer = await waitForElement( - () => document.querySelector('[data-chat-composer-footer="true"]'), - "Unable to find composer footer.", - ); - const initialModelPicker = await waitForElement( - findComposerProviderModelPicker, - "Unable to find provider model picker.", - ); - const initialModelPickerOffset = - initialModelPicker.getBoundingClientRect().left - footer.getBoundingClientRect().left; - const initialImplementButton = await waitForButtonByText("Implement"); - const initialImplementWidth = initialImplementButton.getBoundingClientRect().width; - - await waitForElement( - () => - document.querySelector('button[aria-label="Implementation actions"]'), - "Unable to find implementation actions trigger.", - ); - - await mounted.setContainerSize({ - width: 440, - height: WIDE_FOOTER_VIEWPORT.height, - }); - await expectComposerActionsContained(); - - const implementButton = await waitForButtonByText("Implement"); - const implementActionsButton = await waitForElement( - () => - document.querySelector('button[aria-label="Implementation actions"]'), - "Unable to find implementation actions trigger.", - ); - - await vi.waitFor( - () => { - const implementRect = implementButton.getBoundingClientRect(); - const implementActionsRect = implementActionsButton.getBoundingClientRect(); - const compactModelPicker = findComposerProviderModelPicker(); - expect(compactModelPicker).toBeTruthy(); - - const compactModelPickerOffset = - compactModelPicker!.getBoundingClientRect().left - footer.getBoundingClientRect().left; - - expect(Math.abs(implementRect.right - implementActionsRect.left)).toBeLessThanOrEqual(1); - expect(Math.abs(implementRect.top - implementActionsRect.top)).toBeLessThanOrEqual(1); - expect(Math.abs(implementRect.width - initialImplementWidth)).toBeLessThanOrEqual(1); - expect(Math.abs(compactModelPickerOffset - initialModelPickerOffset)).toBeLessThanOrEqual( - 1, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the wide desktop follow-up layout expanded when the footer still fits", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" }, - planMarkdown: - "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", - }), - }); - - try { - await waitForButtonByText("Implement"); - - await vi.waitFor( - () => { - const footer = document.querySelector('[data-chat-composer-footer="true"]'); - const actions = document.querySelector( - '[data-chat-composer-actions="right"]', - ); - - expect(footer?.dataset.chatComposerFooterCompact).toBe("false"); - expect(actions?.dataset.chatComposerPrimaryActionsCompact).toBe("false"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("compacts the footer when a wide desktop follow-up layout starts overflowing", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" }, - planMarkdown: - "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", - }), - }); - - try { - await waitForButtonByText("Implement"); - - await mounted.setContainerSize({ - width: 804, - height: WIDE_FOOTER_VIEWPORT.height, - }); - - await expectComposerActionsContained(); - - await vi.waitFor( - () => { - const footer = document.querySelector('[data-chat-composer-footer="true"]'); - const actions = document.querySelector( - '[data-chat-composer-actions="right"]', - ); - - expect(footer?.dataset.chatComposerFooterCompact).toBe("true"); - expect(actions?.dataset.chatComposerPrimaryActionsCompact).toBe("true"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the slash-command menu visible above the composer", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-menu-target" as MessageId, - targetText: "command menu thread", - }), - }); - - try { - await waitForComposerEditor(); - await page.getByTestId("composer-editor").fill("/"); - - const menuItem = await waitForComposerMenuItem("slash:model"); - const composerForm = await waitForElement( - () => document.querySelector('[data-chat-composer-form="true"]'), - "Unable to find composer form.", - ); - - await vi.waitFor( - () => { - const menuRect = menuItem.getBoundingClientRect(); - const composerRect = composerForm.getBoundingClientRect(); - const hitTarget = document.elementFromPoint( - menuRect.left + menuRect.width / 2, - menuRect.top + menuRect.height / 2, - ); - - expect(menuRect.width).toBeGreaterThan(0); - expect(menuRect.height).toBeGreaterThan(0); - expect(menuRect.bottom).toBeLessThanOrEqual(composerRect.bottom); - expect(hitTarget instanceof Element && menuItem.contains(hitTarget)).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows a tooltip with the skill description when hovering a skill pill", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-skill-tooltip-target" as MessageId, - targetText: "skill tooltip thread", - }), - configureFixture: (nextFixture) => { - const provider = nextFixture.serverConfig.providers[0]; - if (!provider) { - throw new Error("Expected default provider in test fixture."); - } - ( - provider as { - skills: ServerConfig["providers"][number]["skills"]; - } - ).skills = [ - { - name: "agent-browser", - displayName: "Agent Browser", - description: "Open pages, click around, and inspect web apps.", - path: "/Users/test/.agents/skills/agent-browser/SKILL.md", - enabled: true, - }, - ]; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "use the $agent-browser "); - await waitForComposerText("use the $agent-browser "); - - await waitForElement( - () => document.querySelector('[data-composer-skill-chip="true"]'), - "Unable to find rendered composer skill chip.", - ); - await page.getByText("Agent Browser").hover(); - - await vi.waitFor( - () => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip).not.toBeNull(); - expect(tooltip?.textContent).toContain("Open pages, click around, and inspect web apps."); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); -}); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 41a1cbed5d..279b138186 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -18,8 +18,6 @@ import { MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, branchMismatchKey, buildExpiredTerminalContextToastCopy, - buildLoadingThreadFromShell, - buildThreadTurnInterruptInput, createLocalDispatchSnapshot, deriveCommittedServerUserMessageIds, deriveComposerSendState, @@ -31,6 +29,8 @@ import { reconcileRetainedMountedThreadIds, resolveThreadMetadataUpdateForNextTurn, resolveSendEnvMode, + startNewThreadForProject, + shouldShowBranchMismatchBanner, shouldShowComposerContextStrip, shouldWriteThreadErrorToCurrentServerThread, } from "./ChatView.logic"; @@ -86,51 +86,6 @@ const readySession = { updatedAt: "2026-03-29T00:00:10.000Z", }; -describe("buildLoadingThreadFromShell", () => { - it("preserves shell metadata and supplies empty detail collections", () => { - const shell = { - environmentId, - id: threadId, - projectId, - title: "Loading thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - latestTurn: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - snoozedUntil: null, - snoozedAt: null, - session: null, - latestUserMessageAt: now, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - } satisfies ThreadShell; - - expect(buildLoadingThreadFromShell(shell)).toMatchObject({ - environmentId, - id: threadId, - projectId, - title: "Loading thread", - branch: "main", - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - }); - }); -}); - describe("resolveThreadMetadataUpdateForNextTurn", () => { const modelSelection = { instanceId: ProviderInstanceId.make("codex"), @@ -486,24 +441,19 @@ describe("reconcileRetainedMountedThreadIds", () => { }); describe("shouldWriteThreadErrorToCurrentServerThread", () => { - it("writes errors for a shell-derived active server thread", () => { + it("requires the environment, route thread, and target thread to match", () => { const routeThreadRef = { environmentId, threadId }; expect( shouldWriteThreadErrorToCurrentServerThread({ - activeServerThread: { environmentId, id: threadId }, + serverThread: { environmentId, id: threadId }, routeThreadRef, targetThreadId: threadId, }), ).toBe(true); - }); - - it("requires an active server thread matching the environment, route, and target", () => { - const routeThreadRef = { environmentId, threadId }; - expect( shouldWriteThreadErrorToCurrentServerThread({ - activeServerThread: null, + serverThread: null, routeThreadRef, targetThreadId: threadId, }), @@ -627,42 +577,29 @@ describe("hasServerAcknowledgedLocalDispatch", () => { ).toBe(true); }); - it("acknowledges a steering message projected onto the current running turn", () => { - const runningTurn = { + it("acknowledges a steering message projected onto the current running run", () => { + const runningRun = { ...completedTurn, - state: "running" as const, + status: "running" as const, completedAt: null, }; - const runningSession = { + const runningRuntime = { ...readySession, status: "running" as const, - activeTurnId: runningTurn.turnId, + activeRunId: runningRun.runId, }; const localDispatch = createLocalDispatchSnapshot( - makeThread({ - latestTurn: runningTurn, - session: runningSession, - messages: [ - { - id: MessageId.make("message-before-steer"), - role: "user", - text: "Initial prompt", - turnId: runningTurn.turnId, - createdAt: runningTurn.requestedAt, - updatedAt: runningTurn.requestedAt, - streaming: false, - }, - ], - }), + makeThread({ latestRun: runningRun, runtime: runningRuntime }), + { latestUserMessageId: MessageId.make("message-before-steer") }, ); expect( hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", - latestTurn: runningTurn, + latestRun: runningRun, latestUserMessageId: MessageId.make("message-steer"), - session: runningSession, + runtime: runningRuntime, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 086e1f44d4..3264951bed 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -102,23 +102,14 @@ export function buildLocalDraftThread( createdAt: timestamp, updatedAt: timestamp, archivedAt: null, + settledOverride: null, + settledAt: null, deletedAt: null, }); } -export function buildLoadingThreadFromShell(shell: ThreadShell): Thread { - return { - ...shell, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - deletedAt: null, - }; -} - export function shouldWriteThreadErrorToCurrentServerThread(input: { - activeServerThread: + serverThread: | { environmentId: EnvironmentId; id: ThreadId; @@ -129,24 +120,13 @@ export function shouldWriteThreadErrorToCurrentServerThread(input: { targetThreadId: ThreadId; }): boolean { return Boolean( - input.activeServerThread && + input.serverThread && input.targetThreadId === input.routeThreadRef.threadId && - input.activeServerThread.environmentId === input.routeThreadRef.environmentId && - input.activeServerThread.id === input.targetThreadId, + input.serverThread.environmentId === input.routeThreadRef.environmentId && + input.serverThread.id === input.targetThreadId, ); } -export function buildThreadTurnInterruptInput(thread: Pick): { - threadId: ThreadId; - turnId?: TurnId; -} { - const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null; - return { - threadId: thread.id, - ...(runningTurnId !== null ? { turnId: runningTurnId } : {}), - }; -} - export function reconcileMountedTerminalThreadIds(input: { currentThreadIds: ReadonlyArray; openThreadIds: ReadonlyArray; @@ -473,6 +453,7 @@ export async function waitForStartedServerThread( export interface LocalDispatchSnapshot { startedAt: string; preparingWorktree: boolean; + latestUserMessageId: ChatMessage["id"] | null; latestRunId: RunId | null; latestRunRequestedAt: string | null; latestRunStartedAt: string | null; @@ -483,13 +464,14 @@ export interface LocalDispatchSnapshot { export function createLocalDispatchSnapshot( activeThread: Thread | undefined, - options?: { preparingWorktree?: boolean }, + options?: { preparingWorktree?: boolean; latestUserMessageId?: ChatMessage["id"] | null }, ): LocalDispatchSnapshot { const latestRun = activeThread?.latestRun ?? null; const runtime = activeThread?.runtime ?? null; return { startedAt: new Date().toISOString(), preparingWorktree: Boolean(options?.preparingWorktree), + latestUserMessageId: options?.latestUserMessageId ?? null, latestRunId: latestRun?.runId ?? null, latestRunRequestedAt: latestRun?.requestedAt ?? null, latestRunStartedAt: latestRun?.startedAt ?? null, @@ -519,6 +501,7 @@ export function hasServerAcknowledgedLocalDispatch(input: { localDispatch: LocalDispatchSnapshot | null; phase: SessionPhase; latestRun: Thread["latestRun"] | null; + latestUserMessageId?: ChatMessage["id"] | null; runtime: Thread["runtime"] | null; hasPendingApproval: boolean; hasPendingUserInput: boolean; @@ -533,6 +516,8 @@ export function hasServerAcknowledgedLocalDispatch(input: { const latestRun = input.latestRun ?? null; const runtime = input.runtime ?? null; + const latestUserMessageChanged = + input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); const latestRunChanged = input.localDispatch.latestRunId !== (latestRun?.runId ?? null) || input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) || @@ -540,6 +525,9 @@ export function hasServerAcknowledgedLocalDispatch(input: { input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null); if (input.phase === "running") { + if (latestUserMessageChanged) { + return true; + } if (!latestRunChanged) { return false; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index bc1ea36e69..77352161a2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -22,7 +22,11 @@ import { RuntimeMode, TerminalOpenInput, } from "@t3tools/contracts"; -import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; +import { + connectionStatusTitle, + type EnvironmentConnectionPresentation, +} from "@t3tools/client-runtime/connection"; +import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { deriveThreadActivityRun, deriveLatestThreadRun, @@ -151,10 +155,18 @@ import { } from "../previewMiniPlayerStore"; import { RightPanelTabs } from "./RightPanelTabs"; import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; +import { BranchToolbar } from "./BranchToolbar"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; -import { ChevronDownIcon } from "lucide-react"; +import { + AlarmClockIcon, + CheckCircle2Icon, + ChevronDownIcon, + GitBranchIcon, + TriangleAlertIcon, + WifiOffIcon, +} from "lucide-react"; import { cn, randomHex } from "~/lib/utils"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; @@ -216,6 +228,7 @@ import { threadEnvironment } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; import { useEnvironments, usePrimaryEnvironment } from "../state/environments"; import { + resolveThreadDetailRef, useProject, useProjects, useThreadProjection, @@ -249,14 +262,22 @@ import { } from "./chat/ProviderStatusBanner"; import { ThreadErrorBanner } from "./chat/ThreadErrorBanner"; import { QueuedRunsControl } from "./chat/QueuedRunsControl"; +import { resolveThreadPr } from "./ThreadStatusIndicators"; +import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; +import { + DRAFT_HERO_TRANSITION_ANIMATION_ID, + DRAFT_HERO_TRANSITION_DURATION_MS, + DRAFT_HERO_TRANSITION_EASING, + MOBILE_COMPOSER_VIEW_TRANSITION_NAME, + MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME, + runMobileComposerTransition, +} from "./chat/draftHeroTransition"; import type { ComposerDispatchMode } from "./chat/composerDispatch"; import { MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, branchMismatchKey, buildExpiredTerminalContextToastCopy, buildLocalDraftThread, - buildLoadingThreadFromShell, - buildThreadTurnInterruptInput, collectUserMessageBlobPreviewUrls, createLocalDispatchSnapshot, deriveCommittedServerUserMessageIds, @@ -279,15 +300,16 @@ import { revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, shouldShowComposerContextStrip, + startNewThreadForProject, waitForStartedServerThread, } from "./ChatView.logic"; -import type { ThreadSyncPhase } from "../threadSync"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useComposerHandleContext } from "../composerHandleContext"; import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; import { RightPanelSheet } from "./RightPanelSheet"; import { previewEnvironment } from "../state/preview"; import { useAtomCommand } from "../state/use-atom-command"; +import { Button } from "./ui/button"; import { AlertDialog, AlertDialogClose, @@ -324,6 +346,7 @@ const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_PROJECTION_RUNS: OrchestrationV2ThreadProjection["runs"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; + function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { const transitionGroupRef = useRef(null); const composerAnchorRef = useRef(null); @@ -336,6 +359,7 @@ function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { const attachComposerAnchorRef = (element: HTMLDivElement | null) => { composerAnchorRef.current = element; }; + const captureComposerRect = () => { previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null; }; @@ -353,7 +377,6 @@ function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { animationRef.current?.cancel(); animationRef.current = null; - const previousComposerRect = previousComposerRectRef.current; if ( stateChanged && @@ -382,20 +405,21 @@ function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { void animation.finished .catch(() => undefined) .then(() => { - if (animationRef.current !== animation) { - return; - } - animationRef.current = null; + if (animationRef.current === animation) animationRef.current = null; }); } } - previousStateRef.current = isDraftHeroState; previousComposerRectRef.current = nextComposerRect; }, [isDraftHeroState]); - return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const; + return { + transitionGroupRef: attachTransitionGroupRef, + composerAnchorRef: attachComposerAnchorRef, + captureComposerRect, + } as const; } + const PreviewPanel = lazy(() => import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })), ); @@ -483,7 +507,6 @@ type ChatViewProps = onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; - threadSyncPhase?: ThreadSyncPhase | null; routeKind: "server"; draftId?: never; } @@ -493,7 +516,6 @@ type ChatViewProps = onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; - threadSyncPhase?: never; routeKind: "draft"; draftId: DraftId; }; @@ -509,14 +531,13 @@ type PersistentTerminalLaunchContext = Pick(null); - const latestUserMessageId = - input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null; const resetLocalDispatch = useCallback(() => { setLocalDispatch(null); @@ -528,6 +549,7 @@ function useLocalDispatchState(input: { localDispatch, phase: input.phase, latestRun: input.activeLatestRun, + latestUserMessageId: input.latestUserMessageId, runtime: input.activeThread?.runtime ?? null, hasPendingApproval: input.activePendingApproval !== null, hasPendingUserInput: input.activePendingUserInput !== null, @@ -535,12 +557,12 @@ function useLocalDispatchState(input: { }), [ input.activeLatestRun, + input.latestUserMessageId, input.activePendingApproval, input.activePendingUserInput, input.activeThread?.runtime, input.phase, input.threadError, - latestUserMessageId, localDispatch, ], ); @@ -555,10 +577,13 @@ function useLocalDispatchState(input: { ? active : { ...active, preparingWorktree }; } - return createLocalDispatchSnapshot(input.activeThread, options); + return createLocalDispatchSnapshot(input.activeThread, { + ...options, + latestUserMessageId: input.latestUserMessageId, + }); }); }, - [input.activeThread, serverAcknowledgedLocalDispatch], + [input.activeThread, input.latestUserMessageId, serverAcknowledgedLocalDispatch], ); return { @@ -641,7 +666,6 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); - const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : draftThread @@ -1011,7 +1035,6 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane }: PersistentThreadTerminalPanelProps) { const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); - const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : draftThread @@ -1166,8 +1189,6 @@ function ChatViewContent(props: ChatViewProps) { forceExpandedMobileComposer = false, } = props; const draftId = routeKind === "draft" ? props.draftId : null; - const threadSyncPhase = routeKind === "server" ? (props.threadSyncPhase ?? null) : null; - const threadDetailLoading = threadSyncPhase === "loading"; const handleNewThread = useNewThreadHandler(); const routeThreadRef = useMemo( () => scopeThreadRef(environmentId, threadId), @@ -1220,14 +1241,21 @@ function ChatViewContent(props: ChatViewProps) { ); const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; - const serverThread = useThreadShell(routeKind === "server" ? routeThreadRef : null); - const serverThreadProjection = useThreadProjection( - routeKind === "server" ? routeThreadRef : null, + const draftThread = useComposerDraftStore((store) => + routeKind === "server" + ? store.getDraftSessionByRef(routeThreadRef) + : draftId + ? store.getDraftSession(draftId) + : null, ); + const serverThread = useThreadShell(routeThreadRef); + const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, { + shellExists: serverThread !== null, + waitForShell: draftThread !== null, + }); + const serverThreadProjection = useThreadProjection(routeThreadDetailRef); const serverProjection = serverThreadProjection?.projection ?? null; - const serverVisibleTurnItems = useThreadVisibleTurnItems( - routeKind === "server" ? routeThreadRef : null, - ); + const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadDetailRef); const committedServerMessageIds = useMemo( () => deriveCommittedServerUserMessageIds(serverVisibleTurnItems), [serverVisibleTurnItems], @@ -1417,7 +1445,7 @@ function ChatViewContent(props: ChatViewProps) { ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const fallbackDraftProject = useProject(fallbackDraftProjectRef); - const localDraftError = activeServerThread + const localDraftError = serverThread ? null : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null); const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null; @@ -1426,7 +1454,7 @@ function ChatViewContent(props: ChatViewProps) { // a failed send would silently disappear on promotion. When both keys hold // an entry, the most recent write wins. useEffect(() => { - if (!activeServerThread || !draftId) { + if (!serverThread || !draftId) { return; } const pendingDraftEntry = localDraftErrorsByDraftId[draftId]; @@ -1455,7 +1483,7 @@ function ChatViewContent(props: ChatViewProps) { [routeThreadKey]: pendingDraftEntry, }; }); - }, [activeServerThread, draftId, localDraftErrorsByDraftId, routeThreadKey]); + }, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]); const localDraftThread = useMemo( () => draftThread @@ -1467,7 +1495,7 @@ function ChatViewContent(props: ChatViewProps) { : undefined, [draftThread, fallbackDraftProject?.defaultModelSelection, threadId], ); - const isServerThread = routeKind === "server" && serverThread !== null; + const isServerThread = serverThread !== null; const activeThread = isServerThread ? serverThread : localDraftThread; const serverLatestRun = useMemo( () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)), @@ -1832,6 +1860,7 @@ function ChatViewContent(props: ChatViewProps) { }); return envs; }, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]); + const hasMultipleEnvironments = logicalProjectEnvironments.length > 1; const openPullRequestDialog = useCallback( (reference?: string) => { if (!canCheckoutPullRequestIntoThread) { @@ -2047,6 +2076,156 @@ function ChatViewContent(props: ChatViewProps) { dismissVersionMismatch(versionMismatchDismissKey); setDismissedVersionMismatchKey(versionMismatchDismissKey); }, [setDismissedVersionMismatchKey, versionMismatchDismissKey]); + const versionMismatchEnvironmentId = + versionMismatch && activeThread ? activeThread.environmentId : null; + const serverUpdateEnvironmentId = activeThread?.environmentId ?? null; + const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig); + const serverUpdateState = useAtomValue( + serverEnvironment.updateStateAtom(serverUpdateEnvironmentId), + ); + const systemComposerBannerItems = useMemo(() => { + const items: ComposerBannerStackItem[] = []; + const updateRunning = serverUpdateState.status === "running"; + const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null; + const environmentReconnecting = + unavailableConnection !== null && + (unavailableConnection.phase === "connecting" || + unavailableConnection.phase === "reconnecting"); + // Reconnecting to a version-skewed server with no update in flight + // usually means the server is restarting mid-update and a refresh wiped + // the in-memory update state. Fold the reconnect and version banners + // into one calm line instead of stacking "Failed to connect" on + // "versions differ". A failed update never folds: its error and retry + // action must stay visible. + const reconnectingThroughVersionSkew = + serverUpdateState.status === "idle" && environmentReconnecting && versionMismatch !== null; + // While an update runs, transient connect blips are expected (the server + // restarts) and the update banner already shows progress. Hard failure + // phases still surface so the Reconnect action stays reachable. + const suppressUnavailableBanner = updateRunning && environmentReconnecting; + if (activeEnvironmentUnavailableState && unavailableConnection && !suppressUnavailableBanner) { + if (reconnectingThroughVersionSkew) { + items.push({ + id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`, + variant: "default", + icon: ( +
-
-
-
-
-
-
+
+ {isDraftHeroState ? ( +
+
+ +
+ +
+ ) : ( + + )} {isServerThread && activeThread ? ( )} - selectGitScope("branch")}> + selectGitScope("branch")} + > Branch changes {selectedRunId === null && selectedGitScope === "branch" && ( @@ -779,17 +786,7 @@ export default function DiffPanel({ selectGitScope("branch")} - > - Branch changes - - selectTurn(summary.runId)}> + selectTurn(summary.runId)} + > Turn {turnCount} {formatShortTimestamp(summary.completedAt, settings.timestampFormat)} diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 3bcf55605b..2159205569 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1048,9 +1048,6 @@ export default function GitActionsControl({ ? store.getDraftThreadByRef(activeThreadRef) : null, ); - const activeServerThread = useThread(activeThreadRef, { - waitForShell: activeDraftThread !== null, - }); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false); const [dialogCommitMessage, setDialogCommitMessage] = useState(""); diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 85afc9f235..c4b8b6a16b 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -392,7 +392,11 @@ export default function ProjectScriptsControl({ ) : ( )} - + setActionsMenuOpen({ scripts: open, imports: false })} + > + ) : importableScripts.length > 0 ? ( + setActionsMenuOpen({ scripts: false, imports: open })} + > + }> + + + Add action + + + + + {importMenuItems} + + + Add action + + + ) : ( { }); describe("resolveSidebarV2Status", () => { - const session = { - threadId: ThreadId.make("thread-1"), + const runtime = { status: "running" as const, - providerName: "Codex", + activeRunId: null, providerInstanceId: ProviderInstanceId.make("codex"), - runtimeMode: DEFAULT_RUNTIME_MODE, - activeTurnId: "turn-1" as never, + providerName: "Codex", lastError: null, updatedAt: "2026-03-09T10:00:00.000Z", }; - const idle = { hasPendingApprovals: false, hasPendingUserInput: false }; + const idle = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null }; - it("prioritizes approval over a running session", () => { - expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe( + it("prioritizes approval over a running runtime", () => { + expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, runtime })).toBe( "approval", ); }); - it("prioritizes awaiting input over a running session, below approval", () => { - expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input"); + it("prioritizes awaiting input over a running runtime, below approval", () => { + expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, runtime })).toBe("input"); expect( resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, hasPendingUserInput: true, - session, + runtime, }), ).toBe("approval"); }); - it("reports working for running and starting sessions", () => { - expect(resolveSidebarV2Status({ ...idle, session })).toBe("working"); + it("reports working for running and starting runtimes", () => { + expect(resolveSidebarV2Status({ ...idle, runtime })).toBe("working"); expect( resolveSidebarV2Status({ ...idle, - session: { ...session, status: "starting" as const }, + runtime: { ...runtime, status: "starting" as const }, }), ).toBe("working"); }); - it("reports failed only while the session status is error", () => { + it("reports failed only while the latest run failed", () => { expect( resolveSidebarV2Status({ ...idle, - session: { ...session, status: "error" as const, lastError: "boom" }, + runtime: { ...runtime, status: "failed" as const, lastError: "boom" }, }), ).toBe("failed"); expect( resolveSidebarV2Status({ ...idle, - session: { ...session, status: "stopped" as const, lastError: "persisted" }, + runtime: { ...runtime, status: "completed" as const, lastError: "persisted" }, }), ).toBe("ready"); expect( resolveSidebarV2Status({ ...idle, - session: { ...session, status: "ready" as const, lastError: "persisted" }, + runtime: { ...runtime, status: "idle" as const, lastError: "persisted" }, }), ).toBe("ready"); }); - it("defaults to ready with no session", () => { - expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready"); + it("defaults to ready with no runtime", () => { + expect(resolveSidebarV2Status(idle)).toBe("ready"); }); }); @@ -831,13 +829,13 @@ describe("sortSettledThreadsForSidebarV2", () => { id: string; settledAt?: string | null; latestUserMessageAt?: string | null; - latestTurn?: OrchestrationLatestTurn | null; + latestRun?: Thread["latestRun"]; updatedAt?: string; }) => ({ id: input.id, settledAt: input.settledAt ?? null, latestUserMessageAt: input.latestUserMessageAt ?? null, - latestTurn: input.latestTurn ?? null, + latestRun: input.latestRun ?? null, updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z", }); @@ -877,7 +875,7 @@ describe("sortSettledThreadsForSidebarV2", () => { settled({ id: "completed-later", latestUserMessageAt: "2026-03-09T10:00:00.000Z", - latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }), + latestRun: makeLatestRun({ completedAt: "2026-03-09T10:30:00.000Z" }), }), ]); @@ -895,40 +893,38 @@ describe("sortSettledThreadsForSidebarV2", () => { }); describe("resolveWorkingStartedAt", () => { - const session = { - threadId: ThreadId.make("thread-1"), + const runtime = { status: "running" as const, providerName: "Codex", providerInstanceId: ProviderInstanceId.make("codex"), - runtimeMode: DEFAULT_RUNTIME_MODE, - activeTurnId: "turn-1" as never, + activeRunId: RunId.make("run-1"), lastError: null, updatedAt: "2026-03-09T10:02:00.000Z", }; - it("uses the running turn's start time", () => { + it("uses the running run's start time", () => { expect( resolveWorkingStartedAt({ - latestTurn: makeLatestTurn({ completedAt: null }), - session, + latestRun: makeLatestRun({ completedAt: null }), + runtime, }), ).toBe("2026-03-09T10:00:00.000Z"); }); - it("uses the request time while a turn awaits adoption", () => { + it("uses the request time while a run awaits adoption", () => { expect( resolveWorkingStartedAt({ - latestTurn: makeLatestTurn({ startedAt: null, completedAt: null }), - session, + latestRun: makeLatestRun({ startedAt: null, completedAt: null }), + runtime, }), ).toBe("2026-03-09T10:00:00.000Z"); }); - it("falls back to the session transition when the latest turn already completed", () => { + it("falls back to the runtime transition when the latest run already completed", () => { expect( resolveWorkingStartedAt({ - latestTurn: makeLatestTurn(), - session, + latestRun: makeLatestRun(), + runtime, }), ).toBe("2026-03-09T10:02:00.000Z"); }); @@ -936,14 +932,14 @@ describe("resolveWorkingStartedAt", () => { it("skips a malformed startedAt instead of returning it", () => { expect( resolveWorkingStartedAt({ - latestTurn: makeLatestTurn({ startedAt: "not-a-date", completedAt: null }), - session, + latestRun: makeLatestRun({ startedAt: "not-a-date", completedAt: null }), + runtime, }), ).toBe("2026-03-09T10:00:00.000Z"); }); - it("returns null with neither a running turn nor a session", () => { - expect(resolveWorkingStartedAt({ latestTurn: null, session: null })).toBeNull(); + it("returns null with neither a running run nor a runtime", () => { + expect(resolveWorkingStartedAt({ latestRun: null, runtime: null })).toBeNull(); }); }); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index f76f18fdd5..2ed62235f0 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -50,6 +50,53 @@ type LogicalSidebarProject = SidebarProject & { export type ThreadTraversalDirection = "previous" | "next"; +export async function archiveSelectedThreadEntries< + TEntry extends { readonly threadKey: string }, + TResult extends { readonly _tag: "Success" | "Failure" }, +>(input: { + entries: readonly TEntry[]; + archive: (entry: TEntry, onArchived: () => void) => Promise; +}): Promise<{ + archivedThreadKeys: readonly string[]; + mutationFailure: Extract | null; + followupFailures: readonly Extract[]; +}> { + const archivedThreadKeys: string[] = []; + const followupFailures: Extract[] = []; + + for (const entry of input.entries) { + let didArchive = false; + const result = await input.archive(entry, () => { + didArchive = true; + }); + if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey); + if (result._tag === "Success") continue; + const failure = result as Extract; + if (didArchive) { + followupFailures.push(failure); + continue; + } + return { archivedThreadKeys, mutationFailure: failure, followupFailures }; + } + + return { archivedThreadKeys, mutationFailure: null, followupFailures }; +} + +export function buildMultiSelectThreadContextMenuItems(input: { + count: number; + hasRunningThread: boolean; +}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] { + return [ + { id: "mark-unread", label: `Mark unread (${input.count})` }, + { + id: "archive", + label: `Archive (${input.count})`, + disabled: input.hasRunningThread, + }, + { id: "delete", label: `Delete (${input.count})`, destructive: true }, + ]; +} + export function isSidebarSubagentThread(thread: Pick): boolean { return thread.lineage.relationshipToParent === "subagent"; } @@ -80,6 +127,24 @@ export function getSidebarForkParentThreadId( : thread.lineage.parentThreadId; } +export function buildBulkTitleRegenerationContextMenuItem(input: { + supportedCount: number; + actionableCount: number; +}): ContextMenuItem<"regenerate-title"> | null { + if (input.supportedCount === 0) return null; + if (input.actionableCount === 0) { + return { + id: "regenerate-title", + label: `Regenerating… (${input.supportedCount})`, + disabled: true, + }; + } + return { + id: "regenerate-title", + label: `Regenerate titles (${input.actionableCount})`, + }; +} + export interface ThreadStatusPill { label: | "Working" @@ -420,7 +485,11 @@ export type SidebarV2Status = "approval" | "input" | "working" | "monitoring" | type SidebarV2StatusInput = Pick< SidebarThreadSummary, +<<<<<<< HEAD "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness" +======= + "hasPendingApprovals" | "hasPendingUserInput" | "runtime" +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) >; export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status { @@ -430,12 +499,19 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S if (thread.hasPendingUserInput) { return "input"; } - if (thread.session?.status === "running" || thread.session?.status === "starting") { + if ( + thread.runtime !== null && + ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status) + ) { return "working"; } +<<<<<<< HEAD // A failed session outranks lingering background liveness: the user must // see the failure, not a stale Working (review finding). if (thread.session?.status === "error") { +======= + if (thread.runtime?.status === "failed") { +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) return "failed"; } // Background work outlives the turn: fleets read as working; monitoring @@ -512,13 +588,13 @@ export function searchSidebarThreadsByTitle; /** The timestamp a settled row sorts and labels by: settledAt when stamped (explicit settles), otherwise last activity — the same candidates threadLastActivityAt feeds the auto-settle window (user message plus all - latestTurn stamps), so a thread whose last activity was a turn completion + latestRun stamps), so a thread whose last activity was a run completion doesn't sort by an older message time. updatedAt is the final net. */ export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null { const settledAt = firstValidTimestamp(thread.settledAt); @@ -527,9 +603,9 @@ export function resolveSettledTimestamp(thread: SettledTimestampInput): string | let latestMs = Number.NEGATIVE_INFINITY; for (const candidate of [ thread.latestUserMessageAt, - thread.latestTurn?.requestedAt, - thread.latestTurn?.startedAt, - thread.latestTurn?.completedAt, + thread.latestRun?.requestedAt, + thread.latestRun?.startedAt, + thread.latestRun?.completedAt, ]) { if (candidate == null) continue; const parsed = Date.parse(candidate); @@ -560,13 +636,13 @@ export function sortSettledThreadsForSidebarV2< last transition when the turn projection lags behind. Malformed timestamps fall through to the next candidate, not just missing ones. */ export function resolveWorkingStartedAt( - thread: Pick, + thread: Pick, ): string | null { - const turn = thread.latestTurn; - if (turn && turn.completedAt === null) { - return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt); + const run = thread.latestRun; + if (run && run.completedAt === null) { + return firstValidTimestamp(run.startedAt, run.requestedAt, thread.runtime?.updatedAt); } - return firstValidTimestamp(thread.session?.updatedAt); + return firstValidTimestamp(thread.runtime?.updatedAt); } export function formatWorkingDurationLabel(elapsedMs: number): string { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8aaf7d813a..2dec17496f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -171,6 +171,8 @@ import { import { useThreadSelectionStore } from "../threadSelectionStore"; import { openCommandPalette } from "../commandPaletteBus"; import { + archiveSelectedThreadEntries, + buildMultiSelectThreadContextMenuItems, getSidebarForkParentThreadId, getSidebarThreadIdsToPrewarm, isSidebarSubagentThread, @@ -1805,7 +1807,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; }); const hasRunningThread = selectedThreadEntries.some( - ({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null, + ({ thread }) => thread.runtime?.status === "running" && thread.runtime.activeRunId !== null, ); const clicked = await api.contextMenu.show( diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index 0dfd88d88e..06015a7a03 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -120,6 +120,7 @@ import { resolveSidebarV2Status, resolveThreadLastVisitedAt, resolveWorkingStartedAt, + searchSidebarThreadsByTitle, shouldNavigateAfterProjectRemoval, sortSidebarV2ProjectGroups, sortSettledThreadsForSidebarV2, @@ -304,7 +305,7 @@ function SidebarV2ThreadTooltip({
{modelLabel}
@@ -321,7 +322,7 @@ function SidebarV2ThreadTooltip({
) : null} - {thread.session?.lastError ? ( + {thread.runtime?.lastError ? (
Error occurred
@@ -452,6 +453,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { [thread.environmentId, thread.id], ); const threadKey = scopedThreadKey(threadRef); + const isRegeneratingTitle = thread.titleRegeneration != null; const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); @@ -557,7 +559,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { onChangeRequestState(threadKey, prState); }, [onChangeRequestState, prState, threadKey]); - const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; + const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const driverKind = providerEntry?.driverKind ?? null; const selectedModel = providerEntry?.models.find( @@ -1064,7 +1066,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { @@ -1119,7 +1121,7 @@ const SidebarV2SearchResultRow = memo(function SidebarV2SearchResultRow(props: { activeThreadBranch: thread.branch, currentGitBranch: gitStatus.data?.refName ?? null, }); - const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; + const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const driverKind = providerEntry?.driverKind ?? null; const selectedModel = providerEntry?.models.find( @@ -2512,6 +2514,24 @@ export default function SidebarV2() { case "mark-unread": markThreadUnread(threadRef); return; + case "copy-path": + if (!threadWorkspacePath) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Path unavailable", + description: "This thread does not have a workspace path to copy.", + }), + ); + return; + } + copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); + return; + case "copy-branch": + if (thread.branch) { + copyBranchToClipboard(thread.branch, { branch: thread.branch }); + } + return; case "delete": { if (confirmThreadDelete) { const confirmed = await settlePromise(() => diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx index ec24a56c4d..83e75c2177 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.test.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.test.tsx @@ -8,7 +8,7 @@ describe("ChangedFilesCard", () => { it("keeps its compact header sticky while preserving singular labels", () => { const markup = renderToStaticMarkup( { it("renders a scope and representative-file preview for a large latest change", () => { const markup = renderToStaticMarkup( { it("keeps older collapsed changes to a one-line receipt", () => { const markup = renderToStaticMarkup(
- - + {expanded ? ( + + + } + > + {allDirectoriesExpanded ? ( + + ) : ( + + )} + + + {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"} + + + ) : null} + + onOpenTurnDiff(runId, files[0]?.path)} + /> + } + > + + Open diff + + Open the full diff +
{expanded ? ( @@ -149,7 +177,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { type="button" title={file.path} className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" - onClick={() => onOpenTurnDiff(turnId, file.path)} + onClick={() => onOpenTurnDiff(runId, file.path)} > void }, dispatchMode?: ComposerDispatchMode) => { + if (noProviderAvailable) { + event?.preventDefault(); + return; + } + // A send while a pasted image is still compressing would strand that + // image: the turn snapshot wouldn't include it, and it would surface + // in the *next* draft instead. Only oversized images hit this — small + // files clear the pending counter within a microtask. + if (activeThreadId && (pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) { + event?.preventDefault(); + toastManager.add({ + type: "info", + title: "Still compressing a pasted image.", + description: "Send again once its thumbnail appears.", + }); + return; + } onSend(event, dispatchMode ?? resolveComposerDispatchMode({ phase, queueModifier: false })); if (shouldBlurMobileComposerOnSubmit()) { blurMobileComposerAfterSend(); } }, - [blurMobileComposerAfterSend, onSend, phase, shouldBlurMobileComposerOnSubmit], + [ + activeThreadId, + blurMobileComposerAfterSend, + noProviderAvailable, + onSend, + phase, + shouldBlurMobileComposerOnSubmit, + ], ); const expandMobileComposer = useCallback(() => { if (composerBlurFrameRef.current !== null) { @@ -1962,7 +1978,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return true; } } - if (key === "Enter" && !event.shiftKey) { + if ( + key === "Enter" && + shouldSubmitComposerOnEnter({ isMobileViewport, shiftKey: event.shiftKey }) + ) { submitComposer( undefined, resolveComposerDispatchMode({ @@ -2861,7 +2880,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showPlanFollowUpPrompt={false} promptHasText={false} isSendBusy={isSendBusy} - sendDisabledReason={sendDisabledReason} isConnecting={isConnecting} isEnvironmentUnavailable={ environmentUnavailable !== null || @@ -3146,7 +3164,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showPlanFollowUpPrompt={false} promptHasText={false} isSendBusy={isSendBusy} - sendDisabledReason={sendDisabledReason} isConnecting={isConnecting} isEnvironmentUnavailable={ environmentUnavailable !== null || @@ -3284,7 +3301,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt} promptHasText={prompt.trim().length > 0} isSendBusy={isSendBusy} - sendDisabledReason={sendDisabledReason} isConnecting={isConnecting} isEnvironmentUnavailable={ environmentUnavailable !== null || diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 073e280f7c..a53853f23c 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -1,16 +1,26 @@ +import { type EnvironmentId } from "@t3tools/contracts"; import { memo } from "react"; import { cn } from "~/lib/utils"; +import { ProjectFavicon } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; interface ChatHeaderProps { + activeThreadEnvironmentId: EnvironmentId; activeThreadTitle: string; + activeProjectName: string | undefined; + activeProjectCwd: string | null; rightPanelOpen: boolean; + onNewThreadInProject: () => void; } export const ChatHeader = memo(function ChatHeader({ + activeThreadEnvironmentId, activeThreadTitle, + activeProjectName, + activeProjectCwd, rightPanelOpen, + onNewThreadInProject, }: ChatHeaderProps) { return (
+ {/* The project always leads the header: knowing which project a + thread lives in is priority zero, and the thread title alone + doesn't answer it. */} + {activeProjectName ? ( + + + + } + > + + {activeProjectName} + + New thread in {activeProjectName} + + + / + + + ) : null} - } - onToggleInteractionMode={vi.fn()} - onTogglePlanSidebar={vi.fn()} - onRuntimeModeChange={vi.fn()} - />, - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -describe("CompactComposerControlsMenu", () => { - afterEach(() => { - document.body.innerHTML = ""; - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("shows fast mode controls for Opus", async () => { - await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("off"); - expect(text).toContain("on"); - }); - }); - - it("hides fast mode controls for non-Opus Claude models", async () => { - await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").not.toContain("Fast Mode"); - }); - }); - - it("shows only the provided effort options", async () => { - await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Low"); - expect(text).toContain("Medium"); - expect(text).toContain("High"); - expect(text).not.toContain("Max"); - expect(text).toContain("Ultrathink"); - }); - }); - - it("shows a Claude thinking on/off section for Haiku", async () => { - await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-haiku-4-5", - options: { thinking: true }, - }, - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Thinking"); - expect(text).toContain("On (default)"); - expect(text).toContain("Off"); - }); - }); - - it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { - await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { effort: "high" }, - }, - prompt: "Ultrathink:\nInvestigate this", - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Effort"); - expect(text).not.toContain("ultrathink"); - }); - }); - - it("warns when ultrathink appears in prompt body text", async () => { - await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { effort: "high" }, - }, - prompt: "Ultrathink:\nplease ultrathink about this problem", - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain( - 'Your prompt contains "ultrathink" in the text. Remove it to change effort.', - ); - }); - }); - - it("can hide the interaction mode section", async () => { - const host = document.createElement("div"); - document.body.append(host); - const screen = await render( - , - { container: host }, - ); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).not.toContain("Mode"); - expect(text).not.toContain("Chat"); - expect(text).not.toContain("Plan"); - expect(text).toContain("Access"); - expect(text).toContain("Supervised"); - expect(text).toContain("Full access"); - }); - - await screen.unmount(); - host.remove(); - }); -}); diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx index fbaf81bc9f..f0a0ada7f0 100644 --- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx @@ -1,4 +1,4 @@ -import { ApprovalRequestId } from "@t3tools/contracts"; +import { RuntimeRequestId } from "@t3tools/contracts"; import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vite-plus/test"; @@ -10,10 +10,11 @@ describe("ComposerPendingApprovalPanel", () => { const markup = renderToStaticMarkup( , diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx index aca95868b1..28d9b8a150 100644 --- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx @@ -38,6 +38,18 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova restart the run to continue.

) : null} + {approval.detail ? ( +
+

{detailLabel}

+
+            {approval.detail}
+          
+
+ ) : null}
); }); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 3aefb39e12..82fb1de28a 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -21,7 +21,6 @@ interface ComposerPrimaryActionsProps { showPlanFollowUpPrompt: boolean; promptHasText: boolean; isSendBusy: boolean; - sendDisabledReason: string | null; isConnecting: boolean; isEnvironmentUnavailable: boolean; isPreparingWorktree: boolean; @@ -61,7 +60,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ showPlanFollowUpPrompt, promptHasText, isSendBusy, - sendDisabledReason, isConnecting, isEnvironmentUnavailable, isPreparingWorktree, @@ -74,7 +72,14 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ const pointerFocusProps = preserveComposerFocusOnPointerDown ? { onPointerDown: preventPointerFocus } : undefined; +<<<<<<< HEAD const isSendDisabled = sendDisabledReason !== null; +======= + const environmentIdentificationMode = useEnvironmentIdentificationMode(); + const stageBackdropVariant = useSidebarStageBackdropVariant( + environmentIdentificationMode === "artwork", + ); +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) if (pendingAction) { return ( @@ -157,7 +162,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8", )} {...pointerFocusProps} - disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} > {isConnecting || isSendBusy ? "Sending..." : "Refine"} @@ -171,7 +176,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ size="sm" className="h-9 rounded-l-full rounded-r-none bg-message-action px-4 text-message-action-foreground hover:bg-message-action-hover sm:h-8" {...pointerFocusProps} - disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} > {isConnecting || isSendBusy ? "Sending..." : "Implement"} @@ -184,7 +189,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ className="h-9 rounded-l-none rounded-r-full border-l-message-action-foreground/20 bg-message-action px-2 text-message-action-foreground hover:bg-message-action-hover sm:h-8" aria-label="Implementation actions" {...pointerFocusProps} - disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} /> } > @@ -192,7 +197,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ void onImplementPlanInNewThread()} > Implement in a new thread @@ -211,13 +216,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ "bg-message-action enabled:shadow-message-action/24 hover:bg-message-action-hover", )} {...pointerFocusProps} - disabled={ - isSendBusy || - isSendDisabled || - isConnecting || - isEnvironmentUnavailable || - !hasSendableContent - } + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent} aria-label={ isEnvironmentUnavailable ? "Environment disconnected" diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index ac41f566ac..47a157f9c5 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1130,67 +1130,6 @@ describe("deriveMessagesTimelineRows", () => { ]); }); - it("does not fold the session's running turn when latestTurn regresses", () => { - const rows = deriveMessagesTimelineRows({ - timelineEntries: [ - { - id: "previous-work-entry", - kind: "work", - createdAt: "2026-01-01T00:00:05Z", - entry: { - id: "previous-work", - createdAt: "2026-01-01T00:00:05Z", - turnId: "turn-1" as never, - label: "Read files", - tone: "tool" as const, - }, - }, - { - id: "user-followup-entry", - kind: "message", - createdAt: "2026-01-01T00:01:00Z", - message: { - id: "user-followup" as never, - role: "user", - text: "continue", - turnId: null, - createdAt: "2026-01-01T00:01:00Z", - updatedAt: "2026-01-01T00:01:00Z", - streaming: false, - }, - }, - { - id: "running-work-entry", - kind: "work", - createdAt: "2026-01-01T00:01:05Z", - entry: { - id: "running-work", - createdAt: "2026-01-01T00:01:05Z", - turnId: "turn-2" as never, - label: "Searched files", - tone: "tool" as const, - }, - }, - ], - latestTurn: { - turnId: "turn-1" as never, - state: "completed", - startedAt: "2026-01-01T00:00:00Z", - completedAt: "2026-01-01T00:00:25Z", - }, - runningTurnId: "turn-2" as never, - isWorking: true, - activeTurnStartedAt: "2026-01-01T00:01:00Z", - turnDiffSummaryByAssistantMessageId: new Map(), - revertTurnCountByUserMessageId: new Map(), - }); - - expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.turnId)).toEqual([ - "turn-1", - ]); - expect(rows.map((row) => row.id)).toContain("running-work-entry"); - }); - it("only shows assistant metadata on the terminal assistant message", () => { const rows = deriveMessagesTimelineRows({ timelineEntries: [ @@ -1277,7 +1216,7 @@ describe("deriveMessagesTimelineRows", () => { expect(assistantRow?.showAssistantCopyButton).toBe(false); }); - it("models work log overflow expansion as inserted list rows", () => { + it("groups contiguous work log entries into one timeline row", () => { const timelineEntries = [ { id: "work-entry-1", @@ -1324,27 +1263,17 @@ describe("deriveMessagesTimelineRows", () => { turnDiffSummaryByAssistantMessageId: new Map(), revertTurnCountByUserMessageId: new Map(), }; - const collapsedRows = deriveMessagesTimelineRows(baseInput); - const expandedRows = deriveMessagesTimelineRows({ - ...baseInput, - expandedWorkGroupIds: new Set(["work-group:work-entry-1"]), - }); + const rows = deriveMessagesTimelineRows(baseInput); - expect(collapsedRows.map((row) => row.id)).toEqual(["work-3", "work-toggle:work-entry-1"]); - expect(collapsedRows.find((row) => row.kind === "work-toggle")).toMatchObject({ - groupId: "work-group:work-entry-1", - hiddenCount: 2, - expanded: false, - onlyToolEntries: true, - }); - expect(expandedRows.map((row) => row.id)).toEqual([ - "work-1", - "work-2", - "work-3", - "work-toggle:work-entry-1", - ]); - expect(expandedRows.find((row) => row.kind === "work-toggle")).toMatchObject({ - expanded: true, + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + kind: "work", + id: "work-entry-1", + groupedEntries: [ + expect.objectContaining({ id: "work-1" }), + expect.objectContaining({ id: "work-2" }), + expect.objectContaining({ id: "work-3" }), + ], }); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index fa95e248ab..49775b0285 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -176,15 +176,6 @@ export type MessagesTimelineRow = createdAt: string; groupedEntries: WorkLogEntry[]; } - | { - kind: "work-toggle"; - id: string; - createdAt: string; - groupId: string; - hiddenCount: number; - expanded: boolean; - onlyToolEntries: boolean; - } | { kind: "turn-fold"; id: string; @@ -363,12 +354,11 @@ function deriveSupersededAttemptFolds( } /** - * The session's running turn is authoritative when latestTurn briefly lags or - * regresses behind it. Otherwise, the latest turn counts as unsettled while it - * is still running (or has not recorded a completion). This is deliberately - * keyed on turn lifecycle rather than transient working state: right after the - * user sends a message, the previous turn is still the "active" one until the - * server creates the new turn, and folding must not flicker through that window. + * The latest turn counts as unsettled while it is still running (or has not + * recorded a completion). This is deliberately keyed on the turn's own + * lifecycle rather than transient working state: right after the user sends + * a message, the previous turn is still the "active" one until the server + * creates the new turn, and folding must not flicker through that window. */ function deriveUnsettledRunId(latestRun: TimelineLatestRun | null): RunId | null { if (!latestRun) { @@ -630,6 +620,7 @@ export function deriveMessagesTimelineRows(input: { groupedEntries.push(nextEntry.entry); cursor += 1; } +<<<<<<< HEAD const visibleGroupedEntries = groupedEntries.filter( (entry) => !workEntryIndicatesToolNeutralStatus(entry), ); @@ -684,6 +675,14 @@ export function deriveMessagesTimelineRows(input: { } } } +======= + nextRows.push({ + kind: "work", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + groupedEntries, + }); +>>>>>>> 0c15987295 (fix: reconcile rebase with latest main) index = cursor - 1; continue; } @@ -805,17 +804,6 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "work": return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries); - case "work-toggle": { - const bw = b as typeof a; - return ( - a.createdAt === bw.createdAt && - a.groupId === bw.groupId && - a.hiddenCount === bw.hiddenCount && - a.expanded === bw.expanded && - a.onlyToolEntries === bw.onlyToolEntries - ); - } - case "message": { const bm = b as typeof a; return ( diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 84d61b54f5..c3a36904fc 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1,4 +1,4 @@ -import { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; +import { CheckpointRef, EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; import { createRef, type ReactNode, type Ref } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; @@ -246,13 +246,13 @@ describe("MessagesTimeline", () => { it("keeps assistant changed-files headers sticky below the thread header", () => { const assistantMessageId = MessageId.make("message-assistant-with-files"); - const turnId = TurnId.make("turn-with-files"); + const runId = RunId.make("run-with-files"); const markup = renderToStaticMarkup( { id: assistantMessageId, role: "assistant", text: "Updated the fixture.", - turnId, + runId, createdAt: MESSAGE_CREATED_AT, updatedAt: MESSAGE_CREATED_AT, streaming: false, @@ -277,7 +277,7 @@ describe("MessagesTimeline", () => { [ assistantMessageId, { - turnId, + runId, checkpointTurnCount: 1, checkpointRef: CheckpointRef.make("checkpoint-with-files"), status: "ready", diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c829b08699..9d585ffdd9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -19,6 +19,7 @@ import { use, useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, @@ -26,7 +27,6 @@ import { type MouseEvent, type ReactNode, } from "react"; -import { flushSync } from "react-dom"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { FileDiff } from "@pierre/diffs/react"; import { @@ -49,6 +49,7 @@ import { CheckIcon, ChevronDownIcon, ChevronRightIcon, + ChevronUpIcon, CircleAlertIcon, EyeIcon, GitForkIcon, @@ -73,6 +74,7 @@ import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation"; import { MessageCopyButton } from "./MessageCopyButton"; import { computeStableMessagesTimelineRows, + MAX_VISIBLE_WORK_LOG_ENTRIES, deriveMessagesTimelineRows, normalizeCompactToolLabel, resolveTimelineToolPresentation, @@ -86,6 +88,7 @@ import { resolveTimelineMinimapTopPercent, type StableMessagesTimelineRowsState, type MessagesTimelineRow, + TIMELINE_MINIMAP_MIN_ITEMS, type TimelineLatestRun, } from "./MessagesTimeline.logic"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; @@ -165,7 +168,7 @@ interface TimelineRowActivityState { isWorking: boolean; isRevertingCheckpoint: boolean; activeTurnInProgress: boolean; - latestTurnId: TurnId | null; + latestRunId: RunId | null; } const TimelineRowCtx = createContext(null!); @@ -269,16 +272,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ const [expandedAttemptIds, setExpandedAttemptIds] = useState>( new Set(), ); + const [minimapStripMap] = useState(() => new Map()); - // Toggling a fold inserts/removes rows between the fold row and the final - // message — everything above the trigger is unchanged, so the trigger stays - // put as long as the list doesn't re-anchor. maintainScrollAtEnd would do - // exactly that (pin the bottom content when row data changes while scrolled - // to the end), yanking the trigger out of view. Suppress it for the frames - // in which the toggle's data change and item measurements settle. - const [foldToggleSettling, setFoldToggleSettling] = useState(false); const onToggleTurnFold = useCallback((runId: RunId) => { - setFoldToggleSettling(true); setExpandedRunIds((existing) => { const next = new Set(existing); if (next.has(runId)) { @@ -290,7 +286,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }); }, []); const onToggleAttemptFold = useCallback((attemptId: RunAttemptId) => { - setFoldToggleSettling(true); setExpandedAttemptIds((existing) => { const next = new Set(existing); if (next.has(attemptId)) { @@ -301,33 +296,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return next; }); }, []); - useEffect(() => { - if (!foldToggleSettling) { - return; - } - let secondFrameId: number | null = null; - const firstFrameId = window.requestAnimationFrame(() => { - secondFrameId = window.requestAnimationFrame(() => { - setFoldToggleSettling(false); - }); - - if (anchorBottomBeforeToggle === null || !anchorElement) { - return; - } - - const delta = anchorElement.getBoundingClientRect().bottom - anchorBottomBeforeToggle; - if (Math.abs(delta) < 0.5) { - return; - } - - const list = listRef.current; - const currentScroll = list?.getState?.().scroll; - if (list && typeof currentScroll === "number") { - list.scrollToOffset({ offset: currentScroll + delta, animated: false }); - } - }, - [listRef], - ); // An in-session interrupt leaves its turn expanded so the user keeps their // place; the next turn (or a reload, since this is local state) folds it. @@ -415,6 +383,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({ ? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged } : undefined; }, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]); + const maintainVisibleContentPosition = useMemo( + () => ({ + data: true, + size: false, + }), + [], + ); const handleScroll = useCallback(() => { const state = listRef.current?.getState?.(); @@ -527,9 +502,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ isWorking, isRevertingCheckpoint, activeTurnInProgress, - latestTurnId: latestTurn?.turnId ?? null, + latestRunId: latestRun?.runId ?? null, }), - [activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId], + [activeTurnInProgress, isRevertingCheckpoint, isWorking, latestRun?.runId], ); const listHeader = useMemo( () => @@ -565,6 +540,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ ); if (rows.length === 0 && !isWorking && parentThreadLink === null) { + if (hideEmptyPlaceholder) { + return null; + } return (

@@ -597,14 +575,20 @@ export const MessagesTimeline = memo(function MessagesTimeline({ maintainScrollAtEnd={false} maintainVisibleContentPosition={maintainVisibleContentPosition} onScroll={handleScroll} - className="messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]" - ListHeaderComponent={listHeader} + className={cn( + "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5", + topFadeEnabled && "chat-timeline-scroll-fade", + )} + ListHeaderComponent={ + topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : listHeader + } ListFooterComponent={TIMELINE_LIST_FOOTER} /> { onManualNavigation(); @@ -946,7 +930,6 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time data-message-role={row.kind === "message" ? row.message.role : undefined} > {row.kind === "work" ? : null} - {row.kind === "work-toggle" ? : null} {row.kind === "turn-fold" ? : null} {row.kind === "attempt-fold" ? : null} {row.kind === "message" && row.message.role === "user" ? : null} @@ -992,7 +975,7 @@ function UserTimelineRow({ row }: { row: Extract ) : null} -

+
{regularImages.length > 0 && (
{regularImages.map((image: NonNullable[number]) => ( @@ -1565,17 +1548,26 @@ function WorkingTimer({ createdAt }: { createdAt: string }) { // re-render only the affected row, not the entire list. // --------------------------------------------------------------------------- -/** Renders one or more already-derived work log rows. Overflow expansion is modeled as LegendList data. */ +/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */ const WorkGroupSection = memo(function WorkGroupSection({ groupedEntries, }: { groupedEntries: Extract["groupedEntries"]; }) { const { workspaceRoot } = use(TimelineRowCtx); + const [isExpanded, setIsExpanded] = useState(false); + const sectionRef = useRef(null); + const anchorBottomBeforeToggleRef = useRef(null); const nonEmptyEntries = useMemo( () => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)), [groupedEntries], ); + const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleEntries = + hasOverflow && !isExpanded + ? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) + : nonEmptyEntries; + const hiddenCount = nonEmptyEntries.length - visibleEntries.length; const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry)); const groupLabel = onlyToolEntries ? nonEmptyEntries.length === 1 @@ -1583,17 +1575,49 @@ const WorkGroupSection = memo(function WorkGroupSection({ : `${nonEmptyEntries.length} tool calls` : "Work Log"; + useLayoutEffect(() => { + const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current; + anchorBottomBeforeToggleRef.current = null; + + if (anchorBottomBeforeToggle === null) { + return; + } + + const section = sectionRef.current; + if (!section) { + return; + } + + const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle; + if (Math.abs(delta) < 0.5) { + return; + } + + const scroller = findNearestVerticalScroller(section); + if (scroller) { + scroller.scrollTop += delta; + } else { + window.scrollBy(0, delta); + } + }, [isExpanded]); + + const toggleExpanded = () => { + anchorBottomBeforeToggleRef.current = + sectionRef.current?.getBoundingClientRect().bottom ?? null; + setIsExpanded((v) => !v); + }; + if (nonEmptyEntries.length === 0) return null; return ( -
+
{!onlyToolEntries && (

{groupLabel}

)}
- {nonEmptyEntries.map((workEntry) => ( + {visibleEntries.map((workEntry) => ( ))}
+ {hasOverflow && ( + + )}
); }); -function WorkGroupToggleTimelineRow({ - row, -}: { - row: Extract; -}) { - const ctx = use(TimelineRowCtx); - const labelNoun = row.onlyToolEntries - ? row.hiddenCount === 1 - ? "tool call" - : "tool calls" - : row.hiddenCount === 1 - ? "log entry" - : "log entries"; - - return ( - - ); +function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null { + let parent = element.parentElement; + while (parent) { + const { overflowY } = window.getComputedStyle(parent); + if ( + (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") && + parent.scrollHeight > parent.clientHeight + ) { + return parent; + } + parent = parent.parentElement; + } + return null; } /** Subscribes directly to the UI state store for expand/collapse state, @@ -1694,57 +1709,30 @@ function AssistantChangedFilesSectionInner({ resolvedTheme: "light" | "dark"; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { - const allDirectoriesExpanded = useUiStateStore( - (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId] ?? true, + const activity = use(TimelineRowActivityCtx); + const isLatestRun = activity.latestRunId === turnSummary.runId; + const persistedExpanded = useUiStateStore( + (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId], ); const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded); - const [autoExpanded] = useState(() => - shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn), - ); + const [autoExpanded] = useState(() => shouldAutoExpandChangedFiles(checkpointFiles, isLatestRun)); const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded); - const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded); + const expanded = persistedExpanded ?? (isLatestRun && autoExpanded); return ( -
-
-

- Changed files ({changedFileCountLabel}) - {hasNonZeroStat(summaryStat) && ( - <> - • - - - )} -

-
- - -
-
- -
+ + setExpanded(routeThreadKey, turnSummary.runId, nextExpanded) + } + onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)} + onOpenTurnDiff={onOpenTurnDiff} + /> ); } diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 047128265b..4bfd0c59dc 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -261,7 +261,10 @@ export const OpenInPicker = memo(function OpenInPicker({ {primaryOption?.Icon && (