fix: reconcile rebase with latest main
This commit is contained in:
1 parent
57d1b26374
commit
290392fac9
240 files changed
+22756
-32833
No files matched your search
@@ -80,16 +80,6 @@ jobs:
|
|||||||
sudo apt-get install -y --no-install-recommends build-essential
|
sudo apt-get install -y --no-install-recommends build-essential
|
||||||
command -v cc
|
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+
|
- name: Setup Vite+
|
||||||
uses: voidzero-dev/setup-vp@v1
|
uses: voidzero-dev/setup-vp@v1
|
||||||
with:
|
with:
|
||||||
|
|||||||
+60
-12
@@ -11,23 +11,62 @@ Object.assign(process.env, repoEnv);
|
|||||||
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
|
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
|
||||||
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
||||||
|
|
||||||
const VARIANT_CONFIG: Record<
|
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
|
||||||
AppVariant,
|
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
|
||||||
{
|
|
||||||
readonly appName: string;
|
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
|
||||||
readonly scheme: string;
|
|
||||||
readonly iosIcon: string;
|
if (
|
||||||
readonly iosBundleIdentifier: string;
|
isIosPersonalTeamBuild &&
|
||||||
readonly androidPackage: string;
|
(!personalTeamBundleIdentifier ||
|
||||||
readonly relyingParty?: string;
|
!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: {
|
development: {
|
||||||
appName: "T3 Code Dev",
|
appName: "T3 Code Dev",
|
||||||
scheme: "t3code-dev",
|
scheme: "t3code-dev",
|
||||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||||
androidPackage: "com.t3tools.t3code.dev",
|
androidPackage: "com.t3tools.t3code.dev",
|
||||||
relyingParty: "clerk.t3.codes",
|
relyingParty: "clerk.t3.codes",
|
||||||
|
assets: DEVELOPMENT_ASSETS,
|
||||||
},
|
},
|
||||||
preview: {
|
preview: {
|
||||||
appName: "T3 Code Preview",
|
appName: "T3 Code Preview",
|
||||||
@@ -35,6 +74,7 @@ const VARIANT_CONFIG: Record<
|
|||||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||||
androidPackage: "com.t3tools.t3code.preview",
|
androidPackage: "com.t3tools.t3code.preview",
|
||||||
relyingParty: "clerk.t3.codes",
|
relyingParty: "clerk.t3.codes",
|
||||||
|
assets: PREVIEW_ASSETS,
|
||||||
},
|
},
|
||||||
production: {
|
production: {
|
||||||
appName: "T3 Code",
|
appName: "T3 Code",
|
||||||
@@ -42,6 +82,7 @@ const VARIANT_CONFIG: Record<
|
|||||||
iosBundleIdentifier: "com.t3tools.t3code",
|
iosBundleIdentifier: "com.t3tools.t3code",
|
||||||
androidPackage: "com.t3tools.t3code",
|
androidPackage: "com.t3tools.t3code",
|
||||||
relyingParty: "clerk.t3.codes",
|
relyingParty: "clerk.t3.codes",
|
||||||
|
assets: RELEASE_ASSETS,
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -140,7 +181,14 @@ const config: ExpoConfig = {
|
|||||||
ios: {
|
ios: {
|
||||||
icon: variant.assets.iosIcon,
|
icon: variant.assets.iosIcon,
|
||||||
supportsTablet: true,
|
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: [
|
associatedDomains: [
|
||||||
`applinks:${variant.relyingParty}`,
|
`applinks:${variant.relyingParty}`,
|
||||||
`webcredentials:${variant.relyingParty}`,
|
`webcredentials:${variant.relyingParty}`,
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
||||||
const threadId = snapshot.thread.id;
|
const threadId = snapshot.projection.thread.id;
|
||||||
const payload = yield* encodeStoredThreadSnapshot({
|
const payload = yield* encodeStoredThreadSnapshot({
|
||||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||||
environmentId,
|
environmentId,
|
||||||
|
|||||||
@@ -2,11 +2,6 @@ import {
|
|||||||
ConnectionPersistenceError,
|
ConnectionPersistenceError,
|
||||||
ConnectionRegistrationStore,
|
ConnectionRegistrationStore,
|
||||||
ConnectionTargetStore,
|
ConnectionTargetStore,
|
||||||
EnvironmentCacheStore,
|
|
||||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
|
||||||
StoredOrchestrationShellSnapshot,
|
|
||||||
StoredOrchestrationThreadSnapshot,
|
|
||||||
decodeOrDiscardOrchestrationCache,
|
|
||||||
registerConnectionInCatalog,
|
registerConnectionInCatalog,
|
||||||
removeConnectionFromCatalog,
|
removeConnectionFromCatalog,
|
||||||
removeCatalogValue,
|
removeCatalogValue,
|
||||||
@@ -18,88 +13,12 @@ import {
|
|||||||
CredentialStore,
|
CredentialStore,
|
||||||
ProfileStore,
|
ProfileStore,
|
||||||
} from "@t3tools/client-runtime/connection";
|
} from "@t3tools/client-runtime/connection";
|
||||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
|
||||||
import * as Context from "effect/Context";
|
import * as Context from "effect/Context";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Option from "effect/Option";
|
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";
|
import * as CatalogStore 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),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
function targetPersistenceError(
|
function targetPersistenceError(
|
||||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
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(
|
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||||
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
||||||
|
|||||||
@@ -120,51 +120,14 @@ interface HomeScreenProps {
|
|||||||
|
|
||||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||||
|
|
||||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||||
switch (thread.runtime?.status) {
|
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
|
||||||
case "running":
|
/**
|
||||||
case "waiting":
|
* Top spacing between the list and the Android custom header. The Android
|
||||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||||
case "completed":
|
* already consumes the top safe-area inset, so the list only needs breathing
|
||||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
* room here.
|
||||||
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),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function deriveEmptyState(props: {
|
function deriveEmptyState(props: {
|
||||||
readonly catalogState: WorkspaceState;
|
readonly catalogState: WorkspaceState;
|
||||||
@@ -799,7 +762,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
|||||||
?.providers.find(
|
?.providers.find(
|
||||||
(provider) =>
|
(provider) =>
|
||||||
provider.instanceId ===
|
provider.instanceId ===
|
||||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||||
)?.driver ?? null
|
)?.driver ?? null
|
||||||
}
|
}
|
||||||
environmentLabel={
|
environmentLabel={
|
||||||
@@ -1045,17 +1008,25 @@ export function HomeScreen(props: HomeScreenProps) {
|
|||||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||||
variant="plain"
|
variant="plain"
|
||||||
/>
|
/>
|
||||||
) : !hasResults ? (
|
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||||
<EmptyState
|
<View className="mt-4 items-center">
|
||||||
title="No threads yet"
|
<ActivityIndicator color={accentColor} />
|
||||||
detail="Create a task to start a new coding runtime."
|
</View>
|
||||||
/>
|
) : null}
|
||||||
) : (
|
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||||
projectGroups.map((group) => {
|
<View className="mt-4">
|
||||||
const isExpanded = expandedProjects.has(group.key);
|
<WorkspaceConnectionStatus
|
||||||
const visibleThreads = isExpanded
|
state={props.catalogState}
|
||||||
? group.threads
|
onPress={props.onOpenEnvironments}
|
||||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
variant="sidebar"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
{connectionStatus}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const listHeader = (
|
const listHeader = (
|
||||||
<>
|
<>
|
||||||
@@ -1091,7 +1062,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
|||||||
detail="Choose another environment or create a new task."
|
detail="Choose another environment or create a new task."
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
|
||||||
)
|
)
|
||||||
) : null;
|
) : null;
|
||||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import type {
|
import {
|
||||||
EnvironmentProject,
|
presentThreadShell,
|
||||||
EnvironmentThreadShell,
|
type EnvironmentProject,
|
||||||
|
type EnvironmentThreadShell,
|
||||||
} from "@t3tools/client-runtime/state/shell";
|
} from "@t3tools/client-runtime/state/shell";
|
||||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||||
|
import * as DateTime from "effect/DateTime";
|
||||||
import { describe, expect, it } from "vite-plus/test";
|
import { describe, expect, it } from "vite-plus/test";
|
||||||
|
|
||||||
import {
|
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 {
|
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||||
return {
|
const threadId = ThreadId.make(id);
|
||||||
environmentId,
|
return presentThreadShell(environmentId, {
|
||||||
id: ThreadId.make(id),
|
id: threadId,
|
||||||
projectId,
|
projectId,
|
||||||
title: `Thread ${id}`,
|
title: `Thread ${id}`,
|
||||||
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
latestTurn: null,
|
activeProviderThreadId: null,
|
||||||
createdAt: "2026-06-01T00:00:00.000Z",
|
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
forkedFrom: null,
|
||||||
archivedAt: null,
|
createdBy: "user",
|
||||||
|
creationSource: "mobile",
|
||||||
|
latestRunId: null,
|
||||||
|
activeRunId: null,
|
||||||
|
status: "idle",
|
||||||
|
pendingRuntimeRequest: null,
|
||||||
|
latestVisibleMessage: null,
|
||||||
settledOverride: null,
|
settledOverride: null,
|
||||||
settledAt: null,
|
settledAt: null,
|
||||||
session: null,
|
|
||||||
latestUserMessageAt: null,
|
latestUserMessageAt: null,
|
||||||
hasPendingApprovals: false,
|
|
||||||
hasPendingUserInput: false,
|
|
||||||
hasActionableProposedPlan: false,
|
hasActionableProposedPlan: false,
|
||||||
};
|
itemCount: 0,
|
||||||
|
visibleItemCount: 0,
|
||||||
|
createdAt: threadTimestamp,
|
||||||
|
updatedAt: threadTimestamp,
|
||||||
|
archivedAt: null,
|
||||||
|
deletedAt: null,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||||
|
|||||||
@@ -6,7 +6,11 @@ import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-searc
|
|||||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vite-plus/test";
|
import { describe, expect, it } from "vite-plus/test";
|
||||||
|
|
||||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
import {
|
||||||
|
buildHomeProjectScopes,
|
||||||
|
buildHomeThreadGroups,
|
||||||
|
sortHomeProjectScopes,
|
||||||
|
} from "./homeThreadList";
|
||||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||||
|
|
||||||
function makeProject(
|
function makeProject(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
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 Cause from "effect/Cause";
|
||||||
import * as Haptics from "expo-haptics";
|
import * as Haptics from "expo-haptics";
|
||||||
import { useCallback, useRef } from "react";
|
import { useCallback, useRef } from "react";
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import * as Haptics from "expo-haptics";
|
import * as Haptics from "expo-haptics";
|
||||||
import { SymbolView } from "expo-symbols";
|
import { SymbolView } from "expo-symbols";
|
||||||
import type { EnvironmentId } from "@t3tools/contracts";
|
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||||
import { useRouter } from "expo-router";
|
import { useNavigation } from "@react-navigation/native";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
|
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
|
||||||
|
|
||||||
import { AppText as Text } from "../../components/AppText";
|
import { AppText as Text } from "../../components/AppText";
|
||||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||||
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
|
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
|
||||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
|
||||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||||
import { threadEnvironment } from "../../state/threads";
|
import { threadEnvironment } from "../../state/threads";
|
||||||
import { useAtomCommand } from "../../state/use-atom-command";
|
import { useAtomCommand } from "../../state/use-atom-command";
|
||||||
@@ -22,7 +21,7 @@ export function ThreadActivityInspector(props: {
|
|||||||
readonly iconColor: ColorValue;
|
readonly iconColor: ColorValue;
|
||||||
readonly workspaceRoot?: string | null;
|
readonly workspaceRoot?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const navigation = useNavigation();
|
||||||
const row = props.activity.projectedItem;
|
const row = props.activity.projectedItem;
|
||||||
const support = useV2ItemSupport({
|
const support = useV2ItemSupport({
|
||||||
environmentId: props.environmentId,
|
environmentId: props.environmentId,
|
||||||
|
|||||||
@@ -92,6 +92,12 @@ export interface ThreadComposerProps {
|
|||||||
readonly connectionState: RemoteClientConnectionState;
|
readonly connectionState: RemoteClientConnectionState;
|
||||||
readonly connectionError: string | null;
|
readonly connectionError: string | null;
|
||||||
readonly environmentLabel: 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 selectedThread: EnvironmentThreadShell;
|
||||||
readonly serverConfig: T3ServerConfig | null;
|
readonly serverConfig: T3ServerConfig | null;
|
||||||
readonly queueCount: number;
|
readonly queueCount: number;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
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 { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||||
import type {
|
import type {
|
||||||
@@ -423,6 +424,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
|||||||
<View className="flex-1" />
|
<View className="flex-1" />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||||
|
{showContent ? (
|
||||||
|
<KeyboardStickyView
|
||||||
|
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||||
|
offset={{ closed: 0, opened: 0 }}
|
||||||
|
>
|
||||||
|
{/* 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. */}
|
||||||
|
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||||
|
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||||
<ThreadQueueControl
|
<ThreadQueueControl
|
||||||
environmentId={props.environmentId}
|
environmentId={props.environmentId}
|
||||||
threadId={props.selectedThread.id}
|
threadId={props.selectedThread.id}
|
||||||
|
|||||||
@@ -80,11 +80,16 @@ import {
|
|||||||
} from "../review/nativeReviewDiffAdapter";
|
} from "../review/nativeReviewDiffAdapter";
|
||||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||||
import { cn } from "../../lib/cn";
|
import { cn } from "../../lib/cn";
|
||||||
import type { LayoutVariant } from "../../lib/layout";
|
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
|
||||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
|
||||||
import { buildThreadRoutePath } from "../../lib/routes";
|
|
||||||
import { uuidv4 } from "../../lib/uuid";
|
import { uuidv4 } from "../../lib/uuid";
|
||||||
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
import {
|
||||||
|
resolveMarkdownFontSizes,
|
||||||
|
resolveNativeMarkdownTypography,
|
||||||
|
scaledTypographyLineHeight,
|
||||||
|
} from "../../lib/appearancePreferences";
|
||||||
|
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||||
|
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||||
|
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
|
||||||
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
||||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||||
import {
|
import {
|
||||||
@@ -150,6 +155,7 @@ export interface ThreadFeedProps {
|
|||||||
readonly contentPresentation: ThreadContentPresentation;
|
readonly contentPresentation: ThreadContentPresentation;
|
||||||
readonly agentLabel: string;
|
readonly agentLabel: string;
|
||||||
readonly latestRun: ThreadFeedLatestRun | null;
|
readonly latestRun: ThreadFeedLatestRun | null;
|
||||||
|
readonly activeWorkStartedAt: string | null;
|
||||||
readonly listRef: RefObject<LegendListRef | null>;
|
readonly listRef: RefObject<LegendListRef | null>;
|
||||||
readonly freeze: SharedValue<boolean>;
|
readonly freeze: SharedValue<boolean>;
|
||||||
readonly anchorMessageId: MessageId | null;
|
readonly anchorMessageId: MessageId | null;
|
||||||
@@ -157,6 +163,7 @@ export interface ThreadFeedProps {
|
|||||||
readonly contentTopInset?: number;
|
readonly contentTopInset?: number;
|
||||||
readonly contentBottomInset?: number;
|
readonly contentBottomInset?: number;
|
||||||
readonly topAccessory?: ReactNode;
|
readonly topAccessory?: ReactNode;
|
||||||
|
readonly contentMaxWidth?: number;
|
||||||
readonly layoutVariant?: LayoutVariant;
|
readonly layoutVariant?: LayoutVariant;
|
||||||
readonly usesAutomaticContentInsets?: boolean;
|
readonly usesAutomaticContentInsets?: boolean;
|
||||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||||
@@ -190,7 +197,7 @@ function AssistantForkButton(props: {
|
|||||||
sourceItemId: props.projectedItem.sourceItemId,
|
sourceItemId: props.projectedItem.sourceItemId,
|
||||||
});
|
});
|
||||||
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
|
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
|
||||||
const router = useRouter();
|
const navigation = useNavigation();
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const canFork = canForkProjectedAssistantItem({
|
const canFork = canForkProjectedAssistantItem({
|
||||||
projectedItem: props.projectedItem,
|
projectedItem: props.projectedItem,
|
||||||
@@ -907,12 +914,13 @@ function renderFeedEntry(
|
|||||||
info: { item: ThreadFeedEntry; index: number },
|
info: { item: ThreadFeedEntry; index: number },
|
||||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||||
readonly copiedRowId: string | null;
|
readonly copiedRowId: string | null;
|
||||||
|
readonly expandedWorkGroups: Record<string, boolean>;
|
||||||
readonly expandedWorkRows: Record<string, boolean>;
|
readonly expandedWorkRows: Record<string, boolean>;
|
||||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||||
readonly unsettledTurnId: RunId | null;
|
readonly unsettledTurnId: RunId | null;
|
||||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||||
readonly onToggleWorkGroup: (groupId: 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 onToggleTurnFold: (runId: RunId) => void;
|
||||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||||
readonly onMarkdownLinkPress: (href: string) => void;
|
readonly onMarkdownLinkPress: (href: string) => void;
|
||||||
@@ -928,6 +936,10 @@ function renderFeedEntry(
|
|||||||
const entry = info.item;
|
const entry = info.item;
|
||||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||||
|
|
||||||
|
if (entry.type === "working") {
|
||||||
|
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||||
|
}
|
||||||
|
|
||||||
if (entry.type === "run-fold") {
|
if (entry.type === "run-fold") {
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<Pressable
|
||||||
@@ -983,7 +995,10 @@ function renderFeedEntry(
|
|||||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||||
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
|
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
|
||||||
return (
|
return (
|
||||||
<View className="mb-5 items-end">
|
<Animated.View
|
||||||
|
className="mb-5 items-end"
|
||||||
|
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
|
||||||
|
>
|
||||||
{message.createdBy === "agent" ? (
|
{message.createdBy === "agent" ? (
|
||||||
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||||
Sent by another agent
|
Sent by another agent
|
||||||
@@ -1136,7 +1151,8 @@ function renderFeedEntry(
|
|||||||
expandedRows={props.expandedWorkRows}
|
expandedRows={props.expandedWorkRows}
|
||||||
iconSubtleColor={iconSubtleColor}
|
iconSubtleColor={iconSubtleColor}
|
||||||
onCopyRow={props.onCopyWorkRow}
|
onCopyRow={props.onCopyWorkRow}
|
||||||
onToggleRow={props.onToggleWorkRow}
|
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||||
|
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
|
||||||
workspaceRoot={props.workspaceRoot}
|
workspaceRoot={props.workspaceRoot}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -1441,8 +1457,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
const foldSettleFrameRef = useRef<number | null>(null);
|
const foldSettleFrameRef = useRef<number | null>(null);
|
||||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||||
const previousLatestTurnRef = useRef(props.latestRun);
|
const previousLatestTurnRef = useRef(props.latestRun);
|
||||||
const { width: viewportWidth } = useWindowDimensions();
|
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
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<{
|
const [interactionState, setInteractionState] = useState<{
|
||||||
readonly copiedRowId: string | null;
|
readonly copiedRowId: string | null;
|
||||||
readonly expandedWorkGroups: Record<string, boolean>;
|
readonly expandedWorkGroups: Record<string, boolean>;
|
||||||
@@ -1520,6 +1543,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
const listAppearanceData = useMemo(
|
const listAppearanceData = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
copiedRowId,
|
copiedRowId,
|
||||||
|
expandedWorkGroups,
|
||||||
expandedWorkRows,
|
expandedWorkRows,
|
||||||
iconSubtleColor,
|
iconSubtleColor,
|
||||||
markdownStyles,
|
markdownStyles,
|
||||||
@@ -1529,6 +1553,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
copiedRowId,
|
copiedRowId,
|
||||||
|
expandedWorkGroups,
|
||||||
expandedWorkRows,
|
expandedWorkRows,
|
||||||
iconSubtleColor,
|
iconSubtleColor,
|
||||||
markdownStyles,
|
markdownStyles,
|
||||||
@@ -1537,9 +1562,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
viewportWidth,
|
viewportWidth,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
const presentedFeed = useMemo(
|
const reportHeaderMaterialVisibility = useCallback(
|
||||||
() => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds),
|
(visible: boolean) => {
|
||||||
[expandedTurnIds, props.feed, props.latestRun],
|
if (headerMaterialVisibleRef.current === visible) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
headerMaterialVisibleRef.current = visible;
|
||||||
|
props.onHeaderMaterialVisibilityChange?.(visible);
|
||||||
|
},
|
||||||
|
[props.onHeaderMaterialVisibilityChange],
|
||||||
);
|
);
|
||||||
const handleScroll = useCallback(
|
const handleScroll = useCallback(
|
||||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||||
@@ -1594,6 +1625,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
reportHeaderMaterialVisibility(false);
|
reportHeaderMaterialVisibility(false);
|
||||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||||
|
|
||||||
|
<<<<<<< HEAD
|
||||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||||
// re-arm follow regardless of where the user had scrolled before.
|
// 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;
|
return ids;
|
||||||
}, [expandedWorkGroups]);
|
}, [expandedWorkGroups]);
|
||||||
|
=======
|
||||||
|
>>>>>>> 0c15987295 (fix: reconcile rebase with latest main)
|
||||||
const presentedFeed = useMemo(
|
const presentedFeed = useMemo(
|
||||||
() =>
|
() =>
|
||||||
deriveThreadFeedPresentation(
|
deriveThreadFeedPresentation(
|
||||||
props.feed,
|
props.feed,
|
||||||
props.latestTurn,
|
props.latestRun,
|
||||||
expandedTurnIds,
|
expandedTurnIds,
|
||||||
expandedWorkGroupIds,
|
new Set(
|
||||||
|
Object.entries(expandedWorkGroups)
|
||||||
|
.filter(([, expanded]) => expanded)
|
||||||
|
.map(([groupId]) => groupId),
|
||||||
|
),
|
||||||
props.activeWorkStartedAt,
|
props.activeWorkStartedAt,
|
||||||
),
|
),
|
||||||
[
|
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
|
||||||
expandedTurnIds,
|
|
||||||
expandedWorkGroupIds,
|
|
||||||
props.activeWorkStartedAt,
|
|
||||||
props.feed,
|
|
||||||
props.latestTurn,
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// The empty↔filled key below remounts the list, which resets its imperative
|
// 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(
|
const onToggleWorkRow = useCallback(
|
||||||
(rowId: string) => {
|
(rowId: string, anchorKey?: string) => {
|
||||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
|
||||||
setInteractionState((current) => ({
|
setInteractionState((current) => ({
|
||||||
...current,
|
...current,
|
||||||
expandedWorkRows: {
|
expandedWorkRows: {
|
||||||
@@ -1789,28 +1821,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
[suspendEndScrollMaintenanceForDisclosure],
|
[suspendEndScrollMaintenanceForDisclosure],
|
||||||
);
|
);
|
||||||
|
|
||||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
const onToggleTurnFold = useCallback(
|
||||||
setFoldToggleSettling(true);
|
(runId: RunId) => {
|
||||||
if (foldSettleFrameRef.current !== null) {
|
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
|
||||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
setInteractionState((current) => {
|
||||||
}
|
const next = new Set(current.expandedTurnIds);
|
||||||
if (foldSettleSecondFrameRef.current !== null) {
|
if (next.has(runId)) {
|
||||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
next.delete(runId);
|
||||||
}
|
} else {
|
||||||
setInteractionState((current) => {
|
next.add(runId);
|
||||||
const next = new Set(current.expandedTurnIds);
|
}
|
||||||
if (next.has(runId)) {
|
return { ...current, expandedTurnIds: next };
|
||||||
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;
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[suspendEndScrollMaintenanceForDisclosure],
|
[suspendEndScrollMaintenanceForDisclosure],
|
||||||
@@ -1833,7 +1854,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
const getFixedItemSize = useCallback(
|
const getFixedItemSize = useCallback(
|
||||||
(entry: ThreadFeedEntry) => {
|
(entry: ThreadFeedEntry) => {
|
||||||
switch (entry.type) {
|
switch (entry.type) {
|
||||||
case "turn-fold":
|
case "run-fold":
|
||||||
return TURN_FOLD_HEIGHT;
|
return TURN_FOLD_HEIGHT;
|
||||||
case "work-toggle":
|
case "work-toggle":
|
||||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||||
@@ -1858,6 +1879,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
environmentId: props.environmentId,
|
environmentId: props.environmentId,
|
||||||
threadId: props.threadId,
|
threadId: props.threadId,
|
||||||
copiedRowId,
|
copiedRowId,
|
||||||
|
expandedWorkGroups,
|
||||||
expandedWorkRows,
|
expandedWorkRows,
|
||||||
terminalAssistantMessageIds,
|
terminalAssistantMessageIds,
|
||||||
unsettledTurnId,
|
unsettledTurnId,
|
||||||
@@ -1879,6 +1901,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
copiedRowId,
|
copiedRowId,
|
||||||
|
expandedWorkGroups,
|
||||||
expandedWorkRows,
|
expandedWorkRows,
|
||||||
terminalAssistantMessageIds,
|
terminalAssistantMessageIds,
|
||||||
unsettledTurnId,
|
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.
|
// render into — which is why the header blur was missing on threads.
|
||||||
scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
|
scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
|
||||||
}
|
}
|
||||||
}
|
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||||
maintainVisibleContentPosition
|
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||||
data={presentedFeed}
|
itemLayoutAnimation={feedItemLayoutTransition}
|
||||||
extraData={listAppearanceData}
|
// Patched LegendList prop (patches/@[email protected]):
|
||||||
renderItem={renderItem}
|
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||||
keyExtractor={(entry) => entry.id}
|
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||||
getItemType={(entry) =>
|
// content rest below the transparent header rather than at frame top.
|
||||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
|
||||||
}
|
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||||
keyboardShouldPersistTaps="always"
|
// UIKit's automatic behavior adds the safe-area bottom on top of the
|
||||||
keyboardDismissMode="none"
|
// raw contentInset the keyboard integration writes. The detail screen
|
||||||
keyboardLiftBehavior="whenAtEnd"
|
// under-reports the composer inset by this amount (see
|
||||||
estimatedItemSize={180}
|
// ThreadDetailScreen); this tells LegendList's scroll math about the
|
||||||
initialScrollAtEnd
|
// extra so programmatic end scrolls land at the true resting offset.
|
||||||
ListHeaderComponent={
|
contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
|
||||||
<>
|
// The keyboard integration's offset math (end pinning, max scroll)
|
||||||
<View style={{ height: topContentInset }} />
|
// must add the same UIKit-added extra, or its keyboard-open end
|
||||||
{props.topAccessory}
|
// targets land one safe-area short of the true resting offset.
|
||||||
</>
|
adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
|
||||||
}
|
freeze={props.freeze}
|
||||||
contentContainerStyle={{
|
// Animated: on send, the optimistic message's dataChange fires
|
||||||
paddingTop: 12,
|
// maintainScrollAtEnd before any render-cycle suppression could
|
||||||
paddingHorizontal: horizontalPadding,
|
// 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
|
||||||
{props.feed.length === 0 ? (
|
// 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 : <View style={{ height: topContentInset }} />}
|
||||||
|
{props.topAccessory}
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
contentContainerStyle={{
|
||||||
|
paddingTop: 12,
|
||||||
|
paddingHorizontal: contentHorizontalPadding,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
{props.feed.length === 0 &&
|
||||||
|
props.activeWorkStartedAt === null &&
|
||||||
|
props.contentPresentation.kind === "ready" ? (
|
||||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||||
<ThreadFeedPlaceholder
|
<ThreadFeedPlaceholder
|
||||||
title="No conversation yet"
|
title="No conversation yet"
|
||||||
|
|||||||
@@ -902,7 +902,7 @@ function ThreadNavigationSidebarPane(
|
|||||||
?.providers.find(
|
?.providers.find(
|
||||||
(provider) =>
|
(provider) =>
|
||||||
provider.instanceId ===
|
provider.instanceId ===
|
||||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||||
)?.driver ?? null
|
)?.driver ?? null
|
||||||
}
|
}
|
||||||
environmentLabel={
|
environmentLabel={
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-nat
|
|||||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||||
|
|
||||||
import { AppText as Text } from "../../components/AppText";
|
import { AppText as Text } from "../../components/AppText";
|
||||||
import { buildThreadRoutePath } from "../../lib/routes";
|
|
||||||
import { useThemeColor } from "../../lib/useThemeColor";
|
import { useThemeColor } from "../../lib/useThemeColor";
|
||||||
import { useThreadShells } from "../../state/entities";
|
import { useThreadShells } from "../../state/entities";
|
||||||
import { threadEnvironment } from "../../state/threads";
|
import { threadEnvironment } from "../../state/threads";
|
||||||
@@ -96,7 +95,7 @@ export function ThreadRelationshipsBanner(props: {
|
|||||||
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
|
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
|
||||||
const [visible, setVisible] = useState(false);
|
const [visible, setVisible] = useState(false);
|
||||||
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
|
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
|
||||||
const router = useRouter();
|
const navigation = useNavigation();
|
||||||
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
|
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
|
||||||
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
||||||
const insets = useSafeAreaInsets();
|
const insets = useSafeAreaInsets();
|
||||||
@@ -115,11 +114,14 @@ export function ThreadRelationshipsBanner(props: {
|
|||||||
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
|
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
|
||||||
setVisible(false);
|
setVisible(false);
|
||||||
void Haptics.selectionAsync();
|
void Haptics.selectionAsync();
|
||||||
router.push(
|
if (archivedThread) {
|
||||||
archivedThread
|
navigation.navigate("SettingsSheet", { screen: "SettingsArchive" });
|
||||||
? "/settings/archive"
|
return;
|
||||||
: buildThreadRoutePath({ environmentId: props.environmentId, threadId }),
|
}
|
||||||
);
|
navigation.navigate("Thread", {
|
||||||
|
environmentId: props.environmentId,
|
||||||
|
threadId,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const merge = async () => {
|
const merge = async () => {
|
||||||
|
|||||||
@@ -516,7 +516,7 @@ function ThreadRouteContent(
|
|||||||
terminalDebugLog("terminal-menu:open-new", {
|
terminalDebugLog("terminal-menu:open-new", {
|
||||||
hasThread: Boolean(selectedThread),
|
hasThread: Boolean(selectedThread),
|
||||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||||
@@ -524,7 +524,7 @@ function ThreadRouteContent(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const nextId = nextOpenTerminalId({
|
const nextId = nextOpenTerminalId({
|
||||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||||
});
|
});
|
||||||
void navigation.navigate("ThreadTerminal", {
|
void navigation.navigate("ThreadTerminal", {
|
||||||
environmentId: String(selectedThread.environmentId),
|
environmentId: String(selectedThread.environmentId),
|
||||||
@@ -551,9 +551,9 @@ function ThreadRouteContent(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const targetTerminalId = resolveProjectScriptTerminalId({
|
const targetTerminalId = resolveProjectScriptTerminalId({
|
||||||
existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||||
hasRunningTerminal: terminalMenuSessions.some(
|
hasRunningTerminal: terminalMenuSessions.some(
|
||||||
(runtime) => runtime.status === "running" || runtime.status === "starting",
|
(session) => session.status === "running" || session.status === "starting",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
||||||
|
|||||||
@@ -28,10 +28,14 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
|||||||
import { useThreadPr } from "../../state/use-thread-pr";
|
import { useThreadPr } from "../../state/use-thread-pr";
|
||||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||||
import {
|
import {
|
||||||
|
resolveThreadListV2SnoozeGateExpiryMs,
|
||||||
|
resolveThreadListV2SnoozeMenuSelection,
|
||||||
resolveThreadListV2Status,
|
resolveThreadListV2Status,
|
||||||
|
resolveThreadListV2SwipeActions,
|
||||||
threadHasUnseenCompletion,
|
threadHasUnseenCompletion,
|
||||||
type ThreadListV2Status,
|
type ThreadListV2Status,
|
||||||
} from "./threadListV2";
|
} from "./threadListV2";
|
||||||
|
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
|
* 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: {
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
<View className="mt-1 flex-row items-center gap-2">
|
<View className="mt-1 flex-row items-center gap-2">
|
||||||
{status === "failed" && thread.session?.lastError ? (
|
{status === "failed" && thread.runtime?.lastError ? (
|
||||||
<Text
|
<Text
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex-1 text-xs",
|
"flex-1 text-xs",
|
||||||
@@ -645,7 +649,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
|||||||
)}
|
)}
|
||||||
numberOfLines={1}
|
numberOfLines={1}
|
||||||
>
|
>
|
||||||
{thread.session.lastError}
|
{thread.runtime.lastError}
|
||||||
</Text>
|
</Text>
|
||||||
) : thread.branch || props.environmentLabel ? (
|
) : thread.branch || props.environmentLabel ? (
|
||||||
/* "branch · machine" share one truncating line. The machine sits
|
/* "branch · machine" share one truncating line. The machine sits
|
||||||
|
|||||||
@@ -2,18 +2,21 @@ import * as Haptics from "expo-haptics";
|
|||||||
import { Image } from "expo-image";
|
import { Image } from "expo-image";
|
||||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
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 { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
|
||||||
|
|
||||||
import { AppText as Text } from "../../components/AppText";
|
import { AppText as Text } from "../../components/AppText";
|
||||||
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
|
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
|
||||||
|
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
|
||||||
import { cn } from "../../lib/cn";
|
import { cn } from "../../lib/cn";
|
||||||
import { buildThreadRoutePath } from "../../lib/routes";
|
|
||||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
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 { useV2ItemSupport } from "../../state/v2-item-support";
|
||||||
import { ThreadActivityInspector } from "./ThreadActivityInspector";
|
import { ThreadActivityInspector } from "./ThreadActivityInspector";
|
||||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||||
|
|
||||||
|
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||||
duration: 180,
|
duration: 180,
|
||||||
create: {
|
create: {
|
||||||
@@ -117,7 +120,7 @@ function ThreadActivityThreadLink(props: {
|
|||||||
sourceThreadId: row.sourceThreadId,
|
sourceThreadId: row.sourceThreadId,
|
||||||
sourceItemId: row.sourceItemId,
|
sourceItemId: row.sourceItemId,
|
||||||
});
|
});
|
||||||
const router = useRouter();
|
const navigation = useNavigation();
|
||||||
const item = row.item;
|
const item = row.item;
|
||||||
let targetThreadId: ThreadId | null = null;
|
let targetThreadId: ThreadId | null = null;
|
||||||
let label = "Open related thread";
|
let label = "Open related thread";
|
||||||
@@ -144,12 +147,10 @@ function ThreadActivityThreadLink(props: {
|
|||||||
accessibilityLabel={label}
|
accessibilityLabel={label}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
void Haptics.selectionAsync();
|
void Haptics.selectionAsync();
|
||||||
router.push(
|
navigation.navigate("Thread", {
|
||||||
buildThreadRoutePath({
|
environmentId: props.environmentId,
|
||||||
environmentId: props.environmentId,
|
threadId: targetThreadId,
|
||||||
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]"
|
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<ThreadFeedActivity>,
|
||||||
|
): ReadonlyArray<ThreadFeedActivity> {
|
||||||
|
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<ThreadFeedActivity>,
|
||||||
|
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: {
|
export function ThreadWorkLog(props: {
|
||||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||||
readonly copiedRowId: string | null;
|
readonly copiedRowId: string | null;
|
||||||
@@ -168,22 +217,30 @@ export function ThreadWorkLog(props: {
|
|||||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||||
|
readonly onToggleGroup: () => void;
|
||||||
readonly onToggleRow: (rowId: string) => void;
|
readonly onToggleRow: (rowId: string) => void;
|
||||||
readonly workspaceRoot?: string | null;
|
readonly workspaceRoot?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const colorScheme = useColorScheme();
|
const colorScheme = useColorScheme();
|
||||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
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) {
|
if (rows.length === 0) {
|
||||||
return null;
|
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 onlyToolRows = rows.every((row) => row.toolLike);
|
||||||
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
|
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View className="-mx-1 mb-1 px-1 py-0">
|
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||||
{!onlyToolRows ? (
|
{!onlyToolRows ? (
|
||||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||||
work log
|
work log
|
||||||
@@ -191,16 +248,17 @@ export function ThreadWorkLog(props: {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<View className="gap-px">
|
<View className="gap-px">
|
||||||
{rows.map((row) => {
|
{visibleRows.map((row) => {
|
||||||
const expanded = props.expandedRows[row.id] ?? false;
|
const expanded = props.expandedRows[row.id] ?? false;
|
||||||
const canExpand = row.fullDetail !== null;
|
const canExpand = row.canExpand;
|
||||||
const detail = compactActivityDetail(row.detail);
|
const detail = compactActivityDetail(row.detail);
|
||||||
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
||||||
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View
|
<Animated.View
|
||||||
key={row.id}
|
key={row.id}
|
||||||
|
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
|
||||||
className={cn(
|
className={cn(
|
||||||
row.prominent &&
|
row.prominent &&
|
||||||
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
|
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
|
||||||
@@ -226,7 +284,7 @@ export function ThreadWorkLog(props: {
|
|||||||
style={({ pressed }) => ({
|
style={({ pressed }) => ({
|
||||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||||
})}
|
})}
|
||||||
className="rounded-md px-0.5 py-0"
|
className="rounded-md px-0.5 py-0.5"
|
||||||
>
|
>
|
||||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||||
@@ -287,7 +345,7 @@ export function ThreadWorkLog(props: {
|
|||||||
</View>
|
</View>
|
||||||
</Pressable>
|
</Pressable>
|
||||||
|
|
||||||
{expanded && row.fullDetail ? (
|
{expanded && canExpand ? (
|
||||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||||
<ThreadActivityInspector
|
<ThreadActivityInspector
|
||||||
activity={row}
|
activity={row}
|
||||||
@@ -305,7 +363,7 @@ export function ThreadWorkLog(props: {
|
|||||||
iconColor={props.iconSubtleColor}
|
iconColor={props.iconSubtleColor}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</Animated.View>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</View>
|
</View>
|
||||||
@@ -360,35 +418,33 @@ export function ThreadWorkGroupToggle(props: {
|
|||||||
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View className="-mx-1 mb-1 px-1 py-0">
|
<View className="-mx-1 mb-1 px-1">
|
||||||
<Pressable
|
<Pressable
|
||||||
accessibilityRole="button"
|
accessibilityRole="button"
|
||||||
accessibilityState={{ expanded: props.expanded }}
|
accessibilityState={{ expanded: props.expanded }}
|
||||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
accessibilityLabel={
|
||||||
|
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
|
||||||
|
}
|
||||||
hitSlop={4}
|
hitSlop={4}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
void Haptics.selectionAsync();
|
triggerDisclosureFeedback();
|
||||||
props.onToggle();
|
props.onToggle();
|
||||||
}}
|
}}
|
||||||
style={({ pressed }) => ({
|
style={({ pressed }) => ({
|
||||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
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"
|
||||||
>
|
>
|
||||||
<View className="h-[18px] w-5 items-center justify-center">
|
<View className="h-[18px] w-5 items-center justify-center">
|
||||||
<SymbolView
|
<SymbolView
|
||||||
name={
|
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||||
props.expanded
|
|
||||||
? { ios: "chevron.up", android: "keyboard_arrow_up" }
|
|
||||||
: { ios: "chevron.down", android: "keyboard_arrow_down" }
|
|
||||||
}
|
|
||||||
size={12}
|
size={12}
|
||||||
tintColor={props.iconSubtleColor}
|
tintColor={props.iconSubtleColor}
|
||||||
type="monochrome"
|
type="monochrome"
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
|
||||||
</Text>
|
</Text>
|
||||||
</Pressable>
|
</Pressable>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ import {
|
|||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderInstanceId,
|
ProviderInstanceId,
|
||||||
|
RunId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vite-plus/test";
|
import { describe, expect, it } from "vite-plus/test";
|
||||||
|
|
||||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||||
|
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||||
import {
|
import {
|
||||||
buildThreadListV2Items,
|
buildThreadListV2Items,
|
||||||
buildThreadListV2ListItems,
|
buildThreadListV2ListItems,
|
||||||
@@ -29,27 +30,10 @@ const environmentId = EnvironmentId.make("environment-1");
|
|||||||
function makeThread(
|
function makeThread(
|
||||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||||
): EnvironmentThreadShell {
|
): EnvironmentThreadShell {
|
||||||
return {
|
return makeThreadShellFixture({
|
||||||
environmentId,
|
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,
|
...input,
|
||||||
};
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const NOW = "2026-06-02T00:00:00.000Z";
|
const NOW = "2026-06-02T00:00:00.000Z";
|
||||||
@@ -122,18 +106,16 @@ describe("resolveThreadListV2Enabled", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("resolveThreadListV2Status", () => {
|
describe("resolveThreadListV2Status", () => {
|
||||||
it("prioritizes approval over a running session", () => {
|
it("prioritizes approval over a running runtime", () => {
|
||||||
const thread = makeThread({
|
const thread = makeThread({
|
||||||
id: ThreadId.make("t"),
|
id: ThreadId.make("t"),
|
||||||
title: "t",
|
title: "t",
|
||||||
hasPendingApprovals: true,
|
hasPendingApprovals: true,
|
||||||
session: {
|
runtime: {
|
||||||
threadId: ThreadId.make("t"),
|
|
||||||
status: "running",
|
status: "running",
|
||||||
|
activeRunId: RunId.make("run-t"),
|
||||||
providerName: "Codex",
|
providerName: "Codex",
|
||||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||||
runtimeMode: "full-access",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: NOW,
|
updatedAt: NOW,
|
||||||
},
|
},
|
||||||
@@ -688,10 +670,11 @@ describe("buildThreadListV2Items", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("scopes the flat list to one project", () => {
|
it("scopes the flat list to one project", () => {
|
||||||
|
const projectId = ProjectId.make("project-1");
|
||||||
const otherProjectId = ProjectId.make("project-2");
|
const otherProjectId = ProjectId.make("project-2");
|
||||||
const { items } = buildThreadListV2Items({
|
const { items } = buildThreadListV2Items({
|
||||||
threads: [
|
threads: [
|
||||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
makeThread({ id: ThreadId.make("included"), projectId, title: "Included" }),
|
||||||
makeThread({
|
makeThread({
|
||||||
id: ThreadId.make("excluded"),
|
id: ThreadId.make("excluded"),
|
||||||
projectId: otherProjectId,
|
projectId: otherProjectId,
|
||||||
@@ -699,7 +682,7 @@ describe("buildThreadListV2Items", () => {
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
environmentId: null,
|
environmentId: null,
|
||||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
projectRefs: [{ environmentId, projectId }],
|
||||||
searchQuery: "",
|
searchQuery: "",
|
||||||
now: NOW,
|
now: NOW,
|
||||||
});
|
});
|
||||||
@@ -709,19 +692,21 @@ describe("buildThreadListV2Items", () => {
|
|||||||
|
|
||||||
it("scopes the flat list to every environment member of a logical project", () => {
|
it("scopes the flat list to every environment member of a logical project", () => {
|
||||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||||
|
const projectId = ProjectId.make("project-1");
|
||||||
const { items } = buildThreadListV2Items({
|
const { items } = buildThreadListV2Items({
|
||||||
threads: [
|
threads: [
|
||||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
makeThread({ id: ThreadId.make("local"), projectId, title: "Local" }),
|
||||||
makeThread({
|
makeThread({
|
||||||
environmentId: remoteEnvironmentId,
|
environmentId: remoteEnvironmentId,
|
||||||
id: ThreadId.make("remote"),
|
id: ThreadId.make("remote"),
|
||||||
|
projectId,
|
||||||
title: "Remote",
|
title: "Remote",
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
environmentId: null,
|
environmentId: null,
|
||||||
projectRefs: [
|
projectRefs: [
|
||||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
{ environmentId, projectId },
|
||||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
{ environmentId: remoteEnvironmentId, projectId },
|
||||||
],
|
],
|
||||||
searchQuery: "",
|
searchQuery: "",
|
||||||
now: NOW,
|
now: NOW,
|
||||||
@@ -744,9 +729,9 @@ describe("buildThreadListV2Items settled paging", () => {
|
|||||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||||
// A turn adopted the message (same requestedAt): without it the
|
// A turn adopted the message (same requestedAt): without it the
|
||||||
// thread reads as a queued turn start, which never settles.
|
// thread reads as a queued turn start, which never settles.
|
||||||
latestTurn: {
|
latestRun: {
|
||||||
turnId: TurnId.make(`turn-${index}`),
|
runId: RunId.make(`run-${index}`),
|
||||||
state: "completed",
|
status: "completed",
|
||||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ export function resolveThreadListV2SwipeActions(input: {
|
|||||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||||
thread: Pick<
|
thread: Pick<
|
||||||
EnvironmentThreadShell,
|
EnvironmentThreadShell,
|
||||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
"hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime"
|
||||||
>,
|
>,
|
||||||
options: { readonly now: string },
|
options: { readonly now: string },
|
||||||
): number | null {
|
): number | null {
|
||||||
@@ -143,7 +143,7 @@ export function threadHasUnseenCompletion(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveThreadListV2Status(
|
export function resolveThreadListV2Status(
|
||||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
|
||||||
): ThreadListV2Status {
|
): ThreadListV2Status {
|
||||||
if (thread.hasPendingApprovals) {
|
if (thread.hasPendingApprovals) {
|
||||||
return "approval";
|
return "approval";
|
||||||
@@ -151,10 +151,13 @@ export function resolveThreadListV2Status(
|
|||||||
if (thread.hasPendingUserInput) {
|
if (thread.hasPendingUserInput) {
|
||||||
return "input";
|
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";
|
return "working";
|
||||||
}
|
}
|
||||||
if (thread.session?.status === "error") {
|
if (thread.runtime?.status === "failed") {
|
||||||
return "failed";
|
return "failed";
|
||||||
}
|
}
|
||||||
return "ready";
|
return "ready";
|
||||||
|
|||||||
@@ -1,15 +1,53 @@
|
|||||||
import type { StatusTone } from "../../components/StatusPill";
|
import type { StatusTone } from "../../components/StatusPill";
|
||||||
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
|
import {
|
||||||
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
threadRuntimeIsActive,
|
||||||
|
type EnvironmentThreadShell,
|
||||||
|
} from "@t3tools/client-runtime/state/shell";
|
||||||
|
|
||||||
export function threadSortValue(thread: EnvironmentThreadShell): number {
|
export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||||
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
|
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
|
||||||
return Number.isNaN(candidate) ? 0 : candidate;
|
return Number.isNaN(candidate) ? 0 : candidate;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
export type ThreadStatusKind =
|
||||||
const status = thread.runtime?.status;
|
| "pending-approval"
|
||||||
if (status === "running" || status === "waiting") {
|
| "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 {
|
return {
|
||||||
kind: "pending-approval",
|
kind: "pending-approval",
|
||||||
label: "Needs Approval",
|
label: "Needs Approval",
|
||||||
@@ -20,7 +58,8 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
|||||||
pulse: false,
|
pulse: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (status === "completed") {
|
|
||||||
|
if (thread.hasPendingUserInput) {
|
||||||
return {
|
return {
|
||||||
kind: "awaiting-input",
|
kind: "awaiting-input",
|
||||||
label: "Awaiting Input",
|
label: "Awaiting Input",
|
||||||
@@ -31,7 +70,10 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
|||||||
pulse: false,
|
pulse: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (status === "preparing" || status === "queued" || status === "starting") {
|
|
||||||
|
const runtimeStatus = thread.runtime?.status;
|
||||||
|
|
||||||
|
if (runtimeStatus === "running" || runtimeStatus === "waiting") {
|
||||||
return {
|
return {
|
||||||
kind: "working",
|
kind: "working",
|
||||||
label: "Working",
|
label: "Working",
|
||||||
@@ -42,7 +84,8 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
|||||||
pulse: true,
|
pulse: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (status === "failed") {
|
|
||||||
|
if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") {
|
||||||
return {
|
return {
|
||||||
kind: "connecting",
|
kind: "connecting",
|
||||||
label: "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 {
|
return {
|
||||||
kind: "error",
|
kind: "error",
|
||||||
label: "Error",
|
label: "Error",
|
||||||
@@ -68,7 +111,7 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
|||||||
|
|
||||||
const hasPlanReadyPrompt =
|
const hasPlanReadyPrompt =
|
||||||
thread.interactionMode === "plan" &&
|
thread.interactionMode === "plan" &&
|
||||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
isLatestRunSettled(thread) &&
|
||||||
thread.hasActionableProposedPlan;
|
thread.hasActionableProposedPlan;
|
||||||
if (hasPlanReadyPrompt) {
|
if (hasPlanReadyPrompt) {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -58,16 +58,15 @@ export function useCreateProjectThread() {
|
|||||||
|
|
||||||
const result = await startTurn({
|
const result = await startTurn({
|
||||||
environmentId: input.project.environmentId,
|
environmentId: input.project.environmentId,
|
||||||
input: {
|
input: buildProjectThreadStartTurnInput({
|
||||||
commandId: CommandId.make(metadata.commandId),
|
projectId: input.project.id,
|
||||||
creationSource: "mobile",
|
projectCwd: input.project.workspaceRoot,
|
||||||
threadId,
|
threadId: metadata.threadId,
|
||||||
message: {
|
commandId: metadata.commandId,
|
||||||
messageId: MessageId.make(metadata.messageId),
|
messageId: metadata.messageId,
|
||||||
role: "user",
|
createdAt: metadata.createdAt,
|
||||||
text: initialMessageText,
|
text: initialMessageText,
|
||||||
attachments: input.initialAttachments,
|
attachments: input.initialAttachments,
|
||||||
},
|
|
||||||
modelSelection: input.modelSelection,
|
modelSelection: input.modelSelection,
|
||||||
runtimeMode: input.runtimeMode,
|
runtimeMode: input.runtimeMode,
|
||||||
interactionMode: input.interactionMode,
|
interactionMode: input.interactionMode,
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
|||||||
const isWorktree = spec.workspaceMode === "worktree";
|
const isWorktree = spec.workspaceMode === "worktree";
|
||||||
return {
|
return {
|
||||||
commandId: CommandId.make(spec.commandId),
|
commandId: CommandId.make(spec.commandId),
|
||||||
|
creationSource: "mobile" as const,
|
||||||
threadId: ThreadId.make(spec.threadId),
|
threadId: ThreadId.make(spec.threadId),
|
||||||
message: {
|
message: {
|
||||||
messageId: MessageId.make(spec.messageId),
|
messageId: MessageId.make(spec.messageId),
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ describe("buildThreadFeed", () => {
|
|||||||
]);
|
]);
|
||||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||||
expect(activity?.projectedItem).toBe(rows[1]);
|
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", () => {
|
it("retains inherited and synthetic rows with their original projected identity", () => {
|
||||||
@@ -301,7 +301,7 @@ describe("buildThreadFeed", () => {
|
|||||||
): ThreadFeedActivity => ({
|
): ThreadFeedActivity => ({
|
||||||
id,
|
id,
|
||||||
createdAt,
|
createdAt,
|
||||||
turnId: null,
|
runId: null,
|
||||||
summary: `Tool ${id}`,
|
summary: `Tool ${id}`,
|
||||||
detail: null,
|
detail: null,
|
||||||
canExpand: false,
|
canExpand: false,
|
||||||
@@ -310,14 +310,16 @@ describe("buildThreadFeed", () => {
|
|||||||
icon: "command",
|
icon: "command",
|
||||||
logo: null,
|
logo: null,
|
||||||
toolLike: true,
|
toolLike: true,
|
||||||
|
prominent: false,
|
||||||
status,
|
status,
|
||||||
|
projectedItem: projected(command(createdAt), 0),
|
||||||
});
|
});
|
||||||
const feed: ThreadFeedEntry[] = [
|
const feed: ThreadFeedEntry[] = [
|
||||||
{
|
{
|
||||||
type: "activity-group",
|
type: "activity-group",
|
||||||
id: "work-group-1",
|
id: "work-group-1",
|
||||||
createdAt: "2026-04-01T00:00:01.000Z",
|
createdAt: "2026-04-01T00:00:01.000Z",
|
||||||
turnId: null,
|
runId: null,
|
||||||
activities: [
|
activities: [
|
||||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
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?.summary).toBe("Read a T3 thread");
|
||||||
expect(activity?.logo).toBe("t3-code");
|
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");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ import * as DateTime from "effect/DateTime";
|
|||||||
export type PendingApproval = ThreadPendingApproval;
|
export type PendingApproval = ThreadPendingApproval;
|
||||||
export type PendingUserInput = ThreadPendingUserInput;
|
export type PendingUserInput = ThreadPendingUserInput;
|
||||||
|
|
||||||
|
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||||
|
|
||||||
export interface PendingUserInputDraftAnswer {
|
export interface PendingUserInputDraftAnswer {
|
||||||
readonly selectedOptionLabel?: string;
|
readonly selectedOptionLabel?: string;
|
||||||
readonly customAnswer?: string;
|
readonly customAnswer?: string;
|
||||||
@@ -137,6 +139,16 @@ export type ThreadFeedEntry =
|
|||||||
readonly runId: RunId | null;
|
readonly runId: RunId | null;
|
||||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||||
}
|
}
|
||||||
|
| {
|
||||||
|
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 type: "run-fold";
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
@@ -489,6 +501,18 @@ function capitalizePhrase(value: string): string {
|
|||||||
return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
|
return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function memoizeValue<T>(build: () => T): () => T {
|
||||||
|
let value: T;
|
||||||
|
let initialized = false;
|
||||||
|
return () => {
|
||||||
|
if (!initialized) {
|
||||||
|
value = build();
|
||||||
|
initialized = true;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
|
function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
|
||||||
return (
|
return (
|
||||||
item.type === "reasoning" ||
|
item.type === "reasoning" ||
|
||||||
@@ -661,15 +685,25 @@ function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivi
|
|||||||
const toolPresentation = itemToolPresentation(item);
|
const toolPresentation = itemToolPresentation(item);
|
||||||
const summary = itemSummary(item, toolPresentation);
|
const summary = itemSummary(item, toolPresentation);
|
||||||
const detail = itemPreview(item);
|
const detail = itemPreview(item);
|
||||||
const fullDetail = JSON.stringify(
|
const getFullDetail = memoizeValue(() =>
|
||||||
{
|
JSON.stringify(
|
||||||
visibility: row.visibility,
|
{
|
||||||
sourceThreadId: row.sourceThreadId,
|
visibility: row.visibility,
|
||||||
sourceItemId: row.sourceItemId,
|
sourceThreadId: row.sourceThreadId,
|
||||||
item,
|
sourceItemId: row.sourceItemId,
|
||||||
},
|
item,
|
||||||
null,
|
},
|
||||||
2,
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const getCopyText = memoizeValue(() =>
|
||||||
|
[summary, detail, getFullDetail()]
|
||||||
|
.filter(
|
||||||
|
(value, index, values): value is string =>
|
||||||
|
Boolean(value) && values.indexOf(value) === index,
|
||||||
|
)
|
||||||
|
.join("\n"),
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
|
id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
|
||||||
@@ -677,15 +711,11 @@ function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivi
|
|||||||
runId: item.runId,
|
runId: item.runId,
|
||||||
summary,
|
summary,
|
||||||
detail,
|
detail,
|
||||||
fullDetail,
|
canExpand: true,
|
||||||
|
getFullDetail,
|
||||||
|
getCopyText,
|
||||||
icon: itemIcon(item),
|
icon: itemIcon(item),
|
||||||
logo: toolPresentation?.logo ?? null,
|
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),
|
toolLike: itemIsToolLike(item),
|
||||||
prominent: itemIsProminent(item),
|
prominent: itemIsProminent(item),
|
||||||
status: itemStatus(item),
|
status: itemStatus(item),
|
||||||
@@ -703,6 +733,13 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
|
|||||||
|
|
||||||
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
|
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
|
||||||
const grouped: 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) {
|
for (const entry of entries) {
|
||||||
if (isEmptyMessage(entry)) continue;
|
if (isEmptyMessage(entry)) continue;
|
||||||
if (entry.type !== "activity") {
|
if (entry.type !== "activity") {
|
||||||
@@ -710,25 +747,26 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
|
|||||||
openGroupActivities = null;
|
openGroupActivities = null;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const previous = grouped.at(-1);
|
|
||||||
if (
|
if (
|
||||||
previous?.type === "activity-group" &&
|
openGroupActivities !== null &&
|
||||||
previous.runId === entry.runId &&
|
openGroupRunId === entry.runId &&
|
||||||
!entry.activity.prominent &&
|
!entry.activity.prominent &&
|
||||||
!previous.activities.some((activity) => activity.prominent)
|
!openGroupHasProminent
|
||||||
) {
|
) {
|
||||||
grouped[grouped.length - 1] = {
|
openGroupActivities.push(entry.activity);
|
||||||
...previous,
|
|
||||||
activities: [...previous.activities, entry.activity],
|
|
||||||
};
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
openGroupActivities = [entry.activity];
|
||||||
|
openGroupRunId = entry.runId;
|
||||||
|
openGroupHasProminent = entry.activity.prominent === true;
|
||||||
grouped.push({
|
grouped.push({
|
||||||
type: "activity-group",
|
type: "activity-group",
|
||||||
id: entry.id,
|
id: entry.id,
|
||||||
createdAt: entry.createdAt,
|
createdAt: entry.createdAt,
|
||||||
runId: entry.runId,
|
runId: entry.runId,
|
||||||
activities: [entry.activity],
|
activities: openGroupActivities,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return grouped;
|
return grouped;
|
||||||
@@ -870,8 +908,13 @@ export function deriveThreadFeedPresentation(
|
|||||||
feed: ReadonlyArray<ThreadFeedEntry>,
|
feed: ReadonlyArray<ThreadFeedEntry>,
|
||||||
latestRun: ThreadFeedLatestRun | null,
|
latestRun: ThreadFeedLatestRun | null,
|
||||||
expandedRunIds: ReadonlySet<RunId>,
|
expandedRunIds: ReadonlySet<RunId>,
|
||||||
|
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||||
|
activeWorkStartedAt: string | null = null,
|
||||||
): ThreadFeedEntry[] {
|
): 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 foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
|
||||||
const collapsedEntryIds = new Set<string>();
|
const collapsedEntryIds = new Set<string>();
|
||||||
for (const fold of foldsByAnchorId.values()) {
|
for (const fold of foldsByAnchorId.values()) {
|
||||||
@@ -892,7 +935,9 @@ export function deriveThreadFeedPresentation(
|
|||||||
expanded: expandedRunIds.has(fold.runId),
|
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) {
|
if (activeWorkStartedAt !== null) {
|
||||||
result.push({
|
result.push({
|
||||||
@@ -904,6 +949,55 @@ export function deriveThreadFeedPresentation(
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function appendPresentedFeedEntry(
|
||||||
|
result: ThreadFeedEntry[],
|
||||||
|
entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "working" }>,
|
||||||
|
expandedWorkGroupIds: ReadonlySet<string>,
|
||||||
|
): 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(
|
export function setPendingUserInputCustomAnswer(
|
||||||
draft: PendingUserInputDraftAnswer | undefined,
|
draft: PendingUserInputDraftAnswer | undefined,
|
||||||
customAnswer: string,
|
customAnswer: string,
|
||||||
|
|||||||
@@ -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 { useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
import { orchestrationEnvironment } from "./orchestration";
|
import { orchestrationEnvironment } from "./orchestration";
|
||||||
@@ -51,6 +59,31 @@ function useDebouncedValue<A>(value: A, delayMs: number): A {
|
|||||||
return debounced;
|
return debounced;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useThreadSearch(
|
||||||
|
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||||
|
query: string,
|
||||||
|
): {
|
||||||
|
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
|
||||||
|
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: {
|
export function useBranches(input: {
|
||||||
readonly environmentId: EnvironmentId | null;
|
readonly environmentId: EnvironmentId | null;
|
||||||
readonly cwd: string | null;
|
readonly cwd: string | null;
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import { scopedRequestKey } from "../lib/scopedEntities";
|
|||||||
import {
|
import {
|
||||||
buildPendingUserInputAnswers,
|
buildPendingUserInputAnswers,
|
||||||
setPendingUserInputCustomAnswer,
|
setPendingUserInputCustomAnswer,
|
||||||
sortThreadActivities,
|
|
||||||
type PendingUserInputDraftAnswer,
|
type PendingUserInputDraftAnswer,
|
||||||
} from "../lib/threadActivity";
|
} from "../lib/threadActivity";
|
||||||
import { appAtomRegistry } from "./atom-registry";
|
import { appAtomRegistry } from "./atom-registry";
|
||||||
|
|||||||
@@ -196,8 +196,8 @@ export function useThreadComposerState() {
|
|||||||
setPendingConnectionError(
|
setPendingConnectionError(
|
||||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||||
);
|
);
|
||||||
return null;
|
});
|
||||||
}
|
return messageId;
|
||||||
}, [selectedThreadShell]);
|
}, [selectedThreadShell]);
|
||||||
|
|
||||||
const onChangeDraftMessage = useCallback(
|
const onChangeDraftMessage = useCallback(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useAtomValue } from "@effect/atom-react";
|
import { useAtomValue } from "@effect/atom-react";
|
||||||
import {
|
import {
|
||||||
threadRuntimeIsActive,
|
threadRuntimeIsActive,
|
||||||
|
type EnvironmentProject,
|
||||||
type EnvironmentThreadShell,
|
type EnvironmentThreadShell,
|
||||||
} from "@t3tools/client-runtime/state/shell";
|
} from "@t3tools/client-runtime/state/shell";
|
||||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||||
@@ -374,8 +375,7 @@ export function useThreadOutboxDrain(): void {
|
|||||||
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
|
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
|
||||||
nextQueuedMessage,
|
nextQueuedMessage,
|
||||||
);
|
);
|
||||||
const freshThreadBusy =
|
const freshThreadBusy = threadRuntimeIsActive(freshThread?.runtime);
|
||||||
freshThread?.session?.status === "running" || freshThread?.session?.status === "starting";
|
|
||||||
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
|
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,9 @@ import { useRoute, type RouteProp } from "@react-navigation/native";
|
|||||||
import { useMemo, useRef } from "react";
|
import { useMemo, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
EnvironmentId,
|
EnvironmentId,
|
||||||
type OrchestrationThread,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
|
type OrchestrationV2ThreadProjection,
|
||||||
|
type OrchestrationV2ThreadShell,
|
||||||
type ScopedProjectRef,
|
type ScopedProjectRef,
|
||||||
type ScopedThreadRef,
|
type ScopedThreadRef,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -36,9 +37,11 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
|
|||||||
return value ?? null;
|
return value ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null {
|
function latestUserMessageAt(
|
||||||
for (let index = thread.messages.length - 1; index >= 0; index -= 1) {
|
projection: OrchestrationV2ThreadProjection,
|
||||||
const message = thread.messages[index];
|
): OrchestrationV2ThreadShell["latestUserMessageAt"] {
|
||||||
|
for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
|
||||||
|
const message = projection.messages[index];
|
||||||
if (message?.role === "user") {
|
if (message?.role === "user") {
|
||||||
return message.createdAt;
|
return message.createdAt;
|
||||||
}
|
}
|
||||||
@@ -47,9 +50,14 @@ function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["
|
|||||||
return null;
|
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(
|
function threadDetailToShell(
|
||||||
environmentId: EnvironmentId,
|
environmentId: EnvironmentId,
|
||||||
thread: OrchestrationThread,
|
projection: OrchestrationV2ThreadProjection,
|
||||||
): EnvironmentThreadShell {
|
): EnvironmentThreadShell {
|
||||||
const thread = projection.thread;
|
const thread = projection.thread;
|
||||||
const latestRun = deriveLatestThreadRun(projection);
|
const latestRun = deriveLatestThreadRun(projection);
|
||||||
@@ -60,6 +68,7 @@ function threadDetailToShell(
|
|||||||
id: thread.id,
|
id: thread.id,
|
||||||
projectId: thread.projectId,
|
projectId: thread.projectId,
|
||||||
title: thread.title,
|
title: thread.title,
|
||||||
|
providerInstanceId: thread.providerInstanceId,
|
||||||
modelSelection: thread.modelSelection,
|
modelSelection: thread.modelSelection,
|
||||||
runtimeMode: thread.runtimeMode,
|
runtimeMode: thread.runtimeMode,
|
||||||
interactionMode: thread.interactionMode,
|
interactionMode: thread.interactionMode,
|
||||||
@@ -89,12 +98,8 @@ function threadDetailToShell(
|
|||||||
settledAt: thread.settledAt,
|
settledAt: thread.settledAt,
|
||||||
snoozedUntil: thread.snoozedUntil ?? null,
|
snoozedUntil: thread.snoozedUntil ?? null,
|
||||||
snoozedAt: thread.snoozedAt ?? null,
|
snoozedAt: thread.snoozedAt ?? null,
|
||||||
session: thread.session,
|
deletedAt: thread.deletedAt,
|
||||||
latestUserMessageAt: latestUserMessageAt(thread),
|
});
|
||||||
hasPendingApprovals: false,
|
|
||||||
hasPendingUserInput: false,
|
|
||||||
hasActionableProposedPlan: false,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
|
function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ export function makeRawThreadShell(
|
|||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
archivedAt: null,
|
archivedAt: null,
|
||||||
|
settledOverride: null,
|
||||||
|
settledAt: null,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
...input,
|
...input,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -16,8 +16,6 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node --watch src/bin.ts",
|
"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:codex-replay": "bun scripts/record-codex-app-server-replay-fixture.ts",
|
||||||
"record:claude-replay": "bun scripts/record-claude-agent-sdk-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",
|
"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:",
|
"@types/node": "catalog:",
|
||||||
"effect-acp": "workspace:*",
|
"effect-acp": "workspace:*",
|
||||||
"effect-codex-app-server": "workspace:*",
|
"effect-codex-app-server": "workspace:*",
|
||||||
"tsdown": "catalog:",
|
"vite-plus": "catalog:"
|
||||||
"typescript": "catalog:",
|
|
||||||
"vitest": "catalog:"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^22.16 || ^23.11 || >=24.10"
|
"node": "^22.16 || ^23.11 || >=24.10"
|
||||||
|
|||||||
@@ -83,18 +83,30 @@ let currentReasoning = "medium";
|
|||||||
let currentContext = "272k";
|
let currentContext = "272k";
|
||||||
let currentFast = false;
|
let currentFast = false;
|
||||||
let authenticated = !requiresAuthentication;
|
let authenticated = !requiresAuthentication;
|
||||||
|
let promptCount = 0;
|
||||||
|
let overlappingFirstPromptId: string | undefined;
|
||||||
const cancelledSessions = new Set<string>();
|
const cancelledSessions = new Set<string>();
|
||||||
|
|
||||||
|
function promptIdFromRequestMeta(
|
||||||
|
request: Pick<AcpSchema.PromptRequest, "_meta">,
|
||||||
|
): 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 {
|
function logExit(reason: string): void {
|
||||||
if (!exitLogPath) {
|
if (!exitLogPath) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||||
}
|
}
|
||||||
|
|
||||||
function logResidualCallbackResponse(kind: string): void {
|
function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||||
if (!residualCallbackResponseLogPath) return;
|
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||||
NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function logResidualCallbackResponse(kind: string): void {
|
function logResidualCallbackResponse(kind: string): void {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
AuthRelayWriteScope,
|
AuthRelayWriteScope,
|
||||||
AuthReviewWriteScope,
|
AuthReviewWriteScope,
|
||||||
AuthTerminalOperateScope,
|
AuthTerminalOperateScope,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_V2_WS_METHODS,
|
||||||
type AuthEnvironmentScope,
|
type AuthEnvironmentScope,
|
||||||
WS_METHODS,
|
WS_METHODS,
|
||||||
WsRpcGroup,
|
WsRpcGroup,
|
||||||
@@ -21,6 +21,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
|||||||
* runtime failure.
|
* runtime failure.
|
||||||
*/
|
*/
|
||||||
export const RPC_REQUIRED_SCOPES = {
|
export const RPC_REQUIRED_SCOPES = {
|
||||||
|
<<<<<<< HEAD
|
||||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||||
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
||||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||||
@@ -29,6 +30,19 @@ export const RPC_REQUIRED_SCOPES = {
|
|||||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
|
[ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
|
||||||
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
|
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
|
||||||
[ORCHESTRATION_WS_METHODS.subscribeThread]: 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.serverProbe]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
|
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
|
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
|
||||||
@@ -49,6 +63,12 @@ export const RPC_REQUIRED_SCOPES = {
|
|||||||
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
|
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
|
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
|
||||||
[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
|
[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.cloudGetRelayClientStatus]: AuthRelayReadScope,
|
||||||
[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
|
[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
|
||||||
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
|
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
|
||||||
@@ -62,6 +82,7 @@ export const RPC_REQUIRED_SCOPES = {
|
|||||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||||
|
[WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope,
|
||||||
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
||||||
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
|
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
|
||||||
|
|||||||
@@ -356,6 +356,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
tailscaleServePort: 443,
|
tailscaleServePort: 443,
|
||||||
});
|
});
|
||||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||||
|
assert.equal(resolved.desktopTelemetryFd, 4);
|
||||||
|
assert.equal(resolved.desktopTelemetryControlFd, 5);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.t
|
|||||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||||
import * as ProjectService from "../project/ProjectService.ts";
|
import * as ProjectService from "../project/ProjectService.ts";
|
||||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||||
|
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||||
import {
|
import {
|
||||||
ProjectLiveServerDeclaredResponseError,
|
ProjectLiveServerDeclaredResponseError,
|
||||||
@@ -53,6 +54,7 @@ const makeConfig = (baseDir: string) =>
|
|||||||
...derivedPaths,
|
...derivedPaths,
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl: undefined,
|
devUrl: undefined,
|
||||||
|
devAllowedOrigins: [],
|
||||||
noBrowser: true,
|
noBrowser: true,
|
||||||
startupPresentation: "browser",
|
startupPresentation: "browser",
|
||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
@@ -70,6 +72,7 @@ const readProjects = (baseDir: string) =>
|
|||||||
Layer.provideMerge(ProjectEnrichmentService.layer),
|
Layer.provideMerge(ProjectEnrichmentService.layer),
|
||||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||||
Layer.provideMerge(ProjectFaviconResolver.layer),
|
Layer.provideMerge(ProjectFaviconResolver.layer),
|
||||||
|
Layer.provideMerge(T3ProjectFileLoader.layer),
|
||||||
Layer.provideMerge(WorkspacePaths.layer),
|
Layer.provideMerge(WorkspacePaths.layer),
|
||||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.t
|
|||||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||||
import * as ProjectService from "../project/ProjectService.ts";
|
import * as ProjectService from "../project/ProjectService.ts";
|
||||||
|
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||||
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
|
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
|
||||||
import {
|
import {
|
||||||
clearPersistedServerRuntimeState,
|
clearPersistedServerRuntimeState,
|
||||||
@@ -198,7 +199,12 @@ const projectCommandUuid = Crypto.Crypto.pipe(
|
|||||||
const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe(
|
const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe(
|
||||||
Layer.provideMerge(ProjectEnrichmentService.layer),
|
Layer.provideMerge(ProjectEnrichmentService.layer),
|
||||||
Layer.provideMerge(RepositoryIdentityResolver.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(WorkspacePaths.layer),
|
||||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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", () =>
|
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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.<b>.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", () =>
|
it.effect("creates a commit when working tree is dirty", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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", "[email protected]"]);
|
||||||
|
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", () =>
|
it.effect("uses custom commit message when provided", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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", () =>
|
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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", () =>
|
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -2074,6 +2520,123 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
12_000,
|
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",
|
||||||
|
"[email protected]: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", () =>
|
it.effect("creates PR when one does not already exist", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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", "[email protected]"]);
|
||||||
|
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(
|
it.effect(
|
||||||
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
|
"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"]);
|
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
|
||||||
const remoteDir = yield* createBareRemote();
|
const remoteDir = yield* createBareRemote();
|
||||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
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, ["add", "changes.txt"]);
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
|
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
|
||||||
@@ -2166,6 +2785,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
const { manager, ghCalls } = yield* makeManager({
|
const { manager, ghCalls } = yield* makeManager({
|
||||||
ghScenario: {
|
ghScenario: {
|
||||||
prListSequence: [
|
prListSequence: [
|
||||||
|
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||||
JSON.stringify([
|
JSON.stringify([
|
||||||
{
|
{
|
||||||
number: 1661,
|
number: 1661,
|
||||||
@@ -2183,6 +2803,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
|
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||||
JSON.stringify([
|
JSON.stringify([
|
||||||
{
|
{
|
||||||
number: 188,
|
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", () =>
|
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
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, ["push", "-u", "origin", "main"]);
|
||||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
|
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, ["add", "fork-main-second.txt"]);
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
|
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
|
||||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
|
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
|
||||||
|
|||||||
@@ -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<string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
|
||||||
operation: string,
|
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
|
||||||
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<string, TextGenerationError, Scope.Scope> => {
|
|
||||||
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<void, never> =>
|
|
||||||
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<MaterializedImageAttachments, TextGenerationError> {
|
|
||||||
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* <S extends Schema.Top>({
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson,
|
|
||||||
imagePaths = [],
|
|
||||||
cleanupPaths = [],
|
|
||||||
modelSelection,
|
|
||||||
}: {
|
|
||||||
operation:
|
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
cwd: string;
|
|
||||||
prompt: string;
|
|
||||||
outputSchemaJson: S;
|
|
||||||
imagePaths?: ReadonlyArray<string>;
|
|
||||||
cleanupPaths?: ReadonlyArray<string>;
|
|
||||||
modelSelection: CodexModelSelection;
|
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
|
||||||
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);
|
|
||||||
@@ -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, string>): 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<A, E, R>(
|
|
||||||
env: Record<string, string>,
|
|
||||||
effect: Effect.Effect<A, E, R>,
|
|
||||||
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
|
|
||||||
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<string> {
|
|
||||||
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<string, unknown> });
|
|
||||||
|
|
||||||
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 });
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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<CodexTextGen, TextGenerationShape>()(
|
|
||||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
|
|
||||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
|
|
||||||
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
|
|
||||||
"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),
|
|
||||||
);
|
|
||||||
@@ -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<ChatAttachment> | 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<ChatAttachment> | undefined;
|
|
||||||
/** What model and provider to use for generation. */
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ThreadTitleGenerationResult {
|
|
||||||
title: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TextGenerationService {
|
|
||||||
generateCommitMessage(
|
|
||||||
input: CommitMessageGenerationInput,
|
|
||||||
): Promise<CommitMessageGenerationResult>;
|
|
||||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
|
||||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
|
||||||
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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<CommitMessageGenerationResult, TextGenerationError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate pull request title/body from branch and diff context.
|
|
||||||
*/
|
|
||||||
readonly generatePrContent: (
|
|
||||||
input: PrContentGenerationInput,
|
|
||||||
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate a concise branch name from a user message.
|
|
||||||
*/
|
|
||||||
readonly generateBranchName: (
|
|
||||||
input: BranchNameGenerationInput,
|
|
||||||
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate a concise thread title from a user's first message.
|
|
||||||
*/
|
|
||||||
readonly generateThreadTitle: (
|
|
||||||
input: ThreadTitleGenerationInput,
|
|
||||||
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TextGeneration - Service tag for commit and PR text generation.
|
|
||||||
*/
|
|
||||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
|
||||||
"t3/git/Services/TextGeneration",
|
|
||||||
) {}
|
|
||||||
@@ -21,7 +21,10 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({
|
|||||||
|
|
||||||
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
||||||
McpSessionRegistry.__testing
|
McpSessionRegistry.__testing
|
||||||
.make({ now })
|
.make({
|
||||||
|
now,
|
||||||
|
livenessWindowMs: 100,
|
||||||
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.provideService(HttpServer.HttpServer, httpServer),
|
Effect.provideService(HttpServer.HttpServer, httpServer),
|
||||||
Effect.provideService(ServerEnvironment.ServerEnvironment, fakeEnvironment),
|
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* () {
|
Effect.gen(function* () {
|
||||||
let timestamp = 1_000;
|
let timestamp = 1_000;
|
||||||
const registry = yield* makeRegistry(() => timestamp);
|
const registry = yield* makeRegistry(() => timestamp);
|
||||||
@@ -81,12 +84,7 @@ it.effect("keeps credentials valid until they are explicitly revoked", () =>
|
|||||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||||
});
|
});
|
||||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||||
const resolved = yield* registry.resolve(token);
|
timestamp += 101;
|
||||||
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);
|
|
||||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export const layer = Layer.succeed(
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
resolve: () => Effect.succeed(undefined),
|
resolve: () => Effect.succeed(undefined),
|
||||||
|
touch: () => Effect.void,
|
||||||
revokeProviderSession: () => Effect.void,
|
revokeProviderSession: () => Effect.void,
|
||||||
revokeThread: () => Effect.void,
|
revokeThread: () => Effect.void,
|
||||||
revokeAll: Effect.void,
|
revokeAll: Effect.void,
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ export interface McpIssuedCredential {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface McpSessionRegistryShape {
|
export interface McpSessionRegistryShape {
|
||||||
/** Credentials have no time-based expiry and must be explicitly revoked by their owner. */
|
|
||||||
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
|
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
|
||||||
readonly resolve: (
|
readonly resolve: (
|
||||||
rawToken: string,
|
rawToken: string,
|
||||||
@@ -43,7 +42,9 @@ export class McpSessionRegistry extends Context.Service<
|
|||||||
>()("t3/mcp/McpSessionRegistry") {}
|
>()("t3/mcp/McpSessionRegistry") {}
|
||||||
|
|
||||||
interface CredentialRecord {
|
interface CredentialRecord {
|
||||||
|
readonly tokenHash: string;
|
||||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||||
|
readonly lastAliveAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RegistryState {
|
interface RegistryState {
|
||||||
@@ -51,9 +52,26 @@ interface RegistryState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface McpSessionRegistryOptions {
|
export interface McpSessionRegistryOptions {
|
||||||
|
readonly livenessWindowMs?: number;
|
||||||
readonly now?: () => 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 =>
|
const bytesToHex = (bytes: Uint8Array): string =>
|
||||||
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
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 httpServer = yield* HttpServer.HttpServer;
|
||||||
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
|
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
|
||||||
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
|
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
|
||||||
|
const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
|
||||||
const endpoint =
|
const endpoint =
|
||||||
httpServer.address._tag === "TcpAddress"
|
httpServer.address._tag === "TcpAddress"
|
||||||
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
|
? `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))
|
.digest("SHA-256", new TextEncoder().encode(token))
|
||||||
.pipe(Effect.map(bytesToHex), Effect.orDie);
|
.pipe(Effect.map(bytesToHex), Effect.orDie);
|
||||||
|
|
||||||
|
const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, 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")(
|
const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
|
||||||
function* (request) {
|
function* (request) {
|
||||||
const issuedAt = yield* currentTimeMillis;
|
const issuedAt = yield* currentTimeMillis;
|
||||||
@@ -104,8 +132,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
|||||||
issuedAt,
|
issuedAt,
|
||||||
};
|
};
|
||||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||||
const next = new Map(records);
|
const next = new Map(pruneDead(records, issuedAt));
|
||||||
next.set(tokenHash, { scope });
|
next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
|
||||||
return { records: next };
|
return { records: next };
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
@@ -125,8 +153,15 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
|||||||
function* (rawToken) {
|
function* (rawToken) {
|
||||||
if (rawToken.length === 0) return undefined;
|
if (rawToken.length === 0) return undefined;
|
||||||
const tokenHash = yield* hashToken(rawToken);
|
const tokenHash = yield* hashToken(rawToken);
|
||||||
const record = (yield* SynchronizedRef.get(state)).records.get(tokenHash);
|
const timestamp = yield* currentTimeMillis;
|
||||||
return record?.scope;
|
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;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -334,8 +334,10 @@ function runtimeModeRank(mode: RuntimeMode): number {
|
|||||||
return 0;
|
return 0;
|
||||||
case "auto-accept-edits":
|
case "auto-accept-edits":
|
||||||
return 1;
|
return 1;
|
||||||
case "full-access":
|
case "auto":
|
||||||
return 2;
|
return 2;
|
||||||
|
case "full-access":
|
||||||
|
return 3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import { FetchHttpClient } from "effect/unstable/http";
|
|||||||
import { describe } from "vite-plus/test";
|
import { describe } from "vite-plus/test";
|
||||||
|
|
||||||
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
|
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 { ServerConfig } from "../config.ts";
|
||||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.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(
|
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mergeAll(
|
Layer.mergeAll(
|
||||||
@@ -84,6 +90,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe(
|
|||||||
Layer.provide(serverConfigLayer),
|
Layer.provide(serverConfigLayer),
|
||||||
Layer.provide(serverSettingsLayer),
|
Layer.provide(serverSettingsLayer),
|
||||||
Layer.provide(providerInstanceRegistryLayer),
|
Layer.provide(providerInstanceRegistryLayer),
|
||||||
|
Layer.provide(backgroundPolicyLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@ import {
|
|||||||
type ProviderReplayTranscript,
|
type ProviderReplayTranscript,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Crypto from "effect/Crypto";
|
||||||
import * as FileSystem from "effect/FileSystem";
|
import * as FileSystem from "effect/FileSystem";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
@@ -159,7 +160,7 @@ export function makeAcpReplayRuntime(input: {
|
|||||||
) => Effect.Effect<
|
) => Effect.Effect<
|
||||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||||
EffectAcpErrors.AcpError,
|
EffectAcpErrors.AcpError,
|
||||||
Scope.Scope
|
Crypto.Crypto | Scope.Scope
|
||||||
> {
|
> {
|
||||||
const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString(
|
const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString(
|
||||||
"base64",
|
"base64",
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import {
|
|||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { modelSelectionsEqual } from "@t3tools/shared/model";
|
import { modelSelectionsEqual } from "@t3tools/shared/model";
|
||||||
import * as Cause from "effect/Cause";
|
import * as Cause from "effect/Cause";
|
||||||
|
import * as Crypto from "effect/Crypto";
|
||||||
import * as DateTime from "effect/DateTime";
|
import * as DateTime from "effect/DateTime";
|
||||||
import * as Deferred from "effect/Deferred";
|
import * as Deferred from "effect/Deferred";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
@@ -198,7 +199,7 @@ export interface AcpAdapterV2Flavor {
|
|||||||
) => Effect.Effect<
|
) => Effect.Effect<
|
||||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||||
EffectAcpErrors.AcpError,
|
EffectAcpErrors.AcpError,
|
||||||
Scope.Scope
|
Crypto.Crypto | Scope.Scope
|
||||||
>;
|
>;
|
||||||
readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
|
readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
|
||||||
readonly registerExtensions?: (
|
readonly registerExtensions?: (
|
||||||
@@ -339,6 +340,7 @@ export interface AcpAdapterV2SubagentUpdate {
|
|||||||
export interface AcpAdapterV2Options {
|
export interface AcpAdapterV2Options {
|
||||||
readonly instanceId: ProviderInstanceId;
|
readonly instanceId: ProviderInstanceId;
|
||||||
readonly flavor: AcpAdapterV2Flavor;
|
readonly flavor: AcpAdapterV2Flavor;
|
||||||
|
readonly crypto: Crypto.Crypto;
|
||||||
readonly fileSystem: FileSystem.FileSystem;
|
readonly fileSystem: FileSystem.FileSystem;
|
||||||
readonly idAllocator: IdAllocatorV2Shape;
|
readonly idAllocator: IdAllocatorV2Shape;
|
||||||
readonly serverConfig: ServerConfig["Service"];
|
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) {
|
if (continuationRequests === undefined) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -2883,6 +2885,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
providerThreadId: route.providerThreadId,
|
providerThreadId: route.providerThreadId,
|
||||||
driver,
|
driver,
|
||||||
detail: null,
|
detail: null,
|
||||||
|
clearIfCurrent: () =>
|
||||||
|
continuationPermit.withPermit(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if ((yield* Ref.get(continuationGeneration)) === generation) {
|
||||||
|
yield* Ref.set(continuationRequested, false);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
dispatchIfCurrent: (effect) =>
|
dispatchIfCurrent: (effect) =>
|
||||||
continuationPermit.withPermit(
|
continuationPermit.withPermit(
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -2900,11 +2910,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
return Option.none();
|
return Option.none();
|
||||||
}
|
}
|
||||||
if (!(yield* Ref.get(continuationRequested))) return Option.none();
|
if (!(yield* Ref.get(continuationRequested))) return Option.none();
|
||||||
// Clear after success or failure so a dropped dispatch does not
|
// A successful durable dispatch owns the sticky flag until its
|
||||||
// stick the flag and pin hasPendingBackgroundWork forever.
|
// 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);
|
const exit = yield* Effect.exit(effect);
|
||||||
yield* clearIfOwner;
|
|
||||||
if (Exit.isFailure(exit)) {
|
if (Exit.isFailure(exit)) {
|
||||||
|
yield* clearIfOwner;
|
||||||
return yield* Effect.failCause(exit.cause);
|
return yield* Effect.failCause(exit.cause);
|
||||||
}
|
}
|
||||||
return Option.some(exit.value);
|
return Option.some(exit.value);
|
||||||
@@ -4111,8 +4124,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
runtime = yield* flavor
|
runtime = yield* flavor
|
||||||
.makeRuntime(makeRuntimeInput(runtimeGeneration))
|
.makeRuntime(makeRuntimeInput(runtimeGeneration))
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.provideService(Crypto.Crypto, options.crypto),
|
|
||||||
Effect.provideService(Scope.Scope, runtimeScope),
|
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 +
|
// Minimal quiet for all models (no per-model carveouts). Defer +
|
||||||
// awaitingBackgroundHydration hold the turn through monitors; this
|
// awaitingBackgroundHydration hold the turn through monitors; this
|
||||||
// is only a short debounce after the last rearm so a slightly late
|
// is only a short debounce after the last rearm so a slightly late
|
||||||
// first post-hydration assistant chunk is not dropped. Multi-second
|
// post-hydration assistant chunk stays in the same continuation.
|
||||||
// floors (4–20s) only prolonged Working on grok-4.5.
|
// 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.gen(function* () {
|
||||||
yield* Effect.sleep("2000 millis");
|
yield* Effect.sleep("3000 millis");
|
||||||
if (
|
if (
|
||||||
context.finalized ||
|
context.finalized ||
|
||||||
context.interrupted ||
|
context.interrupted ||
|
||||||
@@ -4587,7 +4602,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
const needsSessionActivation =
|
const needsSessionActivation =
|
||||||
(yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt;
|
(yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt;
|
||||||
if (needsSessionActivation) {
|
if (needsSessionActivation) {
|
||||||
const activated = yield* activateSession(requestedSessionId);
|
const activated = yield* activateSession(requestedSessionId, turnInput.threadId);
|
||||||
yield* Ref.set(activeSessionId, activated.sessionId);
|
yield* Ref.set(activeSessionId, activated.sessionId);
|
||||||
yield* Ref.set(activeSessionSetup, activated);
|
yield* Ref.set(activeSessionSetup, activated);
|
||||||
yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy);
|
yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy);
|
||||||
@@ -4991,7 +5006,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
loadingRole: null,
|
loadingRole: null,
|
||||||
loadingIndex: 0,
|
loadingIndex: 0,
|
||||||
});
|
});
|
||||||
const activated = yield* activateSession(sessionId);
|
const activated = yield* activateSession(
|
||||||
|
sessionId,
|
||||||
|
threadInput.providerThread.appThreadId,
|
||||||
|
);
|
||||||
yield* Ref.set(activeSessionId, activated.sessionId);
|
yield* Ref.set(activeSessionId, activated.sessionId);
|
||||||
yield* Ref.set(activeSessionSetup, activated);
|
yield* Ref.set(activeSessionSetup, activated);
|
||||||
const nextSelection = threadInput.modelSelection ?? input.modelSelection;
|
const nextSelection = threadInput.modelSelection ?? input.modelSelection;
|
||||||
@@ -5295,6 +5313,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
|||||||
Effect.timeoutOption("10 seconds"),
|
Effect.timeoutOption("10 seconds"),
|
||||||
);
|
);
|
||||||
if (Option.isNone(stopped)) {
|
if (Option.isNone(stopped)) {
|
||||||
|
if (!context.finalized) {
|
||||||
|
yield* finalizeTurn(context, "interrupted");
|
||||||
|
}
|
||||||
return yield* new ProviderAdapterProtocolError({
|
return yield* new ProviderAdapterProtocolError({
|
||||||
driver,
|
driver,
|
||||||
detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`,
|
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,
|
loadingRole: null,
|
||||||
loadingIndex: 0,
|
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(activeSessionId, activated.sessionId);
|
||||||
yield* Ref.set(activeSessionSetup, activated);
|
yield* Ref.set(activeSessionSetup, activated);
|
||||||
yield* Ref.set(activeSelection, null);
|
yield* Ref.set(activeSelection, null);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
|||||||
import { assert, describe, it } from "@effect/vitest";
|
import { assert, describe, it } from "@effect/vitest";
|
||||||
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Crypto from "effect/Crypto";
|
||||||
import * as FileSystem from "effect/FileSystem";
|
import * as FileSystem from "effect/FileSystem";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Path from "effect/Path";
|
import * as Path from "effect/Path";
|
||||||
@@ -107,6 +108,7 @@ describe("AcpRegistryAdapterV2", () => {
|
|||||||
});
|
});
|
||||||
const instanceId = ProviderInstanceId.make("acp-registry-fixture");
|
const instanceId = ProviderInstanceId.make("acp-registry-fixture");
|
||||||
const adapter = makeAcpRegistryAdapterV2({
|
const adapter = makeAcpRegistryAdapterV2({
|
||||||
|
crypto: yield* Crypto.Crypto,
|
||||||
instanceId,
|
instanceId,
|
||||||
settings,
|
settings,
|
||||||
environment: {
|
environment: {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { AcpRegistrySettings } from "@t3tools/contracts";
|
import { AcpRegistrySettings } from "@t3tools/contracts";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Crypto from "effect/Crypto";
|
||||||
import * as FileSystem from "effect/FileSystem";
|
import * as FileSystem from "effect/FileSystem";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Path from "effect/Path";
|
import * as Path from "effect/Path";
|
||||||
@@ -41,6 +42,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac
|
|||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const crypto = yield* Crypto.Crypto;
|
||||||
const idAllocator = yield* IdAllocatorV2;
|
const idAllocator = yield* IdAllocatorV2;
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
const replayDir = yield* fileSystem
|
const replayDir = yield* fileSystem
|
||||||
@@ -57,6 +59,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac
|
|||||||
settings: REPLAY_SETTINGS,
|
settings: REPLAY_SETTINGS,
|
||||||
environment: {},
|
environment: {},
|
||||||
childProcessSpawner,
|
childProcessSpawner,
|
||||||
|
crypto,
|
||||||
fileSystem,
|
fileSystem,
|
||||||
idAllocator,
|
idAllocator,
|
||||||
resolver: {
|
resolver: {
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ export interface AcpRegistryAdapterV2Options {
|
|||||||
readonly settings: AcpRegistrySettings;
|
readonly settings: AcpRegistrySettings;
|
||||||
readonly environment: NodeJS.ProcessEnv;
|
readonly environment: NodeJS.ProcessEnv;
|
||||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||||
|
readonly crypto: Crypto.Crypto;
|
||||||
readonly fileSystem: FileSystem.FileSystem;
|
readonly fileSystem: FileSystem.FileSystem;
|
||||||
readonly idAllocator: IdAllocatorV2["Service"];
|
readonly idAllocator: IdAllocatorV2["Service"];
|
||||||
readonly resolver: AcpRegistryResolverShape;
|
readonly resolver: AcpRegistryResolverShape;
|
||||||
@@ -59,7 +60,7 @@ export interface AcpRegistryAdapterV2Options {
|
|||||||
) => Effect.Effect<
|
) => Effect.Effect<
|
||||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||||
EffectAcpErrors.AcpError,
|
EffectAcpErrors.AcpError,
|
||||||
Scope.Scope
|
Crypto.Crypto | Scope.Scope
|
||||||
>;
|
>;
|
||||||
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||||
}
|
}
|
||||||
@@ -70,7 +71,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) {
|
|||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||||
EffectAcpErrors.AcpError,
|
EffectAcpErrors.AcpError,
|
||||||
Scope.Scope
|
Crypto.Crypto | Scope.Scope
|
||||||
> =>
|
> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const resolved = yield* options.resolver
|
const resolved = yield* options.resolver
|
||||||
@@ -111,6 +112,7 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
|
|||||||
return makeAcpAdapterV2({
|
return makeAcpAdapterV2({
|
||||||
instanceId: options.instanceId,
|
instanceId: options.instanceId,
|
||||||
flavor,
|
flavor,
|
||||||
|
crypto: options.crypto,
|
||||||
fileSystem: options.fileSystem,
|
fileSystem: options.fileSystem,
|
||||||
idAllocator: options.idAllocator,
|
idAllocator: options.idAllocator,
|
||||||
serverConfig: options.serverConfig,
|
serverConfig: options.serverConfig,
|
||||||
@@ -139,6 +141,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
|||||||
function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
|
function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
|
||||||
const hostEnvironment = yield* HostProcessEnvironment;
|
const hostEnvironment = yield* HostProcessEnvironment;
|
||||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const crypto = yield* Crypto.Crypto;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const idAllocator = yield* IdAllocatorV2;
|
const idAllocator = yield* IdAllocatorV2;
|
||||||
const providerEventLoggers = yield* ProviderEventLoggers;
|
const providerEventLoggers = yield* ProviderEventLoggers;
|
||||||
@@ -152,6 +155,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
|||||||
settings: { ...input.config, enabled: input.enabled },
|
settings: { ...input.config, enabled: input.enabled },
|
||||||
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
||||||
childProcessSpawner,
|
childProcessSpawner,
|
||||||
|
crypto,
|
||||||
fileSystem,
|
fileSystem,
|
||||||
idAllocator,
|
idAllocator,
|
||||||
resolver,
|
resolver,
|
||||||
|
|||||||
@@ -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", () => {
|
it("keeps approval-required mode interactive with danger-full-access sandboxing", () => {
|
||||||
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(
|
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(
|
||||||
ProviderAdapterV2RuntimePolicy.make({
|
ProviderAdapterV2RuntimePolicy.make({
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ import * as Stream from "effect/Stream";
|
|||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import {
|
import {
|
||||||
CLAUDE_PROVIDER,
|
CLAUDE_PROVIDER,
|
||||||
|
CLAUDE_DEFAULT_INSTANCE_ID,
|
||||||
|
CLAUDE_DRIVER_KIND,
|
||||||
|
ClaudeAdapterV2Driver,
|
||||||
ClaudeAgentSdkQueryRunner,
|
ClaudeAgentSdkQueryRunner,
|
||||||
ClaudeAgentSdkQueryRunnerError,
|
ClaudeAgentSdkQueryRunnerError,
|
||||||
makeClaudeUserMessage,
|
makeClaudeUserMessage,
|
||||||
@@ -159,6 +162,11 @@ export const ClaudeAgentSdkReplayError = Schema.Union([
|
|||||||
ClaudeReplayDriverError,
|
ClaudeReplayDriverError,
|
||||||
]);
|
]);
|
||||||
export type ClaudeAgentSdkReplayError = typeof ClaudeAgentSdkReplayError.Type;
|
export type ClaudeAgentSdkReplayError = typeof ClaudeAgentSdkReplayError.Type;
|
||||||
|
export const ClaudeOrchestratorReplayHarnessError = Schema.Union([
|
||||||
|
ClaudeAgentSdkReplayError,
|
||||||
|
ProviderAdapterDriverCreateError,
|
||||||
|
]);
|
||||||
|
export type ClaudeOrchestratorReplayHarnessError = typeof ClaudeOrchestratorReplayHarnessError.Type;
|
||||||
|
|
||||||
interface ClaudeQueryOpenFrame {
|
interface ClaudeQueryOpenFrame {
|
||||||
readonly type: "query.open";
|
readonly type: "query.open";
|
||||||
@@ -761,7 +769,6 @@ export function makeClaudeProviderAdapterRegistryReplayLayer(
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
return layerFromProviderAdapter.pipe(Layer.provide(adapterLayer));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function replayClaudeAgentSdkTranscript(input: {
|
export async function replayClaudeAgentSdkTranscript(input: {
|
||||||
@@ -2405,7 +2412,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
|
|||||||
|
|
||||||
export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
||||||
ClaudeAgentSdkReplayTranscript,
|
ClaudeAgentSdkReplayTranscript,
|
||||||
ClaudeAgentSdkReplayError
|
ClaudeOrchestratorReplayHarnessError
|
||||||
> = {
|
> = {
|
||||||
driver: CLAUDE_PROVIDER,
|
driver: CLAUDE_PROVIDER,
|
||||||
decodeTranscript: (transcript) =>
|
decodeTranscript: (transcript) =>
|
||||||
|
|||||||
@@ -64,10 +64,8 @@ import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
|||||||
import { compileClaudeModelSelection } from "../../claudeModelOptions.ts";
|
import { compileClaudeModelSelection } from "../../claudeModelOptions.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
|
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
|
||||||
import {
|
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||||
type EventNdjsonLogger,
|
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
|
||||||
makeEventNdjsonLogger,
|
|
||||||
} from "../../provider/Layers/EventNdjsonLogger.ts";
|
|
||||||
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
||||||
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts";
|
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts";
|
||||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||||
@@ -477,15 +475,12 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
|
|||||||
export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
|
export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
|
||||||
ClaudeAgentSdkQueryRunner,
|
ClaudeAgentSdkQueryRunner,
|
||||||
never,
|
never,
|
||||||
Crypto.Crypto | ServerConfig
|
Crypto.Crypto | ProviderEventLoggers
|
||||||
> = Layer.effect(
|
> = Layer.effect(
|
||||||
ClaudeAgentSdkQueryRunner,
|
ClaudeAgentSdkQueryRunner,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const { providerEventLogPath } = yield* ServerConfig;
|
|
||||||
const crypto = yield* Crypto.Crypto;
|
const crypto = yield* Crypto.Crypto;
|
||||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
const { native: nativeEventLogger } = yield* ProviderEventLoggers;
|
||||||
stream: "native",
|
|
||||||
});
|
|
||||||
|
|
||||||
return ClaudeAgentSdkQueryRunner.of({
|
return ClaudeAgentSdkQueryRunner.of({
|
||||||
allocateSessionId: crypto.randomUUIDv4.pipe(
|
allocateSessionId: crypto.randomUUIDv4.pipe(
|
||||||
@@ -1176,6 +1171,8 @@ function permissionModeForClaudeRuntimePolicy(
|
|||||||
return "default";
|
return "default";
|
||||||
case "auto-accept-edits":
|
case "auto-accept-edits":
|
||||||
return "acceptEdits";
|
return "acceptEdits";
|
||||||
|
case "auto":
|
||||||
|
return "auto";
|
||||||
case "full-access":
|
case "full-access":
|
||||||
return "bypassPermissions";
|
return "bypassPermissions";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -265,7 +265,9 @@ describe("CodexAdapterV2 assistant message streaming", () => {
|
|||||||
describe("CodexAdapterV2 runtime policy", () => {
|
describe("CodexAdapterV2 runtime policy", () => {
|
||||||
it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
|
it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
|
||||||
Effect.gen(function* () {
|
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({
|
buildCodexTurnStartParams({
|
||||||
nativeThreadId: `native-${runtimeMode}`,
|
nativeThreadId: `native-${runtimeMode}`,
|
||||||
codexInput: [{ type: "text", text: "test" }],
|
codexInput: [{ type: "text", text: "test" }],
|
||||||
@@ -282,13 +284,20 @@ describe("CodexAdapterV2 runtime policy", () => {
|
|||||||
|
|
||||||
const approvalRequired = yield* build("approval-required");
|
const approvalRequired = yield* build("approval-required");
|
||||||
const autoAcceptEdits = yield* build("auto-accept-edits");
|
const autoAcceptEdits = yield* build("auto-accept-edits");
|
||||||
|
const auto = yield* build("auto");
|
||||||
const fullAccess = yield* build("full-access");
|
const fullAccess = yield* build("full-access");
|
||||||
|
|
||||||
assert.equal(approvalRequired.approvalPolicy, "untrusted");
|
assert.equal(approvalRequired.approvalPolicy, "untrusted");
|
||||||
|
assert.equal(approvalRequired.approvalsReviewer, "user");
|
||||||
assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly");
|
assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly");
|
||||||
assert.equal(autoAcceptEdits.approvalPolicy, "on-request");
|
assert.equal(autoAcceptEdits.approvalPolicy, "on-request");
|
||||||
|
assert.equal(autoAcceptEdits.approvalsReviewer, "user");
|
||||||
assert.equal(autoAcceptEdits.sandboxPolicy?.type, "workspaceWrite");
|
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.approvalPolicy, "never");
|
||||||
|
assert.equal(fullAccess.approvalsReviewer, "user");
|
||||||
assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess");
|
assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -975,6 +984,9 @@ function codexReplayPreamble(input: {
|
|||||||
input: [{ type: "text", text: input.prompt }],
|
input: [{ type: "text", text: input.prompt }],
|
||||||
cwd: "/workspace",
|
cwd: "/workspace",
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
|
approvalPolicy: "never",
|
||||||
|
approvalsReviewer: "user",
|
||||||
|
sandboxPolicy: { type: "dangerFullAccess" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
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 CodexClient from "effect-codex-app-server/client";
|
||||||
import * as CodexReplay from "effect-codex-app-server/replay";
|
import * as CodexReplay from "effect-codex-app-server/replay";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
@@ -12,9 +12,15 @@ import * as Schema from "effect/Schema";
|
|||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||||
import { ProviderAdapterOpenSessionError } from "../ProviderAdapter.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 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>()(
|
export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass<CodexReplayTranscriptDecodeError>()(
|
||||||
"CodexReplayTranscriptDecodeError",
|
"CodexReplayTranscriptDecodeError",
|
||||||
@@ -33,6 +39,7 @@ export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass<Co
|
|||||||
export const CodexOrchestratorReplayHarnessError = Schema.Union([
|
export const CodexOrchestratorReplayHarnessError = Schema.Union([
|
||||||
CodexReplayTranscriptDecodeError,
|
CodexReplayTranscriptDecodeError,
|
||||||
CodexReplay.CodexAppServerReplayError,
|
CodexReplay.CodexAppServerReplayError,
|
||||||
|
ProviderAdapterDriverCreateError,
|
||||||
]);
|
]);
|
||||||
export type CodexOrchestratorReplayHarnessError = typeof CodexOrchestratorReplayHarnessError.Type;
|
export type CodexOrchestratorReplayHarnessError = typeof CodexOrchestratorReplayHarnessError.Type;
|
||||||
|
|
||||||
@@ -99,6 +106,7 @@ export function makeReplayServerConfig(
|
|||||||
baseDir,
|
baseDir,
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl: undefined,
|
devUrl: undefined,
|
||||||
|
devAllowedOrigins: [],
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
startupPresentation: "browser",
|
startupPresentation: "browser",
|
||||||
tailscaleServeEnabled: false,
|
tailscaleServeEnabled: false,
|
||||||
@@ -175,7 +183,7 @@ export function makeCodexProviderAdapterRegistryReplayLayer(input: {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
return layerFromProviderAdapter.pipe(Layer.provide(adapterLayer));
|
return registryLayer;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -568,6 +568,7 @@ function makeReplayServerConfig(
|
|||||||
baseDir,
|
baseDir,
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl: undefined,
|
devUrl: undefined,
|
||||||
|
devAllowedOrigins: [],
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
startupPresentation: "browser",
|
startupPresentation: "browser",
|
||||||
tailscaleServeEnabled: false,
|
tailscaleServeEnabled: false,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
|
|||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import { vi } from "vite-plus/test";
|
import { vi } from "vite-plus/test";
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
|
||||||
import {
|
import {
|
||||||
CursorAgentSdkRunner,
|
CursorAgentSdkRunner,
|
||||||
CursorAgentSdkRunnerError,
|
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", () => ({
|
vi.mock("@cursor/sdk", () => ({
|
||||||
Agent: {
|
Agent: {
|
||||||
create: cursorSdkMock.create,
|
create: cursorSdkMock.create,
|
||||||
@@ -103,8 +80,22 @@ vi.mock("@cursor/sdk", () => ({
|
|||||||
|
|
||||||
const testLayer = cursorAgentSdkRunnerLiveLayer.pipe(
|
const testLayer = cursorAgentSdkRunnerLiveLayer.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
Layer.succeed(ProviderEventLoggers, {
|
||||||
prefix: "t3-cursor-agent-sdk-runner-",
|
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),
|
Layer.provide(NodeServices.layer),
|
||||||
|
|||||||
@@ -17,11 +17,8 @@ import * as Effect from "effect/Effect";
|
|||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||||
import {
|
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
|
||||||
type EventNdjsonLogger,
|
|
||||||
makeEventNdjsonLogger,
|
|
||||||
} from "../../provider/Layers/EventNdjsonLogger.ts";
|
|
||||||
|
|
||||||
export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
|
export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
|
||||||
export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
|
export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
|
||||||
@@ -298,231 +295,231 @@ export function makeCursorAgentSdkProtocolLogger(input: {
|
|||||||
.pipe(Effect.ignore);
|
.pipe(Effect.ignore);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<CursorAgentSdkRunner, never, ServerConfig> =
|
export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<
|
||||||
Layer.effect(
|
CursorAgentSdkRunner,
|
||||||
CursorAgentSdkRunner,
|
never,
|
||||||
Effect.gen(function* () {
|
ProviderEventLoggers
|
||||||
const { providerEventLogPath } = yield* ServerConfig;
|
> = Layer.effect(
|
||||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
CursorAgentSdkRunner,
|
||||||
stream: "native",
|
Effect.gen(function* () {
|
||||||
});
|
const { native: nativeEventLogger } = yield* ProviderEventLoggers;
|
||||||
|
|
||||||
return CursorAgentSdkRunner.of({
|
return CursorAgentSdkRunner.of({
|
||||||
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
|
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
|
||||||
const protocolLogger = makeCursorAgentSdkProtocolLogger({
|
const protocolLogger = makeCursorAgentSdkProtocolLogger({
|
||||||
nativeEventLogger,
|
nativeEventLogger,
|
||||||
threadId: input.threadId,
|
threadId: input.threadId,
|
||||||
providerSessionId: input.providerSessionId,
|
providerSessionId: input.providerSessionId,
|
||||||
});
|
});
|
||||||
const log = (event: CursorAgentSdkProtocolLogEvent) =>
|
const log = (event: CursorAgentSdkProtocolLogEvent) =>
|
||||||
protocolLogger === undefined ? Effect.void : protocolLogger(event);
|
protocolLogger === undefined ? Effect.void : protocolLogger(event);
|
||||||
|
|
||||||
yield* log({
|
yield* log({
|
||||||
direction: "outgoing",
|
direction: "outgoing",
|
||||||
stage: "decoded",
|
stage: "decoded",
|
||||||
payload: {
|
payload: {
|
||||||
type: "agent.open",
|
type: "agent.open",
|
||||||
operation: input.operation,
|
operation: input.operation,
|
||||||
...(input.agentId === undefined ? {} : { agentId: input.agentId }),
|
...(input.agentId === undefined ? {} : { agentId: input.agentId }),
|
||||||
options: loggedCursorAgentOptions(input.options),
|
options: loggedCursorAgentOptions(input.options),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const agent = yield* Effect.tryPromise({
|
const agent = yield* Effect.tryPromise({
|
||||||
try: () =>
|
try: () =>
|
||||||
input.operation === "create"
|
input.operation === "create"
|
||||||
? Agent.create(input.options)
|
? Agent.create(input.options)
|
||||||
: Agent.resume(input.agentId!, input.options),
|
: Agent.resume(input.agentId!, input.options),
|
||||||
catch: (cause) => runnerError(cause, `agent.${input.operation}`),
|
catch: (cause) => runnerError(cause, `agent.${input.operation}`),
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* log({
|
yield* log({
|
||||||
direction: "incoming",
|
direction: "incoming",
|
||||||
stage: "decoded",
|
stage: "decoded",
|
||||||
payload: {
|
payload: {
|
||||||
type: "agent.opened",
|
type: "agent.opened",
|
||||||
agentId: agent.agentId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const cwd =
|
|
||||||
typeof input.options.local?.cwd === "string"
|
|
||||||
? input.options.local.cwd
|
|
||||||
: input.options.local?.cwd?.[0];
|
|
||||||
|
|
||||||
return {
|
|
||||||
agentId: agent.agentId,
|
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 cwd =
|
||||||
const pendingUpdates: Array<InteractionUpdate> = [];
|
typeof input.options.local?.cwd === "string"
|
||||||
let callbackFailure: { readonly cause: unknown } | undefined;
|
? input.options.local.cwd
|
||||||
let callbackChain = Promise.resolve();
|
: input.options.local?.cwd?.[0];
|
||||||
let runId = "";
|
|
||||||
const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
|
|
||||||
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 run = yield* Effect.tryPromise({
|
return {
|
||||||
try: () =>
|
agentId: agent.agentId,
|
||||||
agent.send(sendInput.message, {
|
send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
|
||||||
...sendInput.options,
|
const context = yield* Effect.context();
|
||||||
onDelta: async ({ update }) => {
|
yield* log({
|
||||||
if (!callbacksReady) {
|
direction: "outgoing",
|
||||||
pendingUpdates.push(update);
|
stage: "decoded",
|
||||||
return;
|
payload: {
|
||||||
}
|
type: "run.start",
|
||||||
await dispatchUpdate(update);
|
message: sendInput.message,
|
||||||
},
|
options: loggedCursorSendOptions(sendInput.options),
|
||||||
}),
|
},
|
||||||
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 {
|
let callbacksReady = false;
|
||||||
runId: run.id,
|
const pendingUpdates: Array<InteractionUpdate> = [];
|
||||||
agentId: run.agentId,
|
let callbackFailure: { readonly cause: unknown } | undefined;
|
||||||
wait: Effect.tryPromise({
|
let callbackChain = Promise.resolve();
|
||||||
try: async () => {
|
let runId = "";
|
||||||
const result = await run.wait();
|
const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
|
||||||
await callbackChain;
|
callbackChain = callbackChain
|
||||||
if (callbackFailure !== undefined) {
|
.then(() => {
|
||||||
throw callbackFailure.cause;
|
if (callbackFailure !== undefined) {
|
||||||
}
|
return;
|
||||||
return result;
|
}
|
||||||
},
|
return Effect.runPromiseWith(context)(
|
||||||
catch: (cause) => runnerError(cause, "run.wait"),
|
|
||||||
}).pipe(
|
|
||||||
Effect.tap((result) =>
|
|
||||||
log({
|
log({
|
||||||
direction: "incoming",
|
direction: "incoming",
|
||||||
stage: "decoded",
|
stage: "decoded",
|
||||||
payload: {
|
payload: {
|
||||||
type: "run.completed",
|
type: "interaction.update",
|
||||||
result,
|
runId,
|
||||||
|
update,
|
||||||
},
|
},
|
||||||
}),
|
}).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
|
||||||
),
|
);
|
||||||
),
|
})
|
||||||
cancel: log({
|
.catch((cause) => {
|
||||||
direction: "outgoing",
|
callbackFailure ??= { cause };
|
||||||
stage: "decoded",
|
});
|
||||||
payload: {
|
return callbackChain;
|
||||||
type: "run.cancel",
|
};
|
||||||
runId: run.id,
|
|
||||||
|
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(
|
catch: (cause) => runnerError(cause, "run.start"),
|
||||||
Effect.tryPromise({
|
});
|
||||||
try: async () => {
|
runId = run.id;
|
||||||
try {
|
yield* log({
|
||||||
await run.cancel();
|
direction: "incoming",
|
||||||
} catch (cause) {
|
stage: "decoded",
|
||||||
if (!isCursorCancellationError(cause)) {
|
payload: {
|
||||||
throw cause;
|
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({
|
Effect.tap((messages) =>
|
||||||
direction: "outgoing",
|
log({
|
||||||
stage: "decoded",
|
direction: "incoming",
|
||||||
payload: {
|
stage: "decoded",
|
||||||
type: "agent.close",
|
payload: {
|
||||||
agentId: agent.agentId,
|
type: "agent.messages",
|
||||||
},
|
agentId: agent.agentId,
|
||||||
}).pipe(
|
messages,
|
||||||
Effect.andThen(
|
},
|
||||||
Effect.try({
|
}),
|
||||||
try: () => agent.close(),
|
|
||||||
catch: (cause) => runnerError(cause, "agent.close"),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
} satisfies CursorAgentSdkSession;
|
),
|
||||||
}),
|
close: log({
|
||||||
assertComplete: Effect.void,
|
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,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { GrokSettings } from "@t3tools/contracts";
|
import { GrokSettings } from "@t3tools/contracts";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Crypto from "effect/Crypto";
|
||||||
import * as FileSystem from "effect/FileSystem";
|
import * as FileSystem from "effect/FileSystem";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Path from "effect/Path";
|
import * as Path from "effect/Path";
|
||||||
@@ -34,6 +35,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay
|
|||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const crypto = yield* Crypto.Crypto;
|
||||||
const idAllocator = yield* IdAllocatorV2;
|
const idAllocator = yield* IdAllocatorV2;
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
const replayDir = yield* fileSystem
|
const replayDir = yield* fileSystem
|
||||||
@@ -50,6 +52,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay
|
|||||||
settings: DEFAULT_GROK_SETTINGS,
|
settings: DEFAULT_GROK_SETTINGS,
|
||||||
environment: {},
|
environment: {},
|
||||||
childProcessSpawner,
|
childProcessSpawner,
|
||||||
|
crypto,
|
||||||
fileSystem,
|
fileSystem,
|
||||||
idAllocator,
|
idAllocator,
|
||||||
serverConfig,
|
serverConfig,
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ export interface GrokAdapterV2Options {
|
|||||||
readonly settings: GrokSettings;
|
readonly settings: GrokSettings;
|
||||||
readonly environment: NodeJS.ProcessEnv;
|
readonly environment: NodeJS.ProcessEnv;
|
||||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||||
|
readonly crypto: Crypto.Crypto;
|
||||||
readonly fileSystem: FileSystem.FileSystem;
|
readonly fileSystem: FileSystem.FileSystem;
|
||||||
readonly idAllocator: IdAllocatorV2["Service"];
|
readonly idAllocator: IdAllocatorV2["Service"];
|
||||||
readonly serverConfig: ServerConfig["Service"];
|
readonly serverConfig: ServerConfig["Service"];
|
||||||
@@ -104,7 +105,7 @@ export interface GrokAdapterV2Options {
|
|||||||
) => Effect.Effect<
|
) => Effect.Effect<
|
||||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||||
EffectAcpErrors.AcpError,
|
EffectAcpErrors.AcpError,
|
||||||
Scope.Scope
|
Crypto.Crypto | Scope.Scope
|
||||||
>;
|
>;
|
||||||
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||||
}
|
}
|
||||||
@@ -210,6 +211,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
|||||||
return makeAcpAdapterV2({
|
return makeAcpAdapterV2({
|
||||||
instanceId: options.instanceId,
|
instanceId: options.instanceId,
|
||||||
flavor,
|
flavor,
|
||||||
|
crypto: options.crypto,
|
||||||
fileSystem: options.fileSystem,
|
fileSystem: options.fileSystem,
|
||||||
idAllocator: options.idAllocator,
|
idAllocator: options.idAllocator,
|
||||||
serverConfig: options.serverConfig,
|
serverConfig: options.serverConfig,
|
||||||
@@ -236,6 +238,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
|||||||
function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
|
function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
|
||||||
const hostEnvironment = yield* HostProcessEnvironment;
|
const hostEnvironment = yield* HostProcessEnvironment;
|
||||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const crypto = yield* Crypto.Crypto;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const idAllocator = yield* IdAllocatorV2;
|
const idAllocator = yield* IdAllocatorV2;
|
||||||
const providerEventLoggers = yield* ProviderEventLoggers;
|
const providerEventLoggers = yield* ProviderEventLoggers;
|
||||||
@@ -247,6 +250,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
|||||||
settings: { ...input.config, enabled: input.enabled },
|
settings: { ...input.config, enabled: input.enabled },
|
||||||
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
||||||
childProcessSpawner,
|
childProcessSpawner,
|
||||||
|
crypto,
|
||||||
fileSystem,
|
fileSystem,
|
||||||
idAllocator,
|
idAllocator,
|
||||||
serverConfig,
|
serverConfig,
|
||||||
@@ -288,6 +292,7 @@ export const layer: Layer.Layer<
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const hostEnvironment = yield* HostProcessEnvironment;
|
const hostEnvironment = yield* HostProcessEnvironment;
|
||||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const crypto = yield* Crypto.Crypto;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const idAllocator = yield* IdAllocatorV2;
|
const idAllocator = yield* IdAllocatorV2;
|
||||||
const providerEventLoggers = yield* ProviderEventLoggers;
|
const providerEventLoggers = yield* ProviderEventLoggers;
|
||||||
@@ -299,6 +304,7 @@ export const layer: Layer.Layer<
|
|||||||
settings: DEFAULT_GROK_SETTINGS,
|
settings: DEFAULT_GROK_SETTINGS,
|
||||||
environment: hostEnvironment,
|
environment: hostEnvironment,
|
||||||
childProcessSpawner,
|
childProcessSpawner,
|
||||||
|
crypto,
|
||||||
fileSystem,
|
fileSystem,
|
||||||
idAllocator,
|
idAllocator,
|
||||||
serverConfig,
|
serverConfig,
|
||||||
|
|||||||
@@ -158,6 +158,17 @@ describe("OpenCodeAdapterV2", () => {
|
|||||||
);
|
);
|
||||||
assert.equal(permissionAction(granularApproval, "bash"), "ask");
|
assert.equal(permissionAction(granularApproval, "bash"), "ask");
|
||||||
assert.equal(permissionAction(granularApproval, "read"), "allow");
|
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", () => {
|
it("enforces non-interactive sandbox policy through OpenCode permissions", () => {
|
||||||
|
|||||||
@@ -334,6 +334,13 @@ function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript)
|
|||||||
detail: "OpenCode replay does not load inventory.",
|
detail: "OpenCode replay does not load inventory.",
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
loadInventoryFromCli: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new OpenCodeRuntimeError({
|
||||||
|
operation: "loadInventoryFromCli",
|
||||||
|
detail: "OpenCode replay does not load inventory.",
|
||||||
|
}),
|
||||||
|
),
|
||||||
} satisfies OpenCodeRuntimeShape);
|
} satisfies OpenCodeRuntimeShape);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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" });
|
rules.push({ permission: "edit", pattern: "*", action: "allow" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import { FetchHttpClient } from "effect/unstable/http";
|
|||||||
import { describe } from "vite-plus/test";
|
import { describe } from "vite-plus/test";
|
||||||
|
|
||||||
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
|
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 { ServerConfig } from "../config.ts";
|
||||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
|
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||||
@@ -48,6 +50,10 @@ const serverSettingsLayer = ServerSettingsService.layerTest({
|
|||||||
cursor: { enabled: true },
|
cursor: { enabled: true },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const backgroundPolicyLayer = BackgroundPolicy.layer.pipe(
|
||||||
|
Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())),
|
||||||
|
Layer.provide(serverSettingsLayer),
|
||||||
|
);
|
||||||
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
|
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mergeAll(
|
Layer.mergeAll(
|
||||||
@@ -68,6 +74,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe(
|
|||||||
Layer.provide(serverConfigLayer),
|
Layer.provide(serverConfigLayer),
|
||||||
Layer.provide(serverSettingsLayer),
|
Layer.provide(serverSettingsLayer),
|
||||||
Layer.provide(providerInstanceRegistryLayer),
|
Layer.provide(providerInstanceRegistryLayer),
|
||||||
|
Layer.provide(backgroundPolicyLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import { FetchHttpClient } from "effect/unstable/http";
|
|||||||
import { describe } from "vite-plus/test";
|
import { describe } from "vite-plus/test";
|
||||||
|
|
||||||
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
|
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 { ServerConfig } from "../config.ts";
|
||||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
|
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||||
@@ -47,6 +49,10 @@ const serverSettingsLayer = ServerSettingsService.layerTest({
|
|||||||
grok: { enabled: true },
|
grok: { enabled: true },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const backgroundPolicyLayer = BackgroundPolicy.layer.pipe(
|
||||||
|
Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())),
|
||||||
|
Layer.provide(serverSettingsLayer),
|
||||||
|
);
|
||||||
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
|
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mergeAll(
|
Layer.mergeAll(
|
||||||
@@ -67,6 +73,7 @@ const liveLayer = OrchestrationV2LayerLive.pipe(
|
|||||||
Layer.provide(serverConfigLayer),
|
Layer.provide(serverConfigLayer),
|
||||||
Layer.provide(serverSettingsLayer),
|
Layer.provide(serverSettingsLayer),
|
||||||
Layer.provide(providerInstanceRegistryLayer),
|
Layer.provide(providerInstanceRegistryLayer),
|
||||||
|
Layer.provide(backgroundPolicyLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -994,6 +994,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
|||||||
cause: `Thread ${command.threadId} is not archived.`,
|
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 =
|
const providerSwitchPlan =
|
||||||
command.type === "thread.model-selection.set" || command.type === "provider.switch"
|
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<Array<PendingOrchestrationEffectV2>>,
|
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
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 modelSelection = command.modelSelection ?? projection.thread.modelSelection;
|
||||||
const dispatchMode = command.dispatchMode;
|
const dispatchMode = command.dispatchMode;
|
||||||
const sourcePlanProjection =
|
const sourcePlanProjection =
|
||||||
|
|||||||
@@ -180,6 +180,10 @@ export function applyToProjection(
|
|||||||
case "thread.archived":
|
case "thread.archived":
|
||||||
case "thread.unarchived":
|
case "thread.unarchived":
|
||||||
case "thread.deleted":
|
case "thread.deleted":
|
||||||
|
case "thread.settled":
|
||||||
|
case "thread.unsettled":
|
||||||
|
case "thread.snoozed":
|
||||||
|
case "thread.unsnoozed":
|
||||||
case "thread.metadata-updated":
|
case "thread.metadata-updated":
|
||||||
case "thread.runtime-mode-updated":
|
case "thread.runtime-mode-updated":
|
||||||
case "thread.interaction-mode-updated":
|
case "thread.interaction-mode-updated":
|
||||||
|
|||||||
@@ -22,11 +22,11 @@ import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "./ProviderAdapte
|
|||||||
export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<ProviderAdapterRegistryLookupError>()(
|
export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<ProviderAdapterRegistryLookupError>()(
|
||||||
"ProviderAdapterRegistryLookupError",
|
"ProviderAdapterRegistryLookupError",
|
||||||
{
|
{
|
||||||
provider: ProviderKind,
|
instanceId: ProviderInstanceId,
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
override get message(): string {
|
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 {
|
export interface ProviderAdapterRegistryV2Shape {
|
||||||
readonly get: (
|
readonly get: (
|
||||||
provider: ProviderKind,
|
instanceId: ProviderInstanceId,
|
||||||
) => Effect.Effect<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error>;
|
) => Effect.Effect<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error>;
|
||||||
readonly list: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
readonly list: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||||
readonly getMetadata?: (instanceId: ProviderInstanceId) => Effect.Effect<
|
readonly getMetadata?: (instanceId: ProviderInstanceId) => Effect.Effect<
|
||||||
@@ -122,15 +122,15 @@ function makeRegistry(
|
|||||||
adapters: ReadonlyArray<ProviderAdapterV2Shape>,
|
adapters: ReadonlyArray<ProviderAdapterV2Shape>,
|
||||||
): ProviderAdapterRegistryV2Shape {
|
): ProviderAdapterRegistryV2Shape {
|
||||||
return {
|
return {
|
||||||
get: (provider) =>
|
get: (instanceId) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const adapter = adapters.find((candidate) => candidate.provider === provider);
|
const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
|
||||||
if (!adapter) {
|
if (!adapter) {
|
||||||
return yield* new ProviderAdapterRegistryLookupError({ provider });
|
return yield* new ProviderAdapterRegistryLookupError({ instanceId });
|
||||||
}
|
}
|
||||||
return adapter;
|
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* () {
|
Effect.gen(function* () {
|
||||||
const adapter = yield* ProviderAdapterV2;
|
const adapter = yield* ProviderAdapterV2;
|
||||||
return ProviderAdapterRegistryV2.of({
|
return ProviderAdapterRegistryV2.of({
|
||||||
get: (provider) =>
|
get: (instanceId) =>
|
||||||
adapter.provider === provider
|
adapter.instanceId === instanceId
|
||||||
? Effect.succeed(adapter)
|
? Effect.succeed(adapter)
|
||||||
: Effect.fail(new ProviderAdapterRegistryLookupError({ provider })),
|
: Effect.fail(new ProviderAdapterRegistryLookupError({ instanceId })),
|
||||||
list: () => Effect.succeed([adapter.provider]),
|
list: () => Effect.succeed([adapter.instanceId]),
|
||||||
} satisfies ProviderAdapterRegistryV2Shape);
|
} satisfies ProviderAdapterRegistryV2Shape);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -26,6 +26,8 @@ export interface ProviderContinuationRequest {
|
|||||||
readonly dispatchIfCurrent?: <A, E, R>(
|
readonly dispatchIfCurrent?: <A, E, R>(
|
||||||
effect: Effect.Effect<A, E, R>,
|
effect: Effect.Effect<A, E, R>,
|
||||||
) => Effect.Effect<Option.Option<A>, E, R>;
|
) => Effect.Effect<Option.Option<A>, E, R>;
|
||||||
|
/** Clears a pending offer that the continuation worker intentionally drops. */
|
||||||
|
readonly clearIfCurrent?: () => Effect.Effect<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -32,8 +32,12 @@ export const workerLive = Layer.effectDiscard(
|
|||||||
threadId: request.threadId,
|
threadId: request.threadId,
|
||||||
providerThreadId: request.providerThreadId,
|
providerThreadId: request.providerThreadId,
|
||||||
});
|
});
|
||||||
// Still run the guard so adapters can clear sticky continuationRequested.
|
// No continuation turn will start to clear the adapter's sticky offer.
|
||||||
if (request.dispatchIfCurrent !== undefined) {
|
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);
|
yield* request.dispatchIfCurrent(Effect.void);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ const emptyState: TestProviderRuntimeState = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const modelSelection = {
|
const modelSelection = {
|
||||||
provider: "codex",
|
instanceId: ProviderInstanceId.make("codex"),
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
} satisfies ModelSelection;
|
} satisfies ModelSelection;
|
||||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {
|
|||||||
OrchestrationV2DomainEvent,
|
OrchestrationV2DomainEvent,
|
||||||
OrchestrationV2ProviderSession,
|
OrchestrationV2ProviderSession,
|
||||||
OrchestrationV2RuntimeRequest,
|
OrchestrationV2RuntimeRequest,
|
||||||
ProviderKind,
|
ProviderInstanceId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -62,13 +62,13 @@ export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.T
|
|||||||
export class ProviderSessionOpenError extends Schema.TaggedErrorClass<ProviderSessionOpenError>()(
|
export class ProviderSessionOpenError extends Schema.TaggedErrorClass<ProviderSessionOpenError>()(
|
||||||
"ProviderSessionOpenError",
|
"ProviderSessionOpenError",
|
||||||
{
|
{
|
||||||
provider: ProviderKind,
|
instanceId: ProviderInstanceId,
|
||||||
providerSessionId: ProviderSessionId,
|
providerSessionId: ProviderSessionId,
|
||||||
cause: Schema.optional(Schema.Defect()),
|
cause: Schema.optional(Schema.Defect()),
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
override get message(): string {
|
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(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
new ProviderSessionOpenError({
|
new ProviderSessionOpenError({
|
||||||
provider: input.modelSelection.provider,
|
instanceId: input.modelSelection.instanceId,
|
||||||
providerSessionId: input.providerSessionId,
|
providerSessionId: input.providerSessionId,
|
||||||
cause,
|
cause,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it, vi } from "@effect/vitest";
|
||||||
import {
|
import {
|
||||||
CheckpointScopeId,
|
CheckpointScopeId,
|
||||||
CommandId,
|
CommandId,
|
||||||
@@ -32,6 +32,7 @@ import * as Option from "effect/Option";
|
|||||||
import * as Ref from "effect/Ref";
|
import * as Ref from "effect/Ref";
|
||||||
import * as Stream from "effect/Stream";
|
import * as Stream from "effect/Stream";
|
||||||
|
|
||||||
|
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
|
||||||
import { ServerSettingsService } from "../serverSettings.ts";
|
import { ServerSettingsService } from "../serverSettings.ts";
|
||||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||||
import { EventSinkV2 } from "./EventSink.ts";
|
import { EventSinkV2 } from "./EventSink.ts";
|
||||||
@@ -307,6 +308,77 @@ it.effect("rechecks run ownership immediately before calling the provider", () =
|
|||||||
}).pipe(Effect.provide(RunExecutionTestLayer)),
|
}).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<ReadonlyArray<string>>([]);
|
||||||
|
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", () =>
|
it.effect("keeps ingesting owned child events after the root turn terminalizes", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const threadId = ThreadId.make("thread:run-execution-late-child");
|
const threadId = ThreadId.make("thread:run-execution-late-child");
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import * as Ref from "effect/Ref";
|
|||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
import * as Stream from "effect/Stream";
|
import * as Stream from "effect/Stream";
|
||||||
|
|
||||||
|
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
|
||||||
import { ServerSettingsService } from "../serverSettings.ts";
|
import { ServerSettingsService } from "../serverSettings.ts";
|
||||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||||
import { EventSinkV2 } from "./EventSink.ts";
|
import { EventSinkV2 } from "./EventSink.ts";
|
||||||
@@ -1094,6 +1095,10 @@ export const layer: Layer.Layer<
|
|||||||
return;
|
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
|
yield* input.session
|
||||||
.startTurn({
|
.startTurn({
|
||||||
appThread: input.appThread,
|
appThread: input.appThread,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
|
ApplicationStoredEvent,
|
||||||
OrchestrationV2ArchivedShellStreamItem,
|
OrchestrationV2ArchivedShellStreamItem,
|
||||||
OrchestrationV2ShellSnapshot,
|
OrchestrationV2ShellSnapshot,
|
||||||
OrchestrationV2ThreadShell,
|
OrchestrationV2ThreadShell,
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { assert, it, vi } from "@effect/vitest";
|
import { assert, it, vi } from "@effect/vitest";
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
|
DEFAULT_SERVER_SETTINGS,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderDriverKind,
|
ProviderDriverKind,
|
||||||
ProviderInstanceId,
|
ProviderInstanceId,
|
||||||
|
type ServerProvider,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as Deferred from "effect/Deferred";
|
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 { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||||
import * as ProjectService from "../project/ProjectService.ts";
|
import * as ProjectService from "../project/ProjectService.ts";
|
||||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.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 * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||||
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
||||||
@@ -61,6 +65,9 @@ interface HarnessOptions {
|
|||||||
readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
|
readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
|
||||||
readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
|
readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
|
||||||
readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
|
readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
|
||||||
|
readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
|
||||||
|
readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||||
|
readonly providers?: ReadonlyArray<ServerProvider>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeHarness(options: HarnessOptions = {}) {
|
function makeHarness(options: HarnessOptions = {}) {
|
||||||
@@ -84,6 +91,9 @@ function makeHarness(options: HarnessOptions = {}) {
|
|||||||
const runSetup = vi.fn(
|
const runSetup = vi.fn(
|
||||||
options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
|
options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
|
||||||
);
|
);
|
||||||
|
const generateBranchName = vi.fn(
|
||||||
|
options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })),
|
||||||
|
);
|
||||||
const externalServices = Layer.mergeAll(
|
const externalServices = Layer.mergeAll(
|
||||||
Layer.succeed(ProjectService.ProjectService, {
|
Layer.succeed(ProjectService.ProjectService, {
|
||||||
create: () => Effect.die("unused"),
|
create: () => Effect.die("unused"),
|
||||||
@@ -107,8 +117,10 @@ function makeHarness(options: HarnessOptions = {}) {
|
|||||||
Layer.mock(TextGeneration.TextGeneration)({
|
Layer.mock(TextGeneration.TextGeneration)({
|
||||||
generateThreadTitle:
|
generateThreadTitle:
|
||||||
options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
|
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(
|
const launch = ThreadLaunch.layer.pipe(
|
||||||
Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
|
Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
|
||||||
@@ -116,6 +128,7 @@ function makeHarness(options: HarnessOptions = {}) {
|
|||||||
return {
|
return {
|
||||||
layer: Layer.mergeAll(launch, threadManagement, outbox, database),
|
layer: Layer.mergeAll(launch, threadManagement, outbox, database),
|
||||||
createWorktree,
|
createWorktree,
|
||||||
|
generateBranchName,
|
||||||
runSetup,
|
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) {
|
for (const failurePoint of ["worktree", "setup"] as const) {
|
||||||
it.effect(
|
it.effect(
|
||||||
`${failurePoint} failure keeps the thread and message visible and emits failure items`,
|
`${failurePoint} failure keeps the thread and message visible and emits failure items`,
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import * as Scope from "effect/Scope";
|
|||||||
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||||
import * as ProjectService from "../project/ProjectService.ts";
|
import * as ProjectService from "../project/ProjectService.ts";
|
||||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.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 TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||||
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
||||||
import * as IdAllocator from "./IdAllocator.ts";
|
import * as IdAllocator from "./IdAllocator.ts";
|
||||||
@@ -132,6 +134,8 @@ export const make = Effect.gen(function* () {
|
|||||||
const projects = yield* ProjectService.ProjectService;
|
const projects = yield* ProjectService.ProjectService;
|
||||||
const git = yield* GitWorkflow.GitWorkflowService;
|
const git = yield* GitWorkflow.GitWorkflowService;
|
||||||
const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||||
|
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||||
|
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||||
const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
|
const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
|
||||||
const ids = yield* IdAllocator.IdAllocatorV2;
|
const ids = yield* IdAllocator.IdAllocatorV2;
|
||||||
@@ -222,21 +226,29 @@ export const make = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const initialMessage = input.initialMessage;
|
||||||
let branch =
|
let branch =
|
||||||
input.workspaceStrategy.type === "worktree" &&
|
input.workspaceStrategy.type === "worktree" &&
|
||||||
input.workspaceStrategy.branch === undefined &&
|
input.workspaceStrategy.branch === undefined &&
|
||||||
input.initialMessage !== undefined
|
initialMessage !== undefined
|
||||||
? yield* textGeneration
|
? yield* Effect.gen(function* () {
|
||||||
.generateBranchName({
|
const settings = yield* serverSettings.getSettings;
|
||||||
cwd: project.workspaceRoot,
|
const modelSelection =
|
||||||
message: input.initialMessage.text,
|
settings.sourceControlWriterModelSelection === null
|
||||||
attachments: input.initialMessage.attachments,
|
? settings.textGenerationModelSelection
|
||||||
modelSelection: input.modelSelection,
|
: ServerSettings.resolveSourceControlWriterModelSelection(
|
||||||
})
|
settings,
|
||||||
.pipe(
|
yield* providerRegistry.getProviders,
|
||||||
Effect.map((result) => result.branch),
|
);
|
||||||
Effect.mapError(mapError(input, "generate-metadata", threadId)),
|
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.branch ??
|
||||||
(input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null));
|
(input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null));
|
||||||
let worktreePath =
|
let worktreePath =
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as DateTime from "effect/DateTime";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Queue from "effect/Queue";
|
import * as Queue from "effect/Queue";
|
||||||
import * as Stream from "effect/Stream";
|
import * as Stream from "effect/Stream";
|
||||||
@@ -54,7 +55,13 @@ const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|||||||
prefix: "t3-orchestration-v2-runtime-layer-",
|
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(ServerConfigLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
);
|
||||||
@@ -161,10 +168,7 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
|
|||||||
threadId,
|
threadId,
|
||||||
projectId,
|
projectId,
|
||||||
title: "Runtime layer thread",
|
title: "Runtime layer thread",
|
||||||
modelSelection: {
|
modelSelection: modelSelection,
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.4",
|
|
||||||
},
|
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -618,6 +622,25 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
|
|||||||
modelSelection: { ...modelSelection, model: "gpt-5.5" },
|
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({
|
const archive = yield* orchestrator.dispatch({
|
||||||
type: "thread.archive",
|
type: "thread.archive",
|
||||||
commandId: CommandId.make("runtime-layer-lifecycle-archive"),
|
commandId: CommandId.make("runtime-layer-lifecycle-archive"),
|
||||||
|
|||||||
@@ -89,13 +89,6 @@ const providerSwitchServiceProvided = providerSwitchServiceLayer.pipe(
|
|||||||
Layer.provide(providerAdapterRegistryProvided),
|
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(
|
const providerSessionManagerProvided = providerSessionManagerLayer.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mergeAll(
|
Layer.mergeAll(
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ export function makeReplayServerConfig(
|
|||||||
baseDir,
|
baseDir,
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl: undefined,
|
devUrl: undefined,
|
||||||
|
devAllowedOrigins: [],
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
startupPresentation: "browser",
|
startupPresentation: "browser",
|
||||||
tailscaleServeEnabled: false,
|
tailscaleServeEnabled: false,
|
||||||
@@ -245,7 +246,8 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
|||||||
const providerEventIngestorProvided = providerEventIngestorLayer.pipe(
|
const providerEventIngestorProvided = providerEventIngestorLayer.pipe(
|
||||||
Layer.provide(Layer.mergeAll(storesLayer, eventSinkProvided, idAllocatorLayer)),
|
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(serverConfigLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -239,7 +239,7 @@ export interface FixtureIds {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const CODEX_MODEL_SELECTION = {
|
export const CODEX_MODEL_SELECTION = {
|
||||||
provider: "codex",
|
instanceId: ProviderInstanceId.make("codex"),
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
} satisfies ModelSelection;
|
} satisfies ModelSelection;
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
OrchestrationThreadSearchSource,
|
OrchestrationThreadSearchSource,
|
||||||
OrchestrationShellSnapshot,
|
OrchestrationShellSnapshot,
|
||||||
OrchestrationThread,
|
OrchestrationThread,
|
||||||
|
OrchestrationThreadDetailSnapshot,
|
||||||
type OrchestrationCheckpointSummary,
|
type OrchestrationCheckpointSummary,
|
||||||
type OrchestrationLatestTurn,
|
type OrchestrationLatestTurn,
|
||||||
type OrchestrationMessage,
|
type OrchestrationMessage,
|
||||||
@@ -766,31 +767,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
Result: ProjectionThreadSearchRow,
|
Result: ProjectionThreadSearchRow,
|
||||||
execute: ({ pattern, limit }) =>
|
execute: ({ pattern, limit }) =>
|
||||||
sql`
|
sql`
|
||||||
WITH ranked AS (
|
WITH candidate AS (
|
||||||
SELECT
|
SELECT
|
||||||
threads.thread_id AS thread_id,
|
threads.thread_id AS thread_id,
|
||||||
threads.project_id AS project_id,
|
threads.project_id AS project_id,
|
||||||
CASE messages.role
|
messages.role AS role,
|
||||||
WHEN 'user' THEN 'user'
|
|
||||||
ELSE 'assistant'
|
|
||||||
END AS source,
|
|
||||||
messages.text AS match_text,
|
messages.text AS match_text,
|
||||||
messages.created_at AS message_created_at,
|
messages.created_at AS message_created_at,
|
||||||
CASE messages.role
|
messages.message_id AS message_id,
|
||||||
WHEN 'user' THEN 0
|
threads.updated_at AS thread_updated_at
|
||||||
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
|
|
||||||
FROM projection_thread_messages AS messages
|
FROM projection_thread_messages AS messages
|
||||||
INNER JOIN projection_threads AS threads
|
INNER JOIN projection_threads AS threads
|
||||||
ON threads.thread_id = messages.thread_id
|
ON threads.thread_id = messages.thread_id
|
||||||
@@ -812,6 +797,53 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
AND messages.text LIKE ${pattern} ESCAPE '!'
|
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
|
SELECT
|
||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
@@ -1891,6 +1923,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
archivedAt: row.archivedAt,
|
archivedAt: row.archivedAt,
|
||||||
|
settledOverride: row.settledOverride,
|
||||||
|
settledAt: row.settledAt,
|
||||||
|
snoozedUntil: row.snoozedUntil,
|
||||||
|
snoozedAt: row.snoozedAt,
|
||||||
|
titleRegeneration: mapTitleRegeneration(row),
|
||||||
session: sessionByThread.get(row.threadId) ?? null,
|
session: sessionByThread.get(row.threadId) ?? null,
|
||||||
latestUserMessageAt: row.latestUserMessageAt,
|
latestUserMessageAt: row.latestUserMessageAt,
|
||||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||||
|
|||||||
@@ -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<string, unknown> | undefined)?.detail).toBe(detail);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -5,6 +5,7 @@ import type {
|
|||||||
OrchestrationReadModel,
|
OrchestrationReadModel,
|
||||||
OrchestrationThread,
|
OrchestrationThread,
|
||||||
} from "@t3tools/contracts/legacy-orchestration";
|
} from "@t3tools/contracts/legacy-orchestration";
|
||||||
|
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
|
|
||||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||||
|
|||||||
@@ -206,6 +206,20 @@ layer("OrchestrationEventStore", (it) => {
|
|||||||
assert.isTrue("aggregateKind" in applicationEvents[0]!);
|
assert.isTrue("aggregateKind" in applicationEvents[0]!);
|
||||||
assert.isTrue("event" in applicationEvents[1]!);
|
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(
|
const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
|
||||||
Stream.runCollect,
|
Stream.runCollect,
|
||||||
Effect.map((chunk) => Array.from(chunk)),
|
Effect.map((chunk) => Array.from(chunk)),
|
||||||
|
|||||||
@@ -504,7 +504,7 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const readApplicationEvents = (input: {
|
const readApplicationEventPage = (input: {
|
||||||
readonly afterSequence: number;
|
readonly afterSequence: number;
|
||||||
readonly throughSequence: number;
|
readonly throughSequence: number;
|
||||||
readonly limit: number;
|
readonly limit: number;
|
||||||
@@ -534,7 +534,7 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
afterSequence: number,
|
afterSequence: number,
|
||||||
): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
|
): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
|
||||||
Stream.unwrap(
|
Stream.unwrap(
|
||||||
readApplicationEvents({
|
readApplicationEventPage({
|
||||||
afterSequence,
|
afterSequence,
|
||||||
throughSequence: input.throughSequence,
|
throughSequence: input.throughSequence,
|
||||||
limit: READ_PAGE_SIZE,
|
limit: READ_PAGE_SIZE,
|
||||||
@@ -581,6 +581,7 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
readAgentEvents,
|
readAgentEvents,
|
||||||
latestAgentSequence,
|
latestAgentSequence,
|
||||||
latestApplicationSequence,
|
latestApplicationSequence,
|
||||||
|
readApplicationEvents: catchUpApplicationEvents,
|
||||||
publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
|
publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
|
||||||
streamApplicationEvents,
|
streamApplicationEvents,
|
||||||
} satisfies OrchestrationEventStoreShape;
|
} satisfies OrchestrationEventStoreShape;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import * as Effect from "effect/Effect";
|
|||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
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";
|
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||||
|
|
||||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||||
@@ -13,7 +13,7 @@ layer("036_037_OrchestrationV2", (it) => {
|
|||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
assert.deepStrictEqual(
|
assert.deepStrictEqual(
|
||||||
migrationEntries.map(([id]) => id),
|
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* () {
|
Effect.gen(function* () {
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
yield* runMigrations({ toMigrationInclusive: 38 });
|
yield* runMigrations({ toMigrationInclusive: 38 });
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
|||||||
|
|
||||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
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", () =>
|
it.effect("moves V2 events and current project state behind one global sequence", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
|||||||
|
|
||||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
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", () =>
|
it.effect("preserves existing effects and adds the cancelled terminal status", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|||||||
@@ -82,6 +82,12 @@ export interface OrchestrationEventStoreShape {
|
|||||||
|
|
||||||
readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
|
readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
|
||||||
|
|
||||||
|
/** Read the finite retained application-event range `(afterSequence, throughSequence]`. */
|
||||||
|
readonly readApplicationEvents: (input: {
|
||||||
|
readonly afterSequence: number;
|
||||||
|
readonly throughSequence: number;
|
||||||
|
}) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
|
||||||
|
|
||||||
/** Publish only after the surrounding event/projection transaction commits. */
|
/** Publish only after the surrounding event/projection transaction commits. */
|
||||||
readonly publishCommitted: (events: ReadonlyArray<ApplicationStoredEvent>) => Effect.Effect<void>;
|
readonly publishCommitted: (events: ReadonlyArray<ApplicationStoredEvent>) => Effect.Effect<void>;
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import {
|
|||||||
ClaudeAdapterV2Driver,
|
ClaudeAdapterV2Driver,
|
||||||
type ClaudeAdapterV2DriverEnv,
|
type ClaudeAdapterV2DriverEnv,
|
||||||
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import { ProviderDriverError } from "../Errors.ts";
|
import { ProviderDriverError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
checkClaudeProviderStatus,
|
checkClaudeProviderStatus,
|
||||||
@@ -84,6 +85,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
|||||||
|
|
||||||
export type ClaudeDriverEnv =
|
export type ClaudeDriverEnv =
|
||||||
| ClaudeAdapterV2DriverEnv
|
| ClaudeAdapterV2DriverEnv
|
||||||
|
| BackgroundPolicy.BackgroundPolicy
|
||||||
| ChildProcessSpawner.ChildProcessSpawner
|
| ChildProcessSpawner.ChildProcessSpawner
|
||||||
| Crypto.Crypto
|
| Crypto.Crypto
|
||||||
| FileSystem.FileSystem
|
| FileSystem.FileSystem
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import {
|
|||||||
CodexAdapterV2Driver,
|
CodexAdapterV2Driver,
|
||||||
type CodexAdapterV2DriverEnv,
|
type CodexAdapterV2DriverEnv,
|
||||||
} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
|
} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import { ProviderDriverError } from "../Errors.ts";
|
import { ProviderDriverError } from "../Errors.ts";
|
||||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||||
@@ -75,6 +76,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
|||||||
*/
|
*/
|
||||||
export type CodexDriverEnv =
|
export type CodexDriverEnv =
|
||||||
| CodexAdapterV2DriverEnv
|
| CodexAdapterV2DriverEnv
|
||||||
|
| BackgroundPolicy.BackgroundPolicy
|
||||||
| ChildProcessSpawner.ChildProcessSpawner
|
| ChildProcessSpawner.ChildProcessSpawner
|
||||||
| Crypto.Crypto
|
| Crypto.Crypto
|
||||||
| FileSystem.FileSystem
|
| FileSystem.FileSystem
|
||||||
|
|||||||
@@ -8,7 +8,6 @@
|
|||||||
* @module provider/Drivers/CursorDriver
|
* @module provider/Drivers/CursorDriver
|
||||||
*/
|
*/
|
||||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||||
import * as Duration from "effect/Duration";
|
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
|
|
||||||
@@ -43,13 +42,16 @@ import {
|
|||||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||||
|
|
||||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
|
||||||
const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
|
const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
|
||||||
provider: DRIVER_KIND,
|
provider: DRIVER_KIND,
|
||||||
packageName: null,
|
packageName: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
export type CursorDriverEnv = CursorAdapterV2DriverEnv | ServerConfig | ServerSettingsService;
|
export type CursorDriverEnv =
|
||||||
|
| CursorAdapterV2DriverEnv
|
||||||
|
| BackgroundPolicy.BackgroundPolicy
|
||||||
|
| ServerConfig
|
||||||
|
| ServerSettingsService;
|
||||||
|
|
||||||
const withInstanceIdentity =
|
const withInstanceIdentity =
|
||||||
(input: {
|
(input: {
|
||||||
@@ -125,9 +127,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
|||||||
initialSnapshot: (settings) =>
|
initialSnapshot: (settings) =>
|
||||||
buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
|
buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
|
||||||
checkProvider,
|
checkProvider,
|
||||||
// Model catalog and capabilities come from Cursor's SDK catalog during
|
|
||||||
// provider checks.
|
|
||||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
|||||||
|
|
||||||
export type GrokDriverEnv =
|
export type GrokDriverEnv =
|
||||||
| GrokAdapterV2DriverEnv
|
| GrokAdapterV2DriverEnv
|
||||||
|
| BackgroundPolicy.BackgroundPolicy
|
||||||
| ChildProcessSpawner.ChildProcessSpawner
|
| ChildProcessSpawner.ChildProcessSpawner
|
||||||
| Crypto.Crypto
|
| Crypto.Crypto
|
||||||
| FileSystem.FileSystem
|
| FileSystem.FileSystem
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
OpenCodeAdapterV2Driver,
|
OpenCodeAdapterV2Driver,
|
||||||
type OpenCodeAdapterV2DriverEnv,
|
type OpenCodeAdapterV2DriverEnv,
|
||||||
} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
|
} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import { ProviderDriverError } from "../Errors.ts";
|
import { ProviderDriverError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
checkOpenCodeProviderStatus,
|
checkOpenCodeProviderStatus,
|
||||||
@@ -79,6 +80,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
|||||||
|
|
||||||
export type OpenCodeDriverEnv =
|
export type OpenCodeDriverEnv =
|
||||||
| OpenCodeAdapterV2DriverEnv
|
| OpenCodeAdapterV2DriverEnv
|
||||||
|
| BackgroundPolicy.BackgroundPolicy
|
||||||
| ChildProcessSpawner.ChildProcessSpawner
|
| ChildProcessSpawner.ChildProcessSpawner
|
||||||
| Crypto.Crypto
|
| Crypto.Crypto
|
||||||
| FileSystem.FileSystem
|
| FileSystem.FileSystem
|
||||||
|
|||||||
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user