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