Complete orchestration V2 frontend cutover
- Migrate web and mobile state, commands, and persistence to V2 projections - Render conversations from authoritative visible turn items - Harden runtime policy, launch handling, attachments, and cache invalidation
This commit is contained in:
1 parent
75e126993b
commit
3991a00629
111 files changed
+6306
-9244
No files matched your search
@@ -2,6 +2,11 @@ import {
|
||||
ConnectionPersistenceError,
|
||||
ConnectionRegistrationStore,
|
||||
ConnectionTargetStore,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
removeCatalogValue,
|
||||
@@ -13,11 +18,88 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as CatalogStore from "./catalog-store";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
}
|
||||
|
||||
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
|
||||
function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(
|
||||
Paths.document,
|
||||
THREAD_SNAPSHOT_CACHE_DIRECTORY,
|
||||
encodeURIComponent(environmentId),
|
||||
);
|
||||
if (operation !== "clear-environment") {
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(
|
||||
yield* threadSnapshotDirectory(environmentId, operation),
|
||||
threadSnapshotFileName(threadId),
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
@@ -128,6 +210,172 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const cacheStore = EnvironmentCacheStore.of({
|
||||
loadShell: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "load-shell");
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}
|
||||
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
shellSnapshotFile(environmentId, "load-shell").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "save-shell");
|
||||
const stored = {
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
|
||||
if (!file.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
threadSnapshotFile(environmentId, threadId, "load-thread").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
encodeStoredThreadSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
environmentId,
|
||||
"clear-environment",
|
||||
);
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,42 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
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: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -118,14 +118,51 @@ interface HomeScreenProps {
|
||||
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
* already consumes the top safe-area inset, so the list only needs breathing
|
||||
* room here.
|
||||
*/
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
switch (thread.runtime?.status) {
|
||||
case "running":
|
||||
case "waiting":
|
||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
||||
case "completed":
|
||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
||||
case "queued":
|
||||
case "starting":
|
||||
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
|
||||
case "failed":
|
||||
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
|
||||
default:
|
||||
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
|
||||
}
|
||||
}
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
|
||||
|
||||
function threadRowExit(values: ExitAnimationsValues) {
|
||||
"worklet";
|
||||
|
||||
return {
|
||||
initialValues: {
|
||||
height: values.currentHeight,
|
||||
opacity: 1,
|
||||
originX: values.currentOriginX,
|
||||
},
|
||||
animations: {
|
||||
height: withDelay(
|
||||
90,
|
||||
withTiming(0, {
|
||||
duration: 170,
|
||||
easing: Easing.inOut(Easing.cubic),
|
||||
}),
|
||||
),
|
||||
opacity: withDelay(80, withTiming(0, { duration: 100 })),
|
||||
originX: withTiming(values.currentOriginX - values.windowWidth, {
|
||||
duration: 190,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
@@ -185,7 +222,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -971,25 +1008,17 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View className="mt-4">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
) : !hasResults ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding runtime."
|
||||
/>
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
const isExpanded = expandedProjects.has(group.key);
|
||||
const visibleThreads = isExpanded
|
||||
? group.threads
|
||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
||||
|
||||
const listHeader = (
|
||||
<>
|
||||
|
||||
@@ -6,11 +6,8 @@ import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-searc
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -30,25 +27,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
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,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import {
|
||||
buildReviewListItems,
|
||||
@@ -18,9 +14,9 @@ import {
|
||||
} from "./reviewModel";
|
||||
|
||||
function makeCheckpoint(
|
||||
input: Partial<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-1"),
|
||||
runId: RunId.make("run-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("run-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell";
|
||||
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
@@ -128,11 +129,11 @@ export type ReviewParsedDiff =
|
||||
readonly notice: string | null;
|
||||
};
|
||||
|
||||
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
return `Turn ${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
const fileCount = checkpoint.files.length;
|
||||
if (checkpoint.status !== "ready") {
|
||||
return `Diff ${checkpoint.status}`;
|
||||
@@ -141,8 +142,8 @@ function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string
|
||||
}
|
||||
|
||||
function compareCheckpointTurnCountDescending(
|
||||
left: OrchestrationCheckpointSummary,
|
||||
right: OrchestrationCheckpointSummary,
|
||||
left: ThreadCheckpointSummary,
|
||||
right: ThreadCheckpointSummary,
|
||||
): -1 | 0 | 1 {
|
||||
if (left.checkpointTurnCount === right.checkpointTurnCount) {
|
||||
return 0;
|
||||
@@ -151,7 +152,7 @@ function compareCheckpointTurnCountDescending(
|
||||
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
|
||||
}
|
||||
|
||||
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { useCheckpointDiff } from "../../state/queries";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
@@ -59,7 +60,7 @@ export function useReviewSections(input: {
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>,
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,14 +6,16 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
const canRespond = props.approval.responseCapability === "live";
|
||||
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -27,17 +29,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
{props.approval.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -46,7 +54,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
@@ -9,14 +9,10 @@ export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -24,6 +20,7 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -32,6 +29,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
@@ -49,6 +52,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -78,6 +82,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -94,7 +99,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -91,13 +94,7 @@ export interface ThreadComposerProps {
|
||||
readonly connectionState: RemoteClientConnectionState;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
/**
|
||||
* Message sync phase for the selected thread (drives the status pill):
|
||||
* "loading" = first fetch, nothing to show yet; "syncing" = cached messages
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
@@ -305,9 +302,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime);
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -43,7 +42,7 @@ import { ThreadFeed } from "./ThreadFeed";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
@@ -51,11 +50,11 @@ export interface ThreadDetailScreenProps {
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
@@ -82,16 +81,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -341,41 +340,49 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
className="flex-1"
|
||||
onTouchStart={handleFeedTouchStart}
|
||||
onTouchMove={handleFeedTouchMove}
|
||||
onTouchEnd={handleFeedTouchEnd}
|
||||
onTouchCancel={handleFeedTouchCancel}
|
||||
>
|
||||
<ThreadFeed
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)}
|
||||
<GestureDetector gesture={headerDrawerGesture}>
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
style={{ flex: 1 }}
|
||||
onTouchStart={handleFeedTouchStart}
|
||||
onTouchMove={handleFeedTouchMove}
|
||||
onTouchEnd={handleFeedTouchEnd}
|
||||
onTouchCancel={handleFeedTouchCancel}
|
||||
>
|
||||
<ThreadFeed
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestRun={props.selectedThread.latestRun}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
layoutVariant={layoutVariant}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ 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 }}
|
||||
>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -92,7 +92,7 @@ import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/l
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
@@ -151,8 +151,7 @@ export interface ThreadFeedProps {
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -823,11 +822,11 @@ function renderFeedEntry(
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -841,16 +840,12 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -889,7 +884,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -1320,21 +1315,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
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 previousLatestTurnRef = useRef(props.latestRun);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1424,15 +1412,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
viewportWidth,
|
||||
],
|
||||
);
|
||||
const reportHeaderMaterialVisibility = useCallback(
|
||||
(visible: boolean) => {
|
||||
if (headerMaterialVisibleRef.current === visible) {
|
||||
return;
|
||||
}
|
||||
headerMaterialVisibleRef.current = visible;
|
||||
props.onHeaderMaterialVisibilityChange?.(visible);
|
||||
},
|
||||
[props.onHeaderMaterialVisibilityChange],
|
||||
const presentedFeed = useMemo(
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestRun],
|
||||
);
|
||||
// True while the viewport sits within ~one screen of the list end — the
|
||||
// only region where layout shifts should animate. Starts true because the
|
||||
@@ -1544,29 +1526,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
props.latestRun &&
|
||||
(props.latestRun.completedAt === null || props.latestRun.status === "running")
|
||||
? props.latestRun.runId
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1575,14 +1557,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1676,17 +1658,28 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
StackActions,
|
||||
useFocusEffect,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
@@ -461,20 +456,15 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
const runtime = selectedThread?.runtime;
|
||||
if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}),
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
@@ -504,7 +494,7 @@ function ThreadRouteContent(
|
||||
terminalDebugLog("terminal-menu:open-new", {
|
||||
hasThread: Boolean(selectedThread),
|
||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
@@ -512,7 +502,7 @@ function ThreadRouteContent(
|
||||
}
|
||||
|
||||
const nextId = nextOpenTerminalId({
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
void navigation.navigate("ThreadTerminal", {
|
||||
environmentId: String(selectedThread.environmentId),
|
||||
@@ -539,9 +529,9 @@ function ThreadRouteContent(
|
||||
}
|
||||
|
||||
const targetTerminalId = resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
hasRunningTerminal: terminalMenuSessions.some(
|
||||
(session) => session.status === "running" || session.status === "starting",
|
||||
(runtime) => runtime.status === "running" || runtime.status === "starting",
|
||||
),
|
||||
});
|
||||
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
||||
|
||||
@@ -7,49 +7,9 @@ export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
return Number.isNaN(candidate) ? 0 : candidate;
|
||||
}
|
||||
|
||||
export type ThreadStatusKind =
|
||||
| "pending-approval"
|
||||
| "awaiting-input"
|
||||
| "working"
|
||||
| "connecting"
|
||||
| "error"
|
||||
| "plan-ready";
|
||||
|
||||
export interface ThreadStatusPresentation extends StatusTone {
|
||||
readonly kind: ThreadStatusKind;
|
||||
/** Foreground color for the leading status icon. */
|
||||
readonly iconColor: string;
|
||||
/** Background color for the leading status icon circle. */
|
||||
readonly iconBackground: string;
|
||||
/** Whether the indicator represents in-flight activity. */
|
||||
readonly pulse: boolean;
|
||||
}
|
||||
|
||||
/** Neutral icon colors for threads with no actionable status. */
|
||||
export const THREAD_STATUS_NEUTRAL_ICON = {
|
||||
iconColor: "#8e8e93",
|
||||
iconBackground: "rgba(142,142,147,0.22)",
|
||||
} as const;
|
||||
|
||||
function isLatestTurnSettled(
|
||||
latestTurn: OrchestrationLatestTurn | null,
|
||||
session: OrchestrationSession | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
if (!session) return true;
|
||||
return session.status !== "running";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
||||
const status = thread.runtime?.status;
|
||||
if (status === "running" || status === "waiting") {
|
||||
return {
|
||||
kind: "pending-approval",
|
||||
label: "Needs Approval",
|
||||
@@ -60,8 +20,7 @@ export function resolveThreadStatus(
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.hasPendingUserInput) {
|
||||
if (status === "completed") {
|
||||
return {
|
||||
kind: "awaiting-input",
|
||||
label: "Awaiting Input",
|
||||
@@ -72,8 +31,7 @@ export function resolveThreadStatus(
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
if (status === "queued" || status === "starting") {
|
||||
return {
|
||||
kind: "working",
|
||||
label: "Working",
|
||||
@@ -84,8 +42,7 @@ export function resolveThreadStatus(
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (status === "failed") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
label: "Connecting",
|
||||
|
||||
@@ -58,15 +58,16 @@ export function useCreateProjectThread() {
|
||||
|
||||
const result = await startTurn({
|
||||
environmentId: input.project.environmentId,
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
projectId: input.project.id,
|
||||
projectCwd: input.project.workspaceRoot,
|
||||
threadId: metadata.threadId,
|
||||
commandId: metadata.commandId,
|
||||
messageId: metadata.messageId,
|
||||
createdAt: metadata.createdAt,
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
input: {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
creationSource: "mobile",
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
role: "user",
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
},
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
|
||||
|
||||
import { groupProjectsByRepository } from "./repositoryGroups";
|
||||
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { makeThreadShellFixture } from "../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -23,24 +24,20 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("groupProjectsByRepository", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
|
||||
return `${environmentId}:${projectId}`;
|
||||
@@ -10,7 +10,7 @@ export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId
|
||||
|
||||
export function scopedRequestKey(
|
||||
environmentId: EnvironmentId,
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
): string {
|
||||
return `${environmentId}:${requestId}`;
|
||||
}
|
||||
@@ -1,466 +1,112 @@
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
import { MessageId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
const runId = RunId.make("run-1");
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
): OrchestrationThreadActivity {
|
||||
function message(role: "user" | "assistant", text: string, createdAt: string, id: string) {
|
||||
return {
|
||||
tone: "info",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
...input,
|
||||
};
|
||||
id: MessageId.make(id),
|
||||
role,
|
||||
text,
|
||||
attachments: [],
|
||||
runId: role === "assistant" ? runId : null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
} as const;
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
|
||||
): OrchestrationThread {
|
||||
function commandEntry(overrides: Partial<ThreadWorkEntry> = {}): ThreadWorkEntry {
|
||||
const structuredPayload = {
|
||||
type: "command_execution",
|
||||
input: "vp check",
|
||||
output: "ok",
|
||||
} as ThreadWorkEntry["structuredPayload"];
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
id: "item-1",
|
||||
createdAt: "2026-06-20T00:00:02.000Z",
|
||||
runId,
|
||||
label: "Ran command",
|
||||
command: "vp check",
|
||||
detail: "ok",
|
||||
tone: "tool",
|
||||
itemType: "command_execution",
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Runtime warning thread",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("activity-old"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-old"),
|
||||
payload: {
|
||||
message: "Old warning",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("activity-latest"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
payload: {
|
||||
message: "Latest warning",
|
||||
},
|
||||
}),
|
||||
it("orders V2 messages and work entries while retaining structured tool data", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-old",
|
||||
activities: [{ id: "activity-old", turnId: "turn-old" }],
|
||||
},
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-latest",
|
||||
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
|
||||
},
|
||||
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
|
||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||
expect(activity?.runId).toBe(runId);
|
||||
expect(activity?.fullDetail).toContain('"input": "vp check"');
|
||||
});
|
||||
|
||||
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
const feed = buildThreadFeed(thread);
|
||||
const latestRun = {
|
||||
runId,
|
||||
status: "completed" as const,
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
};
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
|
||||
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
|
||||
expect(expanded.map((entry) => entry.type)).toEqual([
|
||||
"message",
|
||||
"run-fold",
|
||||
"activity-group",
|
||||
"message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("collapses matching tool lifecycle rows like desktop", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Collapsed tools",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-updated"),
|
||||
kind: "tool.updated",
|
||||
tone: "tool",
|
||||
summary: "Run tests",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run tests completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
],
|
||||
it("keeps an active run expanded and marks failed tools as failures", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user")],
|
||||
workEntries: [commandEntry({ tone: "error", toolLifecycleStatus: "failed" })],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
type: "activity-group",
|
||||
});
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(1);
|
||||
expect(group.activities[0]).toMatchObject({
|
||||
id: "tool-completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
canExpand: true,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
|
||||
expect(group.activities[0]?.getCopyText()).toBe(
|
||||
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("defers large tool output expansion until a work row is opened or copied", () => {
|
||||
let serializedToolOutputs = 0;
|
||||
const activities = Array.from({ length: 5_000 }, (_, index) =>
|
||||
makeActivity({
|
||||
id: EventId.make(`large-tool-${index}`),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: `Tool ${index}`,
|
||||
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
|
||||
payload: {
|
||||
title: `Tool ${index}`,
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
toJSON: () => {
|
||||
serializedToolOutputs += 1;
|
||||
return { output: "x".repeat(32_768) };
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-large-tools"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Large tools",
|
||||
activities,
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(serializedToolOutputs).toBe(0);
|
||||
|
||||
const group = feed[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(5_000);
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
expect(group.activities[0]?.getCopyText()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Folded work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:18.000Z",
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "I am checking.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:18.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read files",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Read files",
|
||||
itemType: "file_read",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
type: "turn-fold",
|
||||
label: "Worked for 17s",
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-commentary",
|
||||
"tool-completed",
|
||||
"assistant-final",
|
||||
]);
|
||||
});
|
||||
|
||||
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
|
||||
const firstTurnId = TurnId.make("turn-1");
|
||||
const secondTurnId = TurnId.make("turn-2");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-steered"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Steered work",
|
||||
latestTurn: {
|
||||
turnId: secondTurnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:14.000Z",
|
||||
startedAt: "2026-04-01T00:00:14.000Z",
|
||||
const presented = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("assistant-next"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("user-1"),
|
||||
role: "user",
|
||||
text: "Do it once more.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "Kicking off call 1.",
|
||||
turnId: firstTurnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:09.000Z",
|
||||
updatedAt: "2026-04-01T00:00:09.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("user-2"),
|
||||
role: "user",
|
||||
text: "Actually do 15.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:14.000Z",
|
||||
updatedAt: "2026-04-01T00:00:14.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-next"),
|
||||
role: "assistant",
|
||||
text: "One down - adjusting.",
|
||||
turnId: secondTurnId,
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:17.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("work-1"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-04-01T00:00:12.000Z",
|
||||
turnId: firstTurnId,
|
||||
payload: {
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
new Set(),
|
||||
);
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
label: "Worked for 12s",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
|
||||
const turnId = TurnId.make("turn-running");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-4"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Running work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-failed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run command",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Run command",
|
||||
itemType: "command_execution",
|
||||
detail: "zsh: command not found: nope",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
|
||||
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
|
||||
"failure",
|
||||
);
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
|
||||
+218
-1190
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,5 @@
|
||||
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 type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
@@ -40,7 +35,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type EnvironmentThreadState,
|
||||
createThreadEnvironmentAtoms,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { presentThread, type EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -32,14 +33,21 @@ const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_
|
||||
export function useEnvironmentThread(
|
||||
environmentId: EnvironmentId | null,
|
||||
threadId: ThreadId | null,
|
||||
): EnvironmentThreadState {
|
||||
): Omit<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
const result = useAtomValue(
|
||||
environmentId !== null && threadId !== null
|
||||
? environmentThreads.stateAtom(environmentId, threadId)
|
||||
: EMPTY_THREAD_STATE_ATOM,
|
||||
);
|
||||
return Option.getOrElse(
|
||||
const state = Option.getOrElse(
|
||||
AsyncResult.value(result),
|
||||
() => EMPTY_ENVIRONMENT_THREAD_STATE,
|
||||
) as EnvironmentThreadState;
|
||||
return {
|
||||
...state,
|
||||
data:
|
||||
environmentId === null
|
||||
? Option.none()
|
||||
: Option.map(state.data, (projection) => presentThread(environmentId, projection)),
|
||||
};
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
type PendingUserInputDraftAnswer,
|
||||
@@ -66,14 +64,11 @@ export function useSelectedThreadRequests() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
|
||||
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
const activePendingApprovals = useMemo(
|
||||
() => selectedThread?.pendingApprovals ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
@@ -82,8 +77,8 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
() => selectedThread?.pendingUserInputs ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
@@ -97,7 +92,7 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -109,7 +104,7 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -121,10 +116,16 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activePendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
const result = await respondToApproval({
|
||||
@@ -138,11 +139,16 @@ export function useSelectedThreadRequests() {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
return result;
|
||||
},
|
||||
[respondToApproval, selectedThreadShell],
|
||||
[activePendingApprovals, respondToApproval, selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
if (
|
||||
!selectedThreadShell ||
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingUserInputAnswers
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -106,13 +107,13 @@ export function useThreadComposerState() {
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread?.session) {
|
||||
if (!selectedThread?.runtime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
orchestrationStatus: selectedThread.session.status,
|
||||
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
|
||||
orchestrationStatus: selectedThread.runtime.status,
|
||||
activeRunId: selectedThread.runtime.activeRunId ?? undefined,
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
@@ -123,15 +124,13 @@ export function useThreadComposerState() {
|
||||
}
|
||||
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThread.latestRun,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime);
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
@@ -221,6 +221,7 @@ export function useThreadOutboxDrain(): void {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: queuedMessage.commandId,
|
||||
creationSource: "mobile",
|
||||
threadId: queuedMessage.threadId,
|
||||
message: {
|
||||
messageId: queuedMessage.messageId,
|
||||
@@ -314,7 +315,7 @@ export function useThreadOutboxDrain(): void {
|
||||
threadExists: thread !== undefined,
|
||||
shellStatus,
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
threadBusy: threadRuntimeIsActive(thread?.runtime),
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
presentThread,
|
||||
presentThreadShell,
|
||||
type EnvironmentThread,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2ThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
export function makeRawThreadShell(
|
||||
input: Partial<OrchestrationV2ThreadShell> = {},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const id = input.id ?? ThreadId.make("thread-test");
|
||||
const providerInstanceId = input.providerInstanceId ?? ProviderInstanceId.make("codex");
|
||||
const now = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
return {
|
||||
id,
|
||||
projectId: ProjectId.make("project-test"),
|
||||
title: "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: null,
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeThreadShellFixture(
|
||||
overrides: Partial<EnvironmentThreadShell> = {},
|
||||
): EnvironmentThreadShell {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const raw = makeRawThreadShell({
|
||||
id: overrides.id,
|
||||
projectId: overrides.projectId,
|
||||
title: overrides.title,
|
||||
providerInstanceId: overrides.providerInstanceId,
|
||||
modelSelection: overrides.modelSelection,
|
||||
runtimeMode: overrides.runtimeMode,
|
||||
interactionMode: overrides.interactionMode,
|
||||
branch: overrides.branch,
|
||||
worktreePath: overrides.worktreePath,
|
||||
});
|
||||
return { ...presentThreadShell(environmentId, raw), ...overrides };
|
||||
}
|
||||
|
||||
export function makeThreadFixture(overrides: Partial<EnvironmentThread> = {}): EnvironmentThread {
|
||||
const shell = makeRawThreadShell({
|
||||
id: overrides.id,
|
||||
projectId: overrides.projectId,
|
||||
title: overrides.title,
|
||||
providerInstanceId: overrides.providerInstanceId,
|
||||
modelSelection: overrides.modelSelection,
|
||||
runtimeMode: overrides.runtimeMode,
|
||||
interactionMode: overrides.interactionMode,
|
||||
branch: overrides.branch,
|
||||
worktreePath: overrides.worktreePath,
|
||||
});
|
||||
const projection: OrchestrationV2ThreadProjection = {
|
||||
thread: {
|
||||
id: shell.id,
|
||||
projectId: shell.projectId,
|
||||
title: shell.title,
|
||||
providerInstanceId: shell.providerInstanceId,
|
||||
modelSelection: shell.modelSelection,
|
||||
runtimeMode: shell.runtimeMode,
|
||||
interactionMode: shell.interactionMode,
|
||||
branch: shell.branch,
|
||||
worktreePath: shell.worktreePath,
|
||||
activeProviderThreadId: shell.activeProviderThreadId,
|
||||
lineage: shell.lineage,
|
||||
forkedFrom: shell.forkedFrom,
|
||||
createdBy: shell.createdBy,
|
||||
creationSource: shell.creationSource,
|
||||
createdAt: shell.createdAt,
|
||||
updatedAt: shell.updatedAt,
|
||||
archivedAt: shell.archivedAt,
|
||||
deletedAt: shell.deletedAt,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: shell.updatedAt,
|
||||
};
|
||||
return {
|
||||
...presentThread(overrides.environmentId ?? EnvironmentId.make("environment-test"), projection),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Server
|
||||
|
||||
Node.js WebSocket server for the T3 Code app.
|
||||
@@ -7,11 +7,22 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
createDeterministicAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
|
||||
describe("attachmentStore", () => {
|
||||
it("derives stable attachment ids for idempotent message retries", () => {
|
||||
const first = createDeterministicAttachmentId("thread-1", "message-1:0");
|
||||
const retry = createDeterministicAttachmentId("thread-1", "message-1:0");
|
||||
const next = createDeterministicAttachmentId("thread-1", "message-1:1");
|
||||
|
||||
expect(first).toBe(retry);
|
||||
expect(next).not.toBe(first);
|
||||
expect(first && parseThreadSegmentFromAttachmentId(first)).toBe("thread-1");
|
||||
});
|
||||
|
||||
it("sanitizes thread ids when creating attachment ids", () => {
|
||||
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
|
||||
@@ -42,6 +42,17 @@ export function createAttachmentId(threadId: string): string | null {
|
||||
return `${threadSegment}-${NodeCrypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
export function createDeterministicAttachmentId(
|
||||
threadId: string,
|
||||
stableKey: string,
|
||||
): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) return null;
|
||||
const hash = NodeCrypto.createHash("sha256").update(stableKey).digest("hex").slice(0, 32);
|
||||
const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
|
||||
return `${threadSegment}-${uuid}`;
|
||||
}
|
||||
|
||||
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2DomainEvent,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
@@ -60,6 +62,7 @@ const TestLayer = Layer.mergeAll(
|
||||
);
|
||||
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const providerDriver = ProviderDriverKind.make("codex");
|
||||
const modelSelection = {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
@@ -404,7 +407,32 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:foundation-many-items");
|
||||
const runId = RunId.make("run:foundation-many-items");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread:foundation-many-items");
|
||||
const thread = makeThread(threadId, now);
|
||||
const providerThreadEvent = {
|
||||
id: EventId.make("event:foundation-many-items:provider-thread"),
|
||||
type: "provider-thread.updated" as const,
|
||||
threadId,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: providerThreadId,
|
||||
driver: providerDriver,
|
||||
providerInstanceId,
|
||||
providerSessionId: null,
|
||||
appThreadId: threadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: null,
|
||||
nativeConversationHeadRef: null,
|
||||
status: "active" as const,
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 1,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
} satisfies OrchestrationV2DomainEvent;
|
||||
const runEvent = {
|
||||
id: EventId.make("event:foundation-many-items:run"),
|
||||
type: "run.created" as const,
|
||||
@@ -467,11 +495,13 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
|
||||
yield* eventSink.write({
|
||||
events: [
|
||||
threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }),
|
||||
providerThreadEvent,
|
||||
runEvent,
|
||||
...itemEvents,
|
||||
],
|
||||
});
|
||||
const beforeUpdate = yield* projectionStore.getThreadProjection(threadId);
|
||||
assert.equal(beforeUpdate.thread.activeProviderThreadId, providerThreadId);
|
||||
const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal);
|
||||
assert.lengthOf(ordinals, 151);
|
||||
assert.equal(new Set(ordinals).size, 151);
|
||||
|
||||
@@ -1649,6 +1649,54 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const projection = yield* getProjectionWithPendingEvents(command.threadId, events);
|
||||
const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
|
||||
const dispatchMode = command.dispatchMode;
|
||||
const sourcePlanProjection =
|
||||
command.sourcePlanRef === undefined
|
||||
? null
|
||||
: yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
|
||||
const sourcePlan =
|
||||
command.sourcePlanRef === undefined
|
||||
? null
|
||||
: (sourcePlanProjection?.plans.find(
|
||||
(plan) => plan.id === command.sourcePlanRef?.planId && plan.kind === "proposed_plan",
|
||||
) ?? null);
|
||||
if (command.sourcePlanRef !== undefined && sourcePlan === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
sourcePlanProjection !== null &&
|
||||
sourcePlanProjection.thread.projectId !== projection.thread.projectId
|
||||
) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
|
||||
});
|
||||
}
|
||||
if (sourcePlan !== null && sourcePlan.status !== "active") {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${sourcePlan.id} is not active.`,
|
||||
});
|
||||
}
|
||||
const completeSourcePlan = (occurredAt: DateTime.Utc) =>
|
||||
sourcePlan === null
|
||||
? Effect.void
|
||||
: emit(
|
||||
events,
|
||||
command,
|
||||
)({
|
||||
type: "plan.updated",
|
||||
threadId: sourcePlan.threadId,
|
||||
...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
|
||||
nodeId: sourcePlan.nodeId,
|
||||
occurredAt,
|
||||
payload: { ...sourcePlan, status: "completed" },
|
||||
});
|
||||
|
||||
if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
|
||||
yield* dispatchSteerIntoRun({
|
||||
@@ -1783,6 +1831,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -1861,6 +1910,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
@@ -2030,6 +2080,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -2116,6 +2167,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
@@ -2613,6 +2665,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
checkpointId: null,
|
||||
contextHandoffId:
|
||||
portableForkHandoff?.id ?? providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -2917,6 +2970,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
|
||||
@@ -223,6 +223,13 @@ export function applyToProjection(
|
||||
case "provider-thread.updated":
|
||||
return {
|
||||
...base,
|
||||
thread:
|
||||
event.payload.appThreadId === base.thread.id
|
||||
? {
|
||||
...base.thread,
|
||||
activeProviderThreadId: event.payload.id,
|
||||
}
|
||||
: base.thread,
|
||||
providerThreads: upsertById(base.providerThreads, event.payload),
|
||||
};
|
||||
case "provider-turn.updated":
|
||||
@@ -288,6 +295,8 @@ type ShellThreadRow = {
|
||||
readonly active_run_id: string | null;
|
||||
readonly pending_request_payload_json: string | null;
|
||||
readonly latest_message_payload_json: string | null;
|
||||
readonly latest_user_message_at: string | null;
|
||||
readonly has_actionable_proposed_plan: number;
|
||||
readonly item_count: number;
|
||||
};
|
||||
|
||||
@@ -638,6 +647,13 @@ export function threadShellFromProjection(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
const latestUserMessage =
|
||||
projection.messages
|
||||
.filter((message) => message.role === "user")
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
return {
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
@@ -673,6 +689,10 @@ export function threadShellFromProjection(
|
||||
text: latestVisibleMessage.text,
|
||||
updatedAt: latestVisibleMessage.updatedAt,
|
||||
},
|
||||
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
|
||||
hasActionableProposedPlan: projection.plans.some(
|
||||
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
|
||||
),
|
||||
itemCount: activeLocalTurnItems(projection).length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
createdAt: projection.thread.createdAt,
|
||||
@@ -693,6 +713,8 @@ type ShellThreadState = {
|
||||
readonly activeRunId: RunId | null;
|
||||
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
|
||||
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
|
||||
readonly latestUserMessageAt: DateTime.Utc | null;
|
||||
readonly hasActionableProposedPlan: boolean;
|
||||
readonly itemCount: number;
|
||||
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
|
||||
readonly runOrdinalById: ReadonlyMap<RunId, number>;
|
||||
@@ -819,6 +841,8 @@ function shellFromState(input: {
|
||||
text: input.state.latestVisibleMessage.text,
|
||||
updatedAt: input.state.latestVisibleMessage.updatedAt,
|
||||
},
|
||||
latestUserMessageAt: input.state.latestUserMessageAt,
|
||||
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
|
||||
itemCount: input.state.itemCount,
|
||||
visibleItemCount: input.visibleItemCount,
|
||||
createdAt: input.state.thread.createdAt,
|
||||
@@ -1949,6 +1973,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
ORDER BY message.updated_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_message_payload_json,
|
||||
(
|
||||
SELECT message.updated_at
|
||||
FROM orchestration_v2_projection_messages message
|
||||
WHERE message.thread_id = t.thread_id
|
||||
AND message.role = 'user'
|
||||
ORDER BY message.updated_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_user_message_at,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM orchestration_v2_projection_plans plan
|
||||
WHERE plan.thread_id = t.thread_id
|
||||
AND plan.kind = 'proposed_plan'
|
||||
AND plan.status = 'active'
|
||||
) AS has_actionable_proposed_plan,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM orchestration_v2_projection_turn_items i
|
||||
@@ -2015,6 +2054,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
|
||||
pendingRuntimeRequest,
|
||||
latestVisibleMessage,
|
||||
latestUserMessageAt:
|
||||
row.latest_user_message_at === null
|
||||
? null
|
||||
: DateTime.makeUnsafe(row.latest_user_message_at),
|
||||
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
|
||||
itemCount: row.item_count,
|
||||
updatedAt: thread.updatedAt,
|
||||
runOrdinalById:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
type ModelSelection,
|
||||
type OrchestrationV2AppThread,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
|
||||
import { layerFromProjectRepository, RuntimePolicyV2 } from "./RuntimePolicy.ts";
|
||||
|
||||
const projectId = ProjectId.make("project:runtime-policy");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const modelSelection = {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.5",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
function makeThread(input: {
|
||||
readonly now: DateTime.Utc;
|
||||
readonly worktreePath: string | null;
|
||||
}): OrchestrationV2AppThread {
|
||||
const threadId = ThreadId.make("thread:runtime-policy");
|
||||
return {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Runtime policy",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
const TestLayer = layerFromProjectRepository.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionProjects.ProjectionProjectRepository)({
|
||||
getById: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/project-root",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-21T00:00:00.000Z",
|
||||
updatedAt: "2026-06-21T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("RuntimePolicyV2", (it) => {
|
||||
it.effect("uses the project root for local-checkout threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* RuntimePolicyV2;
|
||||
const now = yield* DateTime.now;
|
||||
const resolved = yield* policy.resolve({
|
||||
thread: makeThread({ now, worktreePath: null }),
|
||||
modelSelection,
|
||||
});
|
||||
assert.equal(resolved.cwd, "/project-root");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers a provisioned worktree over the project root", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* RuntimePolicyV2;
|
||||
const now = yield* DateTime.now;
|
||||
const resolved = yield* policy.resolve({
|
||||
thread: makeThread({ now, worktreePath: "/project-worktree" }),
|
||||
modelSelection,
|
||||
});
|
||||
assert.equal(resolved.cwd, "/project-worktree");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
import { ModelSelection, OrchestrationV2AppThread, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import {
|
||||
ModelSelection,
|
||||
OrchestrationV2AppThread,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
|
||||
import {
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2RuntimePolicy as ProviderAdapterV2RuntimePolicyType,
|
||||
@@ -15,12 +22,13 @@ import {
|
||||
export class RuntimePolicyResolveError extends Schema.TaggedErrorClass<RuntimePolicyResolveError>()(
|
||||
"RuntimePolicyResolveError",
|
||||
{
|
||||
driver: ProviderDriverKind,
|
||||
projectId: ProjectId,
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve runtime policy for ${this.driver}.`;
|
||||
return `Failed to resolve runtime policy for provider instance ${this.providerInstanceId} in project ${this.projectId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +69,51 @@ export const layer: Layer.Layer<RuntimePolicyV2> = Layer.succeed(RuntimePolicyV2
|
||||
}),
|
||||
});
|
||||
|
||||
export const layerFromProjectRepository: Layer.Layer<
|
||||
RuntimePolicyV2,
|
||||
never,
|
||||
ProjectionProjects.ProjectionProjectRepository
|
||||
> = Layer.effect(
|
||||
RuntimePolicyV2,
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* ProjectionProjects.ProjectionProjectRepository;
|
||||
return RuntimePolicyV2.of({
|
||||
resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
|
||||
const cwd =
|
||||
input.thread.worktreePath ??
|
||||
(yield* projects.getById({ projectId: input.thread.projectId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RuntimePolicyResolveError({
|
||||
projectId: input.thread.projectId,
|
||||
providerInstanceId: input.modelSelection.instanceId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new RuntimePolicyResolveError({
|
||||
projectId: input.thread.projectId,
|
||||
providerInstanceId: input.modelSelection.instanceId,
|
||||
cause: "Project not found.",
|
||||
}),
|
||||
),
|
||||
onSome: (project) => Effect.succeed(project.workspaceRoot),
|
||||
}),
|
||||
),
|
||||
));
|
||||
return ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: input.thread.runtimeMode,
|
||||
interactionMode: input.thread.interactionMode,
|
||||
cwd,
|
||||
});
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export function layerWithOverride(
|
||||
override: RuntimePolicyV2Override,
|
||||
): Layer.Layer<RuntimePolicyV2, never, RuntimePolicyV2> {
|
||||
|
||||
@@ -80,6 +80,20 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
(
|
||||
command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0],
|
||||
): Effect.Effect<OrchestratorV2DispatchResult, OrchestratorDispatchError> => {
|
||||
if (command.type === "thread.metadata.update") {
|
||||
const existing = projections.get(command.threadId);
|
||||
if (existing === undefined) return Effect.die("missing existing projection");
|
||||
projections.set(command.threadId, {
|
||||
...existing,
|
||||
thread: {
|
||||
...existing.thread,
|
||||
...(command.title === undefined ? {} : { title: command.title }),
|
||||
...(command.branch === undefined ? {} : { branch: command.branch }),
|
||||
...(command.worktreePath === undefined ? {} : { worktreePath: command.worktreePath }),
|
||||
},
|
||||
});
|
||||
return Effect.succeed({ sequence: 1, storedEvents: [] });
|
||||
}
|
||||
if (command.type !== "thread.create") return Effect.die("unexpected command");
|
||||
if (options?.failCreate) {
|
||||
return Effect.fail(
|
||||
@@ -90,16 +104,37 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
}),
|
||||
);
|
||||
}
|
||||
projections.set(command.threadId, projectionFor(command.threadId));
|
||||
const projection = projectionFor(command.threadId);
|
||||
projections.set(command.threadId, {
|
||||
...projection,
|
||||
thread: {
|
||||
...projection.thread,
|
||||
title: command.title,
|
||||
branch: command.branch,
|
||||
worktreePath: command.worktreePath,
|
||||
},
|
||||
});
|
||||
return Effect.succeed({ sequence: 1, storedEvents: [] });
|
||||
},
|
||||
);
|
||||
const createWorktree = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
|
||||
} as never),
|
||||
const createWorktree = vi.fn(
|
||||
(_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
|
||||
} as never),
|
||||
);
|
||||
const removeWorktree = vi.fn(() => Effect.void);
|
||||
const fetchRemote = vi.fn(
|
||||
(_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["fetchRemote"]>[0]) =>
|
||||
Effect.void,
|
||||
);
|
||||
const resolveRemoteTrackingCommit = vi.fn(
|
||||
(
|
||||
_input: Parameters<
|
||||
GitWorkflow.GitWorkflowService["Service"]["resolveRemoteTrackingCommit"]
|
||||
>[0],
|
||||
) => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
|
||||
);
|
||||
const runForThread = vi.fn(() =>
|
||||
options?.failSetup
|
||||
? Effect.fail(
|
||||
@@ -126,7 +161,12 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
|
||||
snapshot: Effect.die("unused"),
|
||||
}),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({
|
||||
createWorktree,
|
||||
fetchRemote,
|
||||
removeWorktree,
|
||||
resolveRemoteTrackingCommit,
|
||||
}),
|
||||
Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
|
||||
runForThread,
|
||||
}),
|
||||
@@ -150,8 +190,11 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
),
|
||||
dispatch,
|
||||
fetchRemote,
|
||||
createWorktree,
|
||||
projections,
|
||||
removeWorktree,
|
||||
resolveRemoteTrackingCommit,
|
||||
runForThread,
|
||||
sendToThread,
|
||||
};
|
||||
@@ -213,6 +256,104 @@ it.effect(
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("preserves an existing worktree when launching a new thread", () => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
const result = yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_existing_worktree"),
|
||||
threadId: ThreadId.make("thread_existing_worktree"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: {
|
||||
type: "existing_worktree",
|
||||
worktreePath: "/repo-worktrees/existing",
|
||||
branch: "existing",
|
||||
},
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
assert.equal(result.projection.thread.worktreePath, "/repo-worktrees/existing");
|
||||
assert.equal(result.projection.thread.branch, "existing");
|
||||
assert.equal(test.createWorktree.mock.calls.length, 0);
|
||||
assert.equal(test.removeWorktree.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("fetches and resolves origin before provisioning an origin-based worktree", () => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_origin_worktree"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: {
|
||||
type: "worktree",
|
||||
baseRef: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
assert.deepEqual(test.fetchRemote.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
remoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(test.resolveRemoteTrackingCommit.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "main",
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(test.createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "remote-main-sha",
|
||||
newRefName: "feature",
|
||||
baseRefName: "main",
|
||||
path: null,
|
||||
});
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("provisions a worktree for an existing empty thread before sending", () => {
|
||||
const test = makeLayer();
|
||||
const threadId = ThreadId.make("thread_existing_empty");
|
||||
test.projections.set(threadId, projectionFor(threadId));
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_existing_empty"),
|
||||
threadId,
|
||||
reuseExistingThread: true,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" },
|
||||
initialMessage: { text: "Implement it", attachments: [] },
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
const updateCommand = test.dispatch.mock.calls.find(
|
||||
([command]) => command.type === "thread.metadata.update",
|
||||
)?.[0];
|
||||
assert.equal(updateCommand?.type, "thread.metadata.update");
|
||||
if (updateCommand?.type === "thread.metadata.update") {
|
||||
assert.equal(updateCommand.worktreePath, "/repo-worktrees/feature");
|
||||
assert.equal(updateCommand.branch, "feature");
|
||||
}
|
||||
assert.equal(test.sendToThread.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("removes a new worktree and does not create a thread when setup fails", () => {
|
||||
const test = makeLayer({ failSetup: true });
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ChatAttachment,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Actor,
|
||||
type OrchestrationV2CreationSource,
|
||||
@@ -27,20 +28,29 @@ import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
export type ThreadLaunchWorkspaceStrategy =
|
||||
| { readonly type: "root" }
|
||||
| { readonly type: "root"; readonly branch?: string | undefined }
|
||||
| {
|
||||
readonly type: "existing_worktree";
|
||||
readonly worktreePath: string;
|
||||
readonly branch?: string | undefined;
|
||||
}
|
||||
| {
|
||||
readonly type: "worktree";
|
||||
readonly baseRef: string;
|
||||
readonly branch?: string;
|
||||
readonly branch?: string | undefined;
|
||||
readonly startFromOrigin?: boolean | undefined;
|
||||
};
|
||||
|
||||
export interface ThreadLaunchInitialMessage {
|
||||
readonly messageId?: MessageId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}
|
||||
|
||||
export interface ThreadLaunchInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly reuseExistingThread?: boolean;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title: string;
|
||||
readonly modelSelection: ModelSelection;
|
||||
@@ -69,6 +79,7 @@ export class ThreadLaunchError extends Schema.TaggedErrorClass<ThreadLaunchError
|
||||
"provision-worktree",
|
||||
"run-setup-script",
|
||||
"create-thread",
|
||||
"update-thread",
|
||||
"dispatch-message",
|
||||
"compensate-worktree",
|
||||
]),
|
||||
@@ -185,11 +196,18 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const stored = yield* loadWorkflow(input);
|
||||
if (input.reuseExistingThread === true && input.threadId === undefined) {
|
||||
return yield* mapError(
|
||||
input,
|
||||
"update-thread",
|
||||
)("Reusing an existing thread requires a thread id.");
|
||||
}
|
||||
const threadId =
|
||||
stored === null
|
||||
? yield* ids.allocate
|
||||
? (input.threadId ??
|
||||
(yield* ids.allocate
|
||||
.thread({ projectId: input.projectId })
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))))
|
||||
: ThreadId.make(stored.thread_id);
|
||||
if (stored?.status === "completed") {
|
||||
return {
|
||||
@@ -201,7 +219,38 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
let branch = stored?.branch ?? null;
|
||||
const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(
|
||||
function* () {
|
||||
const projection = yield* threads
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
|
||||
if (
|
||||
projection.thread.projectId !== input.projectId ||
|
||||
projection.thread.archivedAt !== null ||
|
||||
projection.thread.deletedAt !== null ||
|
||||
projection.messages.length > 0 ||
|
||||
projection.runs.length > 0
|
||||
) {
|
||||
return yield* mapError(
|
||||
input,
|
||||
"update-thread",
|
||||
threadId,
|
||||
)(
|
||||
"Only an empty active thread in the target project can change workspace during launch.",
|
||||
);
|
||||
}
|
||||
return projection;
|
||||
},
|
||||
);
|
||||
if (input.reuseExistingThread === true && stored?.thread_committed !== 1) {
|
||||
yield* validateReusableThread();
|
||||
}
|
||||
|
||||
let branch =
|
||||
stored?.branch ??
|
||||
(input.workspaceStrategy.type === "worktree"
|
||||
? null
|
||||
: (input.workspaceStrategy.branch ?? null));
|
||||
let title = stored?.title ?? input.title;
|
||||
if (input.initialMessage !== undefined) {
|
||||
if (title === "New thread") {
|
||||
@@ -235,15 +284,36 @@ export const make = Effect.gen(function* () {
|
||||
branch = branch ?? input.workspaceStrategy.branch ?? `thread-${threadId}`;
|
||||
}
|
||||
|
||||
let worktreePath = stored?.worktree_path ?? null;
|
||||
let worktreePath =
|
||||
stored?.worktree_path ??
|
||||
(input.workspaceStrategy.type === "existing_worktree"
|
||||
? input.workspaceStrategy.worktreePath
|
||||
: null);
|
||||
const ownsProvisionedWorktree = input.workspaceStrategy.type === "worktree";
|
||||
const threadCommitted = stored?.thread_committed === 1;
|
||||
let setupCommitted = stored?.setup_committed === 1;
|
||||
let messageCommitted = stored?.message_committed === 1;
|
||||
if (input.workspaceStrategy.type === "worktree" && worktreePath === null) {
|
||||
let startRef = input.workspaceStrategy.baseRef;
|
||||
if (input.workspaceStrategy.startFromOrigin === true) {
|
||||
yield* git
|
||||
.fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
|
||||
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
|
||||
startRef = yield* git
|
||||
.resolveRemoteTrackingCommit({
|
||||
cwd: project.workspaceRoot,
|
||||
refName: input.workspaceStrategy.baseRef,
|
||||
fallbackRemoteName: "origin",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((resolved) => resolved.commitSha),
|
||||
Effect.mapError(mapError(input, "provision-worktree", threadId)),
|
||||
);
|
||||
}
|
||||
const worktree = yield* git
|
||||
.createWorktree({
|
||||
cwd: project.workspaceRoot,
|
||||
refName: input.workspaceStrategy.baseRef,
|
||||
refName: startRef,
|
||||
newRefName: branch!,
|
||||
baseRefName: input.workspaceStrategy.baseRef,
|
||||
path: null,
|
||||
@@ -278,7 +348,7 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
if (setupExit._tag === "Failure") {
|
||||
if (worktreePath !== null && !threadCommitted) {
|
||||
if (ownsProvisionedWorktree && worktreePath !== null && !threadCommitted) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
@@ -313,24 +383,36 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (!threadCommitted) {
|
||||
const createExit = yield* Effect.exit(
|
||||
threads.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch,
|
||||
worktreePath,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
}),
|
||||
);
|
||||
const commitThread =
|
||||
input.reuseExistingThread === true
|
||||
? Effect.gen(function* () {
|
||||
yield* validateReusableThread();
|
||||
return yield* threads.dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
title,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
})
|
||||
: threads.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch,
|
||||
worktreePath,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
});
|
||||
const createExit = yield* Effect.exit(commitThread);
|
||||
if (createExit._tag === "Failure") {
|
||||
if (worktreePath !== null) {
|
||||
if (ownsProvisionedWorktree && worktreePath !== null) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
@@ -339,17 +421,27 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "thread_create_failed",
|
||||
status:
|
||||
input.reuseExistingThread === true ? "thread_update_failed" : "thread_create_failed",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted: false,
|
||||
messageCommitted,
|
||||
lastError: "Thread creation failed.",
|
||||
lastError:
|
||||
input.reuseExistingThread === true
|
||||
? "Thread workspace update failed."
|
||||
: "Thread creation failed.",
|
||||
});
|
||||
return yield* Effect.failCause(createExit.cause).pipe(
|
||||
Effect.mapError(mapError(input, "create-thread", threadId)),
|
||||
Effect.mapError(
|
||||
mapError(
|
||||
input,
|
||||
input.reuseExistingThread === true ? "update-thread" : "create-thread",
|
||||
threadId,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
@@ -365,9 +457,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (input.initialMessage !== undefined && !messageCommitted) {
|
||||
const messageId = yield* ids.allocate
|
||||
.message({ threadId, ordinal: 1 })
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
|
||||
const messageId =
|
||||
input.initialMessage.messageId ??
|
||||
(yield* ids.allocate
|
||||
.message({ threadId, ordinal: 1 })
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
|
||||
yield* threads
|
||||
.sendToThread({
|
||||
projectId: input.projectId,
|
||||
|
||||
@@ -32,7 +32,7 @@ import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlS
|
||||
import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts";
|
||||
import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
|
||||
import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.ts";
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layerFromProjectRepository as runtimePolicyLayerFromProjectRepository } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
@@ -40,6 +40,13 @@ import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.t
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
|
||||
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
const runtimePolicyProvided = runtimePolicyLayerFromProjectRepository.pipe(
|
||||
Layer.provide(ProjectionProjectRepositoryLive),
|
||||
);
|
||||
|
||||
const eventStoreProvided = eventStoreLayer.pipe(
|
||||
Layer.provide(OrchestrationEventInfrastructureLayerLive),
|
||||
);
|
||||
@@ -111,7 +118,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runExecutionServiceProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -130,7 +137,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -189,7 +196,7 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
providerAdapterRegistryProvided,
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
@@ -201,9 +208,6 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
);
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
);
|
||||
|
||||
+199
-28
@@ -1,8 +1,11 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -13,9 +16,11 @@ import {
|
||||
type AuthAccessStreamEvent,
|
||||
type AuthEnvironmentScope,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
type DiscoveredLocalServerList,
|
||||
type GitActionProgressEvent,
|
||||
type GitManagerServiceError,
|
||||
type MessageId,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
@@ -28,18 +33,21 @@ import {
|
||||
type ProjectEntriesFailure,
|
||||
type ProjectFileFailure,
|
||||
type ProjectFileOperation,
|
||||
type ProjectMutation,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchContentsError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
ProjectMutationError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
RpcClientId,
|
||||
ChatAttachmentId,
|
||||
PersistChatAttachmentsError,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
@@ -81,6 +89,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import { issueAssetUrl } from "./assets/AssetAccess.ts";
|
||||
import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -118,6 +128,73 @@ function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
}
|
||||
|
||||
const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageId: MessageId;
|
||||
readonly attachments: ReadonlyArray<{
|
||||
readonly type: "image";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly dataUrl: string;
|
||||
}>;
|
||||
}) {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return yield* Effect.forEach(
|
||||
input.attachments.map((attachment, index) => ({ attachment, index })),
|
||||
Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} has an invalid image payload.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* Effect.fromResult(Encoding.decodeBase64(parsed.base64)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} is not valid base64.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (bytes.byteLength !== attachment.sizeBytes) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} size does not match its payload.`,
|
||||
});
|
||||
}
|
||||
const rawId = createDeterministicAttachmentId(input.threadId, `${input.messageId}:${index}`);
|
||||
if (rawId === null) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: "Could not allocate an attachment identifier.",
|
||||
});
|
||||
}
|
||||
const persisted = {
|
||||
type: "image" as const,
|
||||
id: ChatAttachmentId.make(rawId),
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
yield* fileSystem
|
||||
.writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)), bytes)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Could not persist attachment ${attachment.name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return persisted;
|
||||
}),
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
});
|
||||
|
||||
function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {
|
||||
readonly failure: ProjectEntriesFailure;
|
||||
readonly normalizedCwd?: string;
|
||||
@@ -253,8 +330,11 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsMutate, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
|
||||
@@ -623,20 +703,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
},
|
||||
);
|
||||
|
||||
const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
schemaVersion: snapshot.schemaVersion,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
threads: snapshot.archivedThreads,
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const getOrchestrationV2ArchivedShellSnapshot = sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const threads = yield* threadManagement.getShellSnapshot();
|
||||
return {
|
||||
schemaVersion: threads.schemaVersion,
|
||||
snapshotSequence: yield* applicationEvents.latestApplicationSequence,
|
||||
projects: projects.projects,
|
||||
threads: threads.archivedThreads,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const subscribeOrchestrationV2ArchivedShell = Effect.fn(
|
||||
"ws.orchestrationV2.subscribeArchivedShell",
|
||||
@@ -671,6 +759,64 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live);
|
||||
});
|
||||
|
||||
const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) {
|
||||
switch (mutation.type) {
|
||||
case "project.create":
|
||||
return yield* projectService.create({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
title: mutation.title,
|
||||
workspaceRoot: mutation.workspaceRoot,
|
||||
...(mutation.createWorkspaceRootIfMissing === undefined
|
||||
? {}
|
||||
: { createWorkspaceRootIfMissing: mutation.createWorkspaceRootIfMissing }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.update":
|
||||
return yield* projectService.update({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
...(mutation.title === undefined ? {} : { title: mutation.title }),
|
||||
...(mutation.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: mutation.workspaceRoot }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.delete": {
|
||||
const snapshot = yield* threadManagement.getShellSnapshot();
|
||||
const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
|
||||
(thread) => thread.projectId === mutation.projectId,
|
||||
);
|
||||
if (projectThreads.length > 0 && mutation.force !== true) {
|
||||
return yield* new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: `Project ${mutation.projectId} is not empty.`,
|
||||
});
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
projectThreads,
|
||||
(thread) =>
|
||||
threadManagement.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.make(`${mutation.commandId}:delete-thread:${thread.id}`),
|
||||
threadId: thread.id,
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
return yield* projectService.delete({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handlers = ServerWsRpcGroup.of({
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
@@ -680,7 +826,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
threadManagement.dispatch(
|
||||
ThreadManagementService.withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: "creationSource" in command ? command.creationSource : "web",
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -771,26 +917,29 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
.enqueueCommand(
|
||||
threadLaunch.launch({
|
||||
commandId: input.commandId,
|
||||
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input.reuseExistingThread === undefined
|
||||
? {}
|
||||
: { reuseExistingThread: input.reuseExistingThread }),
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy:
|
||||
input.workspaceStrategy.type === "root"
|
||||
? { type: "root" }
|
||||
: {
|
||||
type: "worktree",
|
||||
baseRef: input.workspaceStrategy.baseRef,
|
||||
...(input.workspaceStrategy.branch === undefined
|
||||
? {}
|
||||
: { branch: input.workspaceStrategy.branch }),
|
||||
},
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
...(input.initialMessage === undefined
|
||||
? {}
|
||||
: { initialMessage: input.initialMessage }),
|
||||
: {
|
||||
initialMessage: {
|
||||
...(input.initialMessage.messageId === undefined
|
||||
? {}
|
||||
: { messageId: input.initialMessage.messageId }),
|
||||
text: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
},
|
||||
}),
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -1137,6 +1286,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsMutate]: (mutation) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsMutate,
|
||||
startup.enqueueCommand(mutateProject(mutation)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProjectMutationError"
|
||||
? cause
|
||||
: new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: "Failed to mutate project.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
@@ -1195,6 +1360,12 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsPersistChatAttachments]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsPersistChatAttachments,
|
||||
persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
|
||||
@@ -116,6 +116,8 @@ export function BranchToolbarBranchSelector({
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
[environmentId, threadId],
|
||||
);
|
||||
const serverThread = useThread(threadRef);
|
||||
const serverSession = serverThread?.runtime ?? null;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { Thread, ThreadShell } from "../types";
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
@@ -37,7 +31,7 @@ const threadId = ThreadId.make("thread-1");
|
||||
const now = "2026-03-29T00:00:00.000Z";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: threadId,
|
||||
environmentId,
|
||||
projectId,
|
||||
@@ -48,27 +42,25 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const completedTurn = {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed" as const,
|
||||
runId: RunId.make("turn-1"),
|
||||
status: "completed" as const,
|
||||
requestedAt: now,
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: "2026-03-29T00:00:10.000Z",
|
||||
@@ -76,12 +68,10 @@ const completedTurn = {
|
||||
};
|
||||
|
||||
const readySession = {
|
||||
threadId,
|
||||
status: "ready" as const,
|
||||
status: "completed" as const,
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access" as const,
|
||||
activeTurnId: null,
|
||||
activeRunId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
@@ -527,16 +517,15 @@ describe("startNewThreadForProject", () => {
|
||||
describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
it("does not acknowledge unchanged server state", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: completedTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: readySession,
|
||||
latestRun: completedTurn,
|
||||
runtime: readySession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -546,11 +535,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("acknowledges a settled newer turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const newerTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("turn-2"),
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: "2026-03-29T00:01:30.000Z",
|
||||
@@ -560,9 +549,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: newerTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
latestRun: newerTurn,
|
||||
runtime: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -572,12 +560,12 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("waits for the matching running turn before acknowledging", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const runningTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running" as const,
|
||||
runId: RunId.make("turn-2"),
|
||||
status: "running" as const,
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
@@ -587,12 +575,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: TurnId.make("turn-other"),
|
||||
activeRunId: RunId.make("turn-other"),
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -603,12 +590,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: runningTurn.turnId,
|
||||
activeRunId: runningTurn.runId,
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -665,9 +651,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
const common = {
|
||||
localDispatch,
|
||||
phase: "ready" as const,
|
||||
latestTurn: null,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: null,
|
||||
latestRun: null,
|
||||
runtime: null,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
type ScopedProjectRef,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadShell } from "../types";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { presentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -70,29 +72,46 @@ export function buildLocalDraftThread(
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModelSelection: ModelSelection,
|
||||
): Thread {
|
||||
return {
|
||||
id: threadId,
|
||||
environmentId: draftThread.environmentId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
|
||||
return presentThread(draftThread.environmentId, {
|
||||
thread: {
|
||||
id: threadId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
providerInstanceId: fallbackModelSelection.instanceId,
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
};
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
|
||||
@@ -353,7 +372,7 @@ export function isBranchMismatchDismissedForSession(key: string | null): boolean
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
thread && (thread.latestRun !== null || thread.messages.length > 0 || thread.runtime !== null),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -377,7 +396,7 @@ export function deriveLockedProvider(input: {
|
||||
if (!threadHasStarted(input.thread)) {
|
||||
return null;
|
||||
}
|
||||
const sessionProvider = input.thread?.session?.providerName ?? null;
|
||||
const sessionProvider = input.thread?.runtime?.providerName ?? null;
|
||||
if (sessionProvider && isProviderDriverKind(sessionProvider)) {
|
||||
return sessionProvider;
|
||||
}
|
||||
@@ -478,41 +497,37 @@ export async function waitForStartedServerThread(
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
latestTurnStartedAt: string | null;
|
||||
latestTurnCompletedAt: string | null;
|
||||
sessionStatus: NonNullable<Thread["session"]>["status"] | null;
|
||||
sessionUpdatedAt: string | null;
|
||||
latestRunId: RunId | null;
|
||||
latestRunRequestedAt: string | null;
|
||||
latestRunStartedAt: string | null;
|
||||
latestRunCompletedAt: string | null;
|
||||
runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
|
||||
runtimeUpdatedAt: string | null;
|
||||
}
|
||||
|
||||
export function createLocalDispatchSnapshot(
|
||||
activeThread: Thread | undefined,
|
||||
options?: { preparingWorktree?: boolean },
|
||||
): LocalDispatchSnapshot {
|
||||
const latestTurn = activeThread?.latestTurn ?? null;
|
||||
const session = activeThread?.session ?? null;
|
||||
const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
|
||||
const latestRun = activeThread?.latestRun ?? null;
|
||||
const runtime = activeThread?.runtime ?? null;
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
latestUserMessageId: latestUserMessage?.id ?? null,
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
latestTurnStartedAt: latestTurn?.startedAt ?? null,
|
||||
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
|
||||
sessionStatus: session?.status ?? null,
|
||||
sessionUpdatedAt: session?.updatedAt ?? null,
|
||||
latestRunId: latestRun?.runId ?? null,
|
||||
latestRunRequestedAt: latestRun?.requestedAt ?? null,
|
||||
latestRunStartedAt: latestRun?.startedAt ?? null,
|
||||
latestRunCompletedAt: latestRun?.completedAt ?? null,
|
||||
runtimeStatus: runtime?.status ?? null,
|
||||
runtimeUpdatedAt: runtime?.updatedAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
localDispatch: LocalDispatchSnapshot | null;
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
session: Thread["session"] | null;
|
||||
latestRun: Thread["latestRun"] | null;
|
||||
runtime: Thread["runtime"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
threadError: string | null | undefined;
|
||||
@@ -524,34 +539,25 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
const latestUserMessageChanged =
|
||||
input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
const latestRun = input.latestRun ?? null;
|
||||
const runtime = input.runtime ?? null;
|
||||
const latestRunChanged =
|
||||
input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
|
||||
input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
|
||||
input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
// Steering adds a user message to the current running turn without
|
||||
// necessarily changing any of the turn timestamps. Treat that projected
|
||||
// message as the server acknowledgment so the composer does not remain
|
||||
// stuck in its local "Sending" state until the turn settles.
|
||||
if (latestUserMessageChanged) {
|
||||
return true;
|
||||
}
|
||||
if (!latestTurnChanged) {
|
||||
if (!latestRunChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
if (latestRun?.startedAt === null || latestRun === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== null &&
|
||||
session?.activeTurnId !== undefined &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
runtime?.activeRunId !== null &&
|
||||
runtime?.activeRunId !== undefined &&
|
||||
latestRun?.runId !== runtime.activeRunId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -559,8 +565,8 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionStatus !== (session?.status ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
latestRunChanged ||
|
||||
input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
|
||||
input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL,
|
||||
defaultInstanceIdForDriver,
|
||||
type EnvironmentId,
|
||||
@@ -13,14 +12,15 @@ import {
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
type RuntimeRequestId,
|
||||
type KeybindingCommand,
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
ProviderDriverKind,
|
||||
RuntimeMode,
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
@@ -78,13 +78,14 @@ import {
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveTimelineEntriesFromVisibleTurnItems,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findSidebarProposedPlan,
|
||||
findLatestProposedPlan,
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
isLatestRunSettled,
|
||||
} from "../session-logic";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
|
||||
@@ -217,7 +218,7 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadShell,
|
||||
useThreadVisibleTurnItems,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -309,7 +310,7 @@ import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_WORK_ENTRIES: ThreadWorkEntry[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
@@ -494,10 +495,10 @@ type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "work
|
||||
|
||||
function useLocalDispatchState(input: {
|
||||
activeThread: Thread | undefined;
|
||||
activeLatestTurn: Thread["latestTurn"] | null;
|
||||
activeLatestRun: Thread["latestRun"] | null;
|
||||
phase: SessionPhase;
|
||||
activePendingApproval: ApprovalRequestId | null;
|
||||
activePendingUserInput: ApprovalRequestId | null;
|
||||
activePendingApproval: RuntimeRequestId | null;
|
||||
activePendingUserInput: RuntimeRequestId | null;
|
||||
threadError: string | null | undefined;
|
||||
}) {
|
||||
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
|
||||
@@ -513,18 +514,17 @@ function useLocalDispatchState(input: {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: input.phase,
|
||||
latestTurn: input.activeLatestTurn,
|
||||
latestUserMessageId,
|
||||
session: input.activeThread?.session ?? null,
|
||||
latestRun: input.activeLatestRun,
|
||||
runtime: input.activeThread?.runtime ?? null,
|
||||
hasPendingApproval: input.activePendingApproval !== null,
|
||||
hasPendingUserInput: input.activePendingUserInput !== null,
|
||||
threadError: input.threadError,
|
||||
}),
|
||||
[
|
||||
input.activeLatestTurn,
|
||||
input.activeLatestRun,
|
||||
input.activePendingApproval,
|
||||
input.activePendingUserInput,
|
||||
input.activeThread?.session,
|
||||
input.activeThread?.runtime,
|
||||
input.phase,
|
||||
input.threadError,
|
||||
latestUserMessageId,
|
||||
@@ -1202,23 +1202,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const composerDraftTarget: ScopedThreadRef | DraftId =
|
||||
routeKind === "server" ? routeThreadRef : props.draftId;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
routeKind === "server"
|
||||
? store.getDraftSessionByRef(routeThreadRef)
|
||||
: draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: null,
|
||||
const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);
|
||||
const serverVisibleTurnItems = useThreadVisibleTurnItems(
|
||||
routeKind === "server" ? routeThreadRef : null,
|
||||
);
|
||||
const routeServerThreadShell = useThreadShell(routeKind === "server" ? routeThreadRef : null);
|
||||
const serverThread = useThread(routeThreadRef, { waitForShell: draftThread !== null });
|
||||
const loadingServerThread = useMemo(
|
||||
() =>
|
||||
threadDetailLoading && routeServerThreadShell
|
||||
? buildLoadingThreadFromShell(routeServerThreadShell)
|
||||
: null,
|
||||
[routeServerThreadShell, threadDetailLoading],
|
||||
);
|
||||
const activeServerThread = serverThread ?? loadingServerThread;
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const activeThreadLastVisitedAt = useUiStateStore(
|
||||
(store) => store.threadLastVisitedAtById[routeThreadKey],
|
||||
@@ -1293,9 +1280,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
|
||||
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
|
||||
ApprovalRequestId[]
|
||||
RuntimeRequestId[]
|
||||
>([]);
|
||||
const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
@@ -1454,7 +1441,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const isServerThread = activeServerThread !== null;
|
||||
const activeThread = activeServerThread ?? localDraftThread;
|
||||
const threadError = isServerThread
|
||||
? (localServerError ?? activeServerThread?.session?.lastError ?? null)
|
||||
? (localServerError ?? serverThread?.runtime?.lastError ?? null)
|
||||
: localDraftError;
|
||||
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode =
|
||||
@@ -1576,14 +1563,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
|
||||
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
|
||||
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const activeLatestRun = activeThread?.latestRun ?? null;
|
||||
const sourcePlanThreadRef = useMemo(() => {
|
||||
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
|
||||
const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId;
|
||||
if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) {
|
||||
return null;
|
||||
}
|
||||
return scopeThreadRef(activeThread.environmentId, sourceThreadId);
|
||||
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread]);
|
||||
}, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]);
|
||||
const sourceThreadProposedPlans = useThreadProposedPlans(sourcePlanThreadRef);
|
||||
const threadPlanCatalog = useMemo<ThreadPlanCatalogEntry[]>(() => {
|
||||
if (!activeThread) {
|
||||
@@ -1615,7 +1602,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: nextThreadIds;
|
||||
});
|
||||
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const latestRunSettled = isLatestRunSettled(activeLatestRun, activeThread?.runtime ?? null);
|
||||
const activeProjectRef = activeThread
|
||||
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
|
||||
: null;
|
||||
@@ -2047,16 +2034,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
selectedProviderByThreadId ?? threadProvider,
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
|
||||
const phase = derivePhase(activeThread?.runtime ?? null);
|
||||
const threadWorkEntries = activeThread?.workEntries ?? EMPTY_WORK_ENTRIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadWorkEntries),
|
||||
[threadWorkEntries],
|
||||
);
|
||||
const pendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(threadActivities),
|
||||
[threadActivities],
|
||||
() => derivePendingApprovals(activeThread?.pendingApprovals ?? []),
|
||||
[activeThread?.pendingApprovals],
|
||||
);
|
||||
const pendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(threadActivities),
|
||||
[threadActivities],
|
||||
() => derivePendingUserInputs(activeThread?.pendingUserInputs ?? []),
|
||||
[activeThread?.pendingUserInputs],
|
||||
);
|
||||
const activePendingUserInput = pendingUserInputs[0] ?? null;
|
||||
const activePendingDraftAnswers = useMemo(
|
||||
@@ -2089,36 +2079,37 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
[activePendingDraftAnswers, activePendingUserInput],
|
||||
);
|
||||
const activePendingIsResponding = activePendingUserInput
|
||||
? respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
|
||||
? activePendingUserInput.responseCapability !== "live" ||
|
||||
respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
|
||||
: false;
|
||||
const activeProposedPlan = useMemo(() => {
|
||||
if (!latestTurnSettled) {
|
||||
if (!latestRunSettled) {
|
||||
return null;
|
||||
}
|
||||
return findLatestProposedPlan(
|
||||
activeThread?.proposedPlans ?? [],
|
||||
activeLatestTurn?.turnId ?? null,
|
||||
activeLatestRun?.runId ?? null,
|
||||
);
|
||||
}, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]);
|
||||
}, [activeLatestRun?.runId, activeThread?.proposedPlans, latestRunSettled]);
|
||||
const sidebarProposedPlan = useMemo(
|
||||
() =>
|
||||
findSidebarProposedPlan({
|
||||
threads: threadPlanCatalog,
|
||||
latestTurn: activeLatestTurn,
|
||||
latestTurnSettled,
|
||||
latestRun: activeLatestRun,
|
||||
latestRunSettled,
|
||||
threadId: activeThread?.id ?? null,
|
||||
}),
|
||||
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
|
||||
[activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog],
|
||||
);
|
||||
const activePlan = useMemo(
|
||||
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
() => deriveActivePlanState(activeThread?.todoPlans ?? [], activeLatestRun?.runId ?? undefined),
|
||||
[activeLatestRun?.runId, activeThread?.todoPlans],
|
||||
);
|
||||
const planSidebarLabel = sidebarProposedPlan || interactionMode === "plan" ? "Plan" : "Tasks";
|
||||
const showPlanFollowUpPrompt =
|
||||
pendingUserInputs.length === 0 &&
|
||||
interactionMode === "plan" &&
|
||||
latestTurnSettled &&
|
||||
latestRunSettled &&
|
||||
hasActionableProposedPlan(activeProposedPlan);
|
||||
const activePendingApproval = pendingApprovals[0] ?? null;
|
||||
const {
|
||||
@@ -2129,7 +2120,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
isSendBusy,
|
||||
} = useLocalDispatchState({
|
||||
activeThread,
|
||||
activeLatestTurn,
|
||||
activeLatestRun,
|
||||
phase,
|
||||
activePendingApproval: activePendingApproval?.requestId ?? null,
|
||||
activePendingUserInput: activePendingUserInput?.requestId ?? null,
|
||||
@@ -2137,8 +2128,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
activeLatestRun,
|
||||
activeThread?.runtime ?? null,
|
||||
localDispatchStartedAt,
|
||||
);
|
||||
useEffect(() => {
|
||||
@@ -2202,7 +2193,17 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
}, []);
|
||||
const serverMessages = activeThread?.messages;
|
||||
const serverAttachmentIds = useMemo(() => {
|
||||
const committedServerAttachmentIds = useMemo(() => {
|
||||
const attachmentIds = new Set<string>();
|
||||
for (const row of serverVisibleTurnItems) {
|
||||
if (row.item.type !== "user_message") continue;
|
||||
for (const attachment of row.item.attachments) {
|
||||
attachmentIds.add(attachment.id);
|
||||
}
|
||||
}
|
||||
return [...attachmentIds];
|
||||
}, [serverVisibleTurnItems]);
|
||||
const draftAttachmentIds = useMemo(() => {
|
||||
const attachmentIds = new Set<string>();
|
||||
for (const message of serverMessages ?? []) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
@@ -2211,6 +2212,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return [...attachmentIds];
|
||||
}, [serverMessages]);
|
||||
const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : draftAttachmentIds;
|
||||
const serverAttachmentResources = useMemo(
|
||||
() =>
|
||||
serverAttachmentIds.map((attachmentId) => ({
|
||||
@@ -2381,22 +2383,22 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
|
||||
}, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);
|
||||
const timelineEntries = useMemo(
|
||||
const serverTimelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntriesFromVisibleTurnItems({
|
||||
visibleTurnItems: serverVisibleTurnItems,
|
||||
optimisticMessages: optimisticUserMessages,
|
||||
attachmentUrlById: serverAttachmentUrlById,
|
||||
}),
|
||||
[optimisticUserMessages, serverVisibleTurnItems, serverAttachmentUrlById],
|
||||
);
|
||||
const draftTimelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
|
||||
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
|
||||
);
|
||||
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
|
||||
const draftHeroDockRequested =
|
||||
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
|
||||
const isDraftHeroState =
|
||||
isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested;
|
||||
const [
|
||||
attachDraftHeroTransitionGroupRef,
|
||||
attachDraftHeroComposerAnchorRef,
|
||||
captureDraftHeroComposerRect,
|
||||
] = useDraftHeroLayoutTransition(isDraftHeroState);
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
|
||||
const byMessageId = new Map<MessageId, TurnDiffSummary>();
|
||||
@@ -2427,7 +2429,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
continue;
|
||||
}
|
||||
const turnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[summary.runId];
|
||||
if (typeof turnCount !== "number") {
|
||||
break;
|
||||
}
|
||||
@@ -2437,7 +2439,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
return byUserMessageId;
|
||||
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||
}, [inferredCheckpointTurnCountByRunId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
@@ -2465,7 +2467,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
?.instanceId ?? null;
|
||||
const activeProviderInstanceId =
|
||||
selectedProviderInstanceId ??
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.runtime?.providerInstanceId ??
|
||||
activeThread?.modelSelection.instanceId ??
|
||||
activeProject?.defaultModelSelection?.instanceId ??
|
||||
null;
|
||||
@@ -2544,9 +2546,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]);
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "stopped")),
|
||||
activeThread && (activeThread.messages.length > 0 || activeThread.runtime !== null),
|
||||
);
|
||||
|
||||
// Handle environment change for draft threads. When the user picks a
|
||||
@@ -3092,8 +3092,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [handleInteractionModeChange, interactionMode]);
|
||||
const dismissPlanSidebarForCurrentTurn = useCallback(() => {
|
||||
planSidebarDismissedForTurnRef.current =
|
||||
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
activePlan?.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__";
|
||||
}, [activePlan?.runId, sidebarProposedPlan?.runId]);
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
if (planSidebarOpen) {
|
||||
@@ -3842,20 +3842,20 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!autoOpenPlanSidebar) return;
|
||||
if (!activePlan) return;
|
||||
if (planSidebarOpen) return;
|
||||
const latestTurnId = activeLatestTurn?.turnId ?? null;
|
||||
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
|
||||
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
const latestRunId = activeLatestRun?.runId ?? null;
|
||||
if (latestRunId && activePlan.runId !== latestRunId) return;
|
||||
const turnKey = activePlan.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__";
|
||||
if (planSidebarDismissedForTurnRef.current === turnKey) return;
|
||||
if (activeThreadRef) {
|
||||
useRightPanelStore.getState().open(activeThreadRef, "plan");
|
||||
}
|
||||
}, [
|
||||
activePlan,
|
||||
activeLatestTurn?.turnId,
|
||||
activeLatestRun?.runId,
|
||||
activeThreadRef,
|
||||
autoOpenPlanSidebar,
|
||||
planSidebarOpen,
|
||||
sidebarProposedPlan?.turnId,
|
||||
sidebarProposedPlan?.runId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -4753,7 +4753,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
role: "user",
|
||||
text: outgoingMessageText,
|
||||
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: messageCreatedAt,
|
||||
updatedAt: messageCreatedAt,
|
||||
streaming: false,
|
||||
@@ -4966,8 +4966,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
};
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!activeThreadId) return;
|
||||
if (
|
||||
pendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
)
|
||||
return;
|
||||
|
||||
setRespondingRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
@@ -4990,12 +4995,17 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
return result;
|
||||
},
|
||||
[activeThreadId, environmentId, respondToThreadApproval, setThreadError],
|
||||
[activeThreadId, environmentId, pendingApprovals, respondToThreadApproval, setThreadError],
|
||||
);
|
||||
|
||||
const onRespondToUserInput = useCallback(
|
||||
async (requestId: ApprovalRequestId, answers: Record<string, unknown>) => {
|
||||
async (requestId: RuntimeRequestId, answers: Record<string, unknown>) => {
|
||||
if (!activeThreadId) return;
|
||||
if (
|
||||
pendingUserInputs.find((input) => input.requestId === requestId)?.responseCapability !==
|
||||
"live"
|
||||
)
|
||||
return;
|
||||
|
||||
setRespondingUserInputRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
@@ -5018,7 +5028,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
return result;
|
||||
},
|
||||
[activeThreadId, environmentId, respondToThreadUserInput, setThreadError],
|
||||
[activeThreadId, environmentId, pendingUserInputs, respondToThreadUserInput, setThreadError],
|
||||
);
|
||||
|
||||
const setActivePendingUserInputQuestionIndex = useCallback(
|
||||
@@ -5102,7 +5112,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onAdvanceActivePendingUserInput = useCallback(() => {
|
||||
if (!activePendingUserInput || !activePendingProgress) {
|
||||
if (
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingProgress
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (activePendingProgress.isLastQuestion) {
|
||||
@@ -5196,7 +5210,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
id: messageIdForSend,
|
||||
role: "user",
|
||||
text: outgoingMessageText,
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: messageCreatedAt,
|
||||
updatedAt: messageCreatedAt,
|
||||
streaming: false,
|
||||
@@ -5466,9 +5480,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
const reason = getStartedThreadModelChangeBlockReason({
|
||||
providers: providerStatuses,
|
||||
hasStartedSession: activeThread.session !== null,
|
||||
hasStartedSession: activeThread.runtime !== null,
|
||||
currentModelSelection: activeThread.modelSelection,
|
||||
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
|
||||
currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null,
|
||||
nextModelSelection: { instanceId, model },
|
||||
});
|
||||
return reason ? `${reason.description} Start a new thread to use this model.` : null;
|
||||
@@ -5492,9 +5506,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
if (lockedProvider !== null && activeThread.session?.providerInstanceId) {
|
||||
if (lockedProvider !== null && activeThread.runtime?.providerInstanceId) {
|
||||
const currentEntry = providerStatuses.find(
|
||||
(snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId,
|
||||
(snapshot) => snapshot.instanceId === activeThread.runtime?.providerInstanceId,
|
||||
);
|
||||
if (
|
||||
currentEntry?.continuation?.groupKey &&
|
||||
@@ -5521,9 +5535,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
};
|
||||
const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({
|
||||
providers: providerStatuses,
|
||||
hasStartedSession: activeThread.session !== null,
|
||||
hasStartedSession: activeThread.runtime !== null,
|
||||
currentModelSelection: activeThread.modelSelection,
|
||||
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
|
||||
currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null,
|
||||
nextModelSelection,
|
||||
});
|
||||
if (modelChangeBlockReason) {
|
||||
@@ -5603,9 +5617,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setExpandedImage(preview);
|
||||
}, []);
|
||||
const onOpenTurnDiff = useCallback(
|
||||
(turnId: TurnId, filePath?: string) => {
|
||||
(runId: RunId, filePath?: string) => {
|
||||
if (!isServerThread || !activeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(activeThreadRef, turnId, filePath);
|
||||
useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath);
|
||||
useRightPanelStore.getState().open(activeThreadRef, "diff");
|
||||
onDiffPanelOpen?.();
|
||||
},
|
||||
@@ -5800,16 +5814,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnInProgress={isWorking || !latestRunSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
latestTurn={activeLatestTurn}
|
||||
runningTurnId={
|
||||
activeThread.session?.status === "running"
|
||||
? activeThread.session.activeTurnId
|
||||
: null
|
||||
}
|
||||
latestRun={activeLatestRun}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
routeThreadKey={routeThreadKey}
|
||||
@@ -5867,168 +5876,86 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
ref={attachDraftHeroTransitionGroupRef}
|
||||
className="chat-composer-horizontal-inset w-full"
|
||||
>
|
||||
<div className="pointer-events-auto relative z-10">
|
||||
{isDraftHeroState ? (
|
||||
<div className="absolute inset-x-0 bottom-full z-0">
|
||||
<div
|
||||
className="pb-8"
|
||||
style={
|
||||
forceExpandedMobileComposer
|
||||
? {
|
||||
viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<DraftHeroHeadline
|
||||
activeProjectRef={activeProjectRef}
|
||||
activeProjectTitle={activeProject?.title ?? null}
|
||||
/>
|
||||
</div>
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
</div>
|
||||
) : (
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
)}
|
||||
{threadSyncPhase && !activeEnvironmentUnavailable ? (
|
||||
<ThreadSyncStatusPill phase={threadSyncPhase} />
|
||||
) : null}
|
||||
<div
|
||||
className="relative"
|
||||
style={
|
||||
forceExpandedMobileComposer
|
||||
? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-glass-shell relative mx-auto w-full max-w-3xl",
|
||||
showComposerContextStrip && "chat-composer-glass-shell-with-context",
|
||||
)}
|
||||
>
|
||||
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
sendDisabledReason={threadDetailLoading ? "Messages loading" : null}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={
|
||||
activeProject?.defaultModelSelection
|
||||
}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{showComposerContextStrip && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
aria-hidden
|
||||
className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"
|
||||
<div className="relative mx-auto h-full w-full max-w-208 overflow-clip rounded-t-[20px]">
|
||||
<div className="chat-composer-shared-blur absolute -inset-8" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-composer-horizontal-inset">
|
||||
<div className="pointer-events-auto relative z-10 isolate">
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<div className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan}
|
||||
sidebarProposedPlan={sidebarProposedPlan}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadWorkEntries={activeThread?.workEntries}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
shouldAutoScrollRef={isAtEndRef}
|
||||
scheduleStickToBottom={scrollToEnd}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import {
|
||||
buildBrowseGroups,
|
||||
buildThreadActionItems,
|
||||
@@ -112,7 +113,7 @@ const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
@@ -120,7 +121,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
@@ -129,13 +130,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
@@ -246,55 +246,55 @@ export default function DiffPanel({
|
||||
),
|
||||
);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
() =>
|
||||
[...turnDiffSummaries].toSorted((left, right) => {
|
||||
const leftTurnCount =
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
|
||||
const rightTurnCount =
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
|
||||
if (leftTurnCount !== rightTurnCount) {
|
||||
return rightTurnCount - leftTurnCount;
|
||||
}
|
||||
return right.completedAt.localeCompare(left.completedAt);
|
||||
}),
|
||||
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
|
||||
[inferredCheckpointTurnCountByRunId, turnDiffSummaries],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!routeThreadRef || diffSelection.kind !== "turn") return;
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(
|
||||
routeThreadRef,
|
||||
orderedTurnDiffSummaries.map((summary) => summary.turnId),
|
||||
orderedTurnDiffSummaries.map((summary) => summary.runId),
|
||||
);
|
||||
}, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
|
||||
|
||||
const selectedTurnId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
|
||||
const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
|
||||
const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
|
||||
const selectedFileRevealRequestId =
|
||||
diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? undefined
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
|
||||
orderedTurnDiffSummaries[0]);
|
||||
const selectedCheckpointTurnCount =
|
||||
selectedTurn &&
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]);
|
||||
const latestTurn = orderedTurnDiffSummaries[0];
|
||||
const selectedScopeLabel =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? selectedGitScope === "unstaged"
|
||||
? "Working tree"
|
||||
: "Branch changes"
|
||||
: selectedTurn?.turnId === latestTurn?.turnId
|
||||
: selectedTurn?.runId === latestTurn?.runId
|
||||
? "Latest turn"
|
||||
: `Turn ${selectedCheckpointTurnCount ?? "?"}`;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : selectedGitScope;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
|
||||
const collapseScopeKey = routeThreadRef
|
||||
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
|
||||
: null;
|
||||
@@ -324,12 +324,12 @@ export default function DiffPanel({
|
||||
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
|
||||
},
|
||||
{ enabled: isGitRepo && selectedTurn !== undefined },
|
||||
);
|
||||
const primaryBranchDiffPreview = useEnvironmentQuery(
|
||||
selectedTurnId === null && activeThread && activeCwd
|
||||
selectedRunId === null && activeThread && activeCwd
|
||||
? reviewEnvironment.diffPreview({
|
||||
environmentId: activeThread.environmentId,
|
||||
input: {
|
||||
@@ -341,7 +341,7 @@ export default function DiffPanel({
|
||||
: null,
|
||||
);
|
||||
const shouldRetryBranchDiffAtEnvironmentCwd =
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
|
||||
serverConfig?.cwd !== undefined &&
|
||||
serverConfig.cwd !== activeCwd;
|
||||
@@ -364,7 +364,7 @@ export default function DiffPanel({
|
||||
(source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
|
||||
);
|
||||
const localBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -381,7 +381,7 @@ export default function DiffPanel({
|
||||
: null,
|
||||
);
|
||||
const remoteBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -424,9 +424,9 @@ export default function DiffPanel({
|
||||
const renderablePatch = useMemo(
|
||||
() =>
|
||||
getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
|
||||
compactPartialHunkOffsets: selectedTurnId === null,
|
||||
compactPartialHunkOffsets: selectedRunId === null,
|
||||
}),
|
||||
[resolvedTheme, selectedPatch, selectedTurnId],
|
||||
[resolvedTheme, selectedPatch, selectedRunId],
|
||||
);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -505,21 +505,9 @@ export default function DiffPanel({
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
|
||||
return {
|
||||
scopeKey: collapseScopeKey,
|
||||
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
|
||||
};
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
const selectTurn = (runId: RunId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
|
||||
};
|
||||
const selectGitScope = (scope: "branch" | "unstaged") => {
|
||||
if (!routeThreadRef) return;
|
||||
@@ -551,6 +539,15 @@ export default function DiffPanel({
|
||||
onClick={() => selectGitScope("unstaged")}
|
||||
>
|
||||
<span>Working tree</span>
|
||||
{selectedRunId === null && selectedGitScope === "unstaged" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => selectGitScope("branch")}>
|
||||
<span>Branch changes</span>
|
||||
{selectedRunId === null && selectedGitScope === "branch" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className={
|
||||
@@ -569,10 +566,13 @@ export default function DiffPanel({
|
||||
: undefined
|
||||
}
|
||||
onClick={() => {
|
||||
if (latestTurn) selectTurn(latestTurn.turnId);
|
||||
if (latestTurn) selectTurn(latestTurn.runId);
|
||||
}}
|
||||
>
|
||||
<span>Latest turn</span>
|
||||
{selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
|
||||
@@ -580,20 +580,15 @@ export default function DiffPanel({
|
||||
{orderedTurnDiffSummaries.map((summary) => {
|
||||
const turnCount =
|
||||
summary.checkpointTurnCount ??
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
inferredCheckpointTurnCountByRunId[summary.runId] ??
|
||||
"?";
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={summary.turnId}
|
||||
className={
|
||||
summary.turnId === selectedTurn?.turnId ? "bg-foreground/[0.08]" : undefined
|
||||
}
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
>
|
||||
<DropdownMenuItem key={summary.runId} onClick={() => selectTurn(summary.runId)}>
|
||||
<span>Turn {turnCount}</span>
|
||||
<span className="ml-auto text-xs tabular-nums text-muted-foreground">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
{summary.runId === selectedTurn?.runId && <CheckIcon className="ml-1" />}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
@@ -601,7 +596,7 @@ export default function DiffPanel({
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{selectedTurnId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
|
||||
{selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
|
||||
<div
|
||||
className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
|
||||
title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
|
||||
@@ -823,7 +818,7 @@ export default function DiffPanel({
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : selectedTurnId !== null && orderedTurnDiffSummaries.length === 0 ? (
|
||||
) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
</div>
|
||||
|
||||
@@ -31,20 +31,14 @@ import {
|
||||
sortScopedProjectsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
@@ -239,13 +233,13 @@ describe("resolveSidebarStageBadgeLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function makeLatestTurn(overrides?: {
|
||||
function makeLatestRun(overrides?: {
|
||||
completedAt?: string | null;
|
||||
startedAt?: string | null;
|
||||
}): OrchestrationLatestTurn {
|
||||
}): NonNullable<Thread["latestRun"]> {
|
||||
return {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
runId: "turn-1" as never,
|
||||
status: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt:
|
||||
@@ -263,9 +257,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -277,9 +271,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: undefined,
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -879,15 +873,13 @@ describe("resolveThreadStatusPill", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "plan" as const,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
lastVisitedAt: undefined,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtime: {
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
activeRunId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
},
|
||||
@@ -930,11 +922,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
hasActionableProposedPlan: true,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -946,11 +938,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -963,12 +955,12 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -1120,7 +1112,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
@@ -1132,7 +1124,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
@@ -1141,13 +1133,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
@@ -1231,7 +1221,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -1247,7 +1237,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import type { ThreadRouteTarget } from "../threadRoutes";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
import { isLatestRunSettled } from "../session-logic";
|
||||
import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
@@ -141,8 +141,8 @@ type ThreadStatusInput = Pick<
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "interactionMode"
|
||||
| "latestTurn"
|
||||
| "session"
|
||||
| "latestRun"
|
||||
| "runtime"
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
};
|
||||
@@ -240,8 +240,8 @@ export function useThreadJumpHintVisibility(): {
|
||||
}
|
||||
|
||||
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
if (!thread.latestRun?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestRun.completedAt);
|
||||
if (Number.isNaN(completedAt)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
|
||||
@@ -594,7 +594,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
|
||||
return {
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -603,7 +603,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (thread.runtime?.status === "starting" || thread.runtime?.status === "queued") {
|
||||
return {
|
||||
label: "Connecting",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -615,7 +615,7 @@ export function resolveThreadStatusPill(input: {
|
||||
const hasPlanReadyPrompt =
|
||||
!thread.hasPendingUserInput &&
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
isLatestRunSettled(thread.latestRun, thread.runtime) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
@@ -442,7 +442,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
[discoveredPorts, navigateToThread, openPreview, threadRef],
|
||||
);
|
||||
const isThreadRunning =
|
||||
thread.session?.status === "running" && thread.session.activeTurnId != null;
|
||||
thread.runtime?.status === "running" && thread.runtime.activeRunId != null;
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -1777,8 +1777,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
);
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const { threadKey, thread } of selectedThreadEntries) {
|
||||
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestRun?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
return;
|
||||
@@ -2155,7 +2156,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
|
||||
markThreadUnread(threadKey, thread.latestRun?.completedAt);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TurnId } from "@t3tools/contracts";
|
||||
import { RunId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
@@ -142,7 +142,7 @@ describe("ChangedFilesTree", () => {
|
||||
({ files, visibleLabels, hiddenLabels }) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesTree
|
||||
turnId={TurnId.make("turn-1")}
|
||||
runId={RunId.make("turn-1")}
|
||||
files={files}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
@@ -218,7 +218,7 @@ describe("ChangedFilesTree", () => {
|
||||
({ files, visibleLabels }) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesTree
|
||||
turnId={TurnId.make("turn-1")}
|
||||
runId={RunId.make("turn-1")}
|
||||
files={files}
|
||||
allDirectoriesExpanded
|
||||
resolvedTheme="light"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type TurnId } from "@t3tools/contracts";
|
||||
import { type RunId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useMemo, useState } from "react";
|
||||
import { type TurnDiffFileChange } from "../../types";
|
||||
import {
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
expanded: boolean;
|
||||
showCompactPreview: boolean;
|
||||
@@ -36,10 +36,10 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
resolvedTheme: "light" | "dark";
|
||||
onExpandedChange: (expanded: boolean) => void;
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
runId,
|
||||
files,
|
||||
expanded,
|
||||
showCompactPreview,
|
||||
@@ -100,57 +100,29 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
</span>
|
||||
</button>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{expanded ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={
|
||||
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
|
||||
}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
aria-label="Open diff"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{expanded ? (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
key={`changed-files-tree:${runId}`}
|
||||
runId={runId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
@@ -202,13 +174,13 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
});
|
||||
|
||||
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const directoryPathsKey = useMemo(
|
||||
() => collectDirectoryPaths(treeNodes).join("\u0000"),
|
||||
@@ -293,7 +265,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
onClick={() => onOpenTurnDiff(runId, node.path)}
|
||||
>
|
||||
{hasDirectoryNodes || depth > 0 ? (
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
PreviewAnnotationPayload,
|
||||
@@ -10,7 +9,8 @@ import type {
|
||||
ScopedThreadRef,
|
||||
ServerProvider,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
RunId,
|
||||
RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
@@ -548,13 +548,13 @@ export interface ChatComposerProps {
|
||||
activePendingIsResponding: boolean;
|
||||
activePendingDraftAnswers: Record<string, PendingUserInputDraftAnswer>;
|
||||
activePendingQuestionIndex: number;
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
respondingRequestIds: RuntimeRequestId[];
|
||||
|
||||
// Plan
|
||||
showPlanFollowUpPrompt: boolean;
|
||||
activeProposedPlan: Thread["proposedPlans"][number] | null;
|
||||
activePlan: { turnId?: TurnId } | null;
|
||||
sidebarProposedPlan: { turnId?: TurnId } | null;
|
||||
activePlan: { runId?: RunId | null } | null;
|
||||
sidebarProposedPlan: { runId?: RunId | null } | null;
|
||||
planSidebarLabel: string;
|
||||
planSidebarOpen: boolean;
|
||||
|
||||
@@ -569,7 +569,7 @@ export interface ChatComposerProps {
|
||||
activeThreadModelSelection: ModelSelection | null | undefined;
|
||||
|
||||
// Context window
|
||||
activeThreadActivities: Thread["activities"] | undefined;
|
||||
activeThreadWorkEntries: Thread["workEntries"] | undefined;
|
||||
|
||||
// Misc
|
||||
resolvedTheme: "light" | "dark";
|
||||
@@ -585,12 +585,16 @@ export interface ChatComposerProps {
|
||||
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
|
||||
composerRef: React.RefObject<ChatComposerHandle | null>;
|
||||
|
||||
// Scroll
|
||||
shouldAutoScrollRef: React.RefObject<boolean>;
|
||||
scheduleStickToBottom: () => void;
|
||||
|
||||
// Callbacks
|
||||
onSend: (e?: { preventDefault: () => void }) => void;
|
||||
onInterrupt: () => void;
|
||||
onImplementPlanInNewThread: () => void;
|
||||
onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
onSelectActivePendingUserInputOption: (questionId: string, optionLabel: string) => void;
|
||||
@@ -662,7 +666,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
providerStatuses,
|
||||
activeProjectDefaultModelSelection,
|
||||
activeThreadModelSelection,
|
||||
activeThreadActivities,
|
||||
activeThreadWorkEntries,
|
||||
resolvedTheme,
|
||||
settings,
|
||||
keybindings,
|
||||
@@ -673,6 +677,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
composerElementContextsRef,
|
||||
shouldAutoScrollRef,
|
||||
scheduleStickToBottom,
|
||||
onSend,
|
||||
onInterrupt,
|
||||
onImplementPlanInNewThread,
|
||||
@@ -754,7 +760,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.runtime?.providerInstanceId ??
|
||||
activeThreadModelSelection?.instanceId ??
|
||||
activeProjectDefaultModelSelection?.instanceId ??
|
||||
null;
|
||||
@@ -772,7 +778,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const lockedContinuationGroupKey = useMemo((): string | null => {
|
||||
if (!lockedProvider || !activeThread) return null;
|
||||
const lockedInstanceId =
|
||||
activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
|
||||
activeThread.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
|
||||
if (!lockedInstanceId) return null;
|
||||
return (
|
||||
providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId)
|
||||
@@ -798,7 +804,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
|
||||
const candidates: Array<string | null | undefined> = [
|
||||
composerDraft.activeProvider,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThread?.runtime?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
];
|
||||
@@ -835,7 +841,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
}, [
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThread?.runtime?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
composerDraft.activeProvider,
|
||||
lockedContinuationGroupKey,
|
||||
@@ -939,8 +945,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// Context window
|
||||
// ------------------------------------------------------------------
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
|
||||
[activeThreadActivities],
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []),
|
||||
[activeThreadWorkEntries],
|
||||
);
|
||||
const activeThreadProviderDisplayName = useMemo(() => {
|
||||
if (!activeThreadModelSelection) return null;
|
||||
@@ -987,6 +993,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -1441,12 +1448,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
};
|
||||
};
|
||||
|
||||
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
|
||||
const initialCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact);
|
||||
setIsComposerFooterCompact(initialCompactness.footerCompact);
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const [entry] = entries;
|
||||
if (!entry) return;
|
||||
const nextCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact((previous) =>
|
||||
previous === nextCompactness.primaryActionsCompact
|
||||
@@ -1456,13 +1466,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setIsComposerFooterCompact((previous) =>
|
||||
previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact,
|
||||
);
|
||||
const nextHeight = entry.contentRect.height;
|
||||
const previousHeight = composerFormHeightRef.current;
|
||||
composerFormHeightRef.current = nextHeight;
|
||||
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
});
|
||||
|
||||
observer.observe(composerForm);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
|
||||
}, [
|
||||
activeThreadId,
|
||||
composerFooterActionLayoutKey,
|
||||
composerFooterHasWideActions,
|
||||
scheduleStickToBottom,
|
||||
shouldAutoScrollRef,
|
||||
]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Image persist effect
|
||||
@@ -2752,6 +2774,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
canRespond={activePendingApproval.responseCapability === "live"}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
/>
|
||||
</div>
|
||||
@@ -3108,6 +3131,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
canRespond={activePendingApproval.responseCapability === "live"}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { type ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { type RuntimeRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
interface ComposerPendingApprovalActionsProps {
|
||||
requestId: ApprovalRequestId;
|
||||
requestId: RuntimeRequestId;
|
||||
isResponding: boolean;
|
||||
canRespond: boolean;
|
||||
onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
@@ -14,6 +15,7 @@ interface ComposerPendingApprovalActionsProps {
|
||||
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
|
||||
requestId,
|
||||
isResponding,
|
||||
canRespond,
|
||||
onRespondToApproval,
|
||||
}: ComposerPendingApprovalActionsProps) {
|
||||
return (
|
||||
@@ -21,7 +23,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "cancel")}
|
||||
>
|
||||
Cancel turn
|
||||
@@ -29,7 +31,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "decline")}
|
||||
>
|
||||
Decline
|
||||
@@ -37,7 +39,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "acceptForSession")}
|
||||
>
|
||||
Always allow this session
|
||||
@@ -45,7 +47,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "accept")}
|
||||
>
|
||||
Approve once
|
||||
|
||||
@@ -32,17 +32,11 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
|
||||
<span className="text-xs text-muted-foreground">1/{pendingCount}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{approval.detail ? (
|
||||
<div className="mt-3 rounded-lg border border-border/65 bg-background/70 p-3">
|
||||
<p className="text-xs font-medium text-muted-foreground">{detailLabel}</p>
|
||||
<pre
|
||||
aria-label={detailLabel}
|
||||
className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-foreground"
|
||||
data-approval-detail="complete"
|
||||
>
|
||||
{approval.detail}
|
||||
</pre>
|
||||
</div>
|
||||
{approval.responseCapability === "not_resumable" ? (
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
This request belonged to a provider process that is no longer available. Interrupt or
|
||||
restart the run to continue.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
import { type PendingUserInput } from "../../session-logic";
|
||||
import {
|
||||
@@ -10,7 +10,7 @@ import { cn } from "~/lib/utils";
|
||||
|
||||
interface PendingUserInputPanelProps {
|
||||
pendingUserInputs: PendingUserInput[];
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
respondingRequestIds: RuntimeRequestId[];
|
||||
answers: Record<string, PendingUserInputDraftAnswer>;
|
||||
questionIndex: number;
|
||||
onToggleOption: (questionId: string, optionLabel: string) => void;
|
||||
@@ -59,6 +59,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
}) {
|
||||
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
|
||||
const activeQuestion = progress.activeQuestion;
|
||||
const canRespond = prompt.responseCapability === "live";
|
||||
const responseDisabled = isResponding || !canRespond;
|
||||
const autoAdvanceTimerRef = useRef<number | null>(null);
|
||||
const onAdvanceRef = useRef(onAdvance);
|
||||
const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
|
||||
@@ -120,7 +122,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
// outside editable fields. Multi-select prompts toggle options in place; single-
|
||||
// select prompts keep the existing auto-advance behavior.
|
||||
useEffect(() => {
|
||||
if (!activeQuestion || isResponding) return;
|
||||
if (!activeQuestion || responseDisabled) return;
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target;
|
||||
@@ -144,7 +146,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
};
|
||||
document.addEventListener("keydown", handler);
|
||||
return () => document.removeEventListener("keydown", handler);
|
||||
}, [activeQuestion, isResponding]);
|
||||
}, [activeQuestion, responseDisabled]);
|
||||
|
||||
if (!activeQuestion) {
|
||||
return null;
|
||||
@@ -165,6 +167,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
|
||||
{!canRespond ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
This request belonged to a provider process that is no longer available. Interrupt or
|
||||
restart the run to continue.
|
||||
</p>
|
||||
) : null}
|
||||
{activeQuestion.multiSelect ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
|
||||
) : null}
|
||||
@@ -182,8 +190,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
isSelected
|
||||
? "border-primary/30 bg-primary/8 text-foreground"
|
||||
: "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
|
||||
isResponding && "opacity-50 cursor-not-allowed",
|
||||
!isResponding && "cursor-pointer",
|
||||
responseDisabled && "opacity-50 cursor-not-allowed",
|
||||
!responseDisabled && "cursor-pointer",
|
||||
);
|
||||
const content = (
|
||||
<>
|
||||
@@ -211,8 +219,10 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
<button
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={isResponding}
|
||||
disabled={responseDisabled}
|
||||
aria-disabled={responseDisabled}
|
||||
onClick={() => {
|
||||
if (responseDisabled) return;
|
||||
handleOptionSelection(activeQuestion.id, option.label);
|
||||
}}
|
||||
className={className}
|
||||
|
||||
@@ -272,7 +272,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Write a poem",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -286,7 +286,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "I should ground this first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -300,14 +300,14 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Here is the poem.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -335,7 +335,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-one" as never,
|
||||
role: "assistant",
|
||||
text: "Earlier response.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -349,16 +349,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-two" as never,
|
||||
role: "assistant",
|
||||
text: "Active response.",
|
||||
turnId: "turn-2" as never,
|
||||
runId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-2" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:19Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -379,7 +379,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
assistantMessageId: "assistant-1" as never,
|
||||
checkpointTurnCount: 2,
|
||||
@@ -398,7 +398,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Do the thing",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -412,7 +412,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-1" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
@@ -450,7 +450,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "Build it",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -464,7 +464,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Looking around first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
updatedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
@@ -477,7 +477,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -490,7 +490,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
@@ -510,7 +510,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
(row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.runId).toBe("turn-1");
|
||||
expect(foldRow?.expanded).toBe(false);
|
||||
// User message boundary (00:00:00) → terminal message updatedAt (00:00:22).
|
||||
expect(foldRow?.label).toBe("Worked for 22s");
|
||||
@@ -522,7 +522,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -556,7 +556,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "do it once more",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -570,7 +570,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-commentary" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Kicking off call 1.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:09Z",
|
||||
updatedAt: "2026-01-01T00:00:09Z",
|
||||
streaming: false,
|
||||
@@ -583,7 +583,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -596,7 +596,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "actually do 15",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:14Z",
|
||||
updatedAt: "2026-01-01T00:00:14Z",
|
||||
streaming: false,
|
||||
@@ -610,16 +610,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-next" as never,
|
||||
role: "assistant" as const,
|
||||
text: "One down — adjusting.",
|
||||
turnId: "turn-2" as never,
|
||||
runId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:17Z",
|
||||
updatedAt: "2026-01-01T00:00:17Z",
|
||||
streaming: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-2" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:14Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -634,7 +634,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
// User message (00:00:00) → trailing work entry (00:00:12).
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.runId).toBe("turn-1");
|
||||
expect(foldRow?.label).toBe("Worked for 12s");
|
||||
});
|
||||
|
||||
@@ -648,15 +648,15 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "interrupted",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "interrupted",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:47Z",
|
||||
},
|
||||
@@ -669,15 +669,88 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "turn-fold",
|
||||
turnId: "turn-1",
|
||||
runId: "turn-1",
|
||||
label: "You stopped after 47s",
|
||||
expanded: false,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps interruption request, intervening work, and result visible in order", () => {
|
||||
const runId = "turn-1" as never;
|
||||
const interruptEvent = (type: "run_interrupt_request" | "run_interrupt_result") => ({
|
||||
position: type === "run_interrupt_request" ? 0 : 2,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: "thread-1" as never,
|
||||
sourceItemId: `item-${type}` as never,
|
||||
item: {
|
||||
id: `item-${type}`,
|
||||
threadId: "thread-1",
|
||||
runId,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: type === "run_interrupt_request" ? 0 : 2,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type,
|
||||
message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
|
||||
},
|
||||
});
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "interrupt-request",
|
||||
kind: "event",
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
projectedItem: interruptEvent("run_interrupt_request") as never,
|
||||
},
|
||||
{
|
||||
id: "work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
runId,
|
||||
label: "Finishing tool output",
|
||||
tone: "tool",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "interrupt-result",
|
||||
kind: "event",
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
projectedItem: interruptEvent("run_interrupt_result") as never,
|
||||
},
|
||||
],
|
||||
latestRun: {
|
||||
runId,
|
||||
status: "interrupted",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:03Z",
|
||||
},
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"interrupt-request",
|
||||
"work-entry",
|
||||
"interrupt-result",
|
||||
]);
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
|
||||
// Right after send, isWorking is true but latestTurn still points at the
|
||||
// Right after send, isWorking is true but latestRun still points at the
|
||||
// previous, settled turn — it must stay folded through that window.
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
@@ -688,7 +761,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -701,7 +774,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
@@ -715,16 +788,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-followup" as never,
|
||||
role: "user",
|
||||
text: "yooo",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
updatedAt: "2026-01-01T00:01:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "completed",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:22Z",
|
||||
},
|
||||
@@ -755,7 +828,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
updatedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
@@ -768,15 +841,15 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -866,7 +939,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Checking first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -880,14 +953,14 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -913,16 +986,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -1019,7 +1092,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -1028,7 +1101,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
@@ -1124,7 +1197,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -1133,7 +1206,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -7,7 +7,12 @@ import {
|
||||
type WorkLogEntry,
|
||||
} from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
type MessageId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
|
||||
@@ -128,9 +133,9 @@ export interface TimelineDurationMessage {
|
||||
streaming: boolean;
|
||||
}
|
||||
|
||||
export type TimelineLatestTurn = Pick<
|
||||
OrchestrationLatestTurn,
|
||||
"turnId" | "state" | "startedAt" | "completedAt"
|
||||
export type TimelineLatestRun = Pick<
|
||||
ThreadRunSummary,
|
||||
"runId" | "status" | "startedAt" | "completedAt"
|
||||
>;
|
||||
|
||||
export type MessagesTimelineRow =
|
||||
@@ -153,7 +158,7 @@ export type MessagesTimelineRow =
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
}
|
||||
@@ -169,6 +174,12 @@ export type MessagesTimelineRow =
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
kind: "event";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
id: string;
|
||||
@@ -238,8 +249,8 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
continue;
|
||||
}
|
||||
|
||||
const responseKey = message.turnId
|
||||
? `turn:${message.turnId}`
|
||||
const responseKey = message.runId
|
||||
? `turn:${message.runId}`
|
||||
: `unkeyed:${nullTurnResponseIndex}`;
|
||||
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
|
||||
}
|
||||
@@ -248,7 +259,7 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
}
|
||||
|
||||
interface TurnFold {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
anchorEntryId: string;
|
||||
createdAt: string;
|
||||
hiddenEntryIds: ReadonlySet<string>;
|
||||
@@ -263,18 +274,16 @@ interface TurnFold {
|
||||
* user sends a message, the previous turn is still the "active" one until the
|
||||
* server creates the new turn, and folding must not flicker through that window.
|
||||
*/
|
||||
function deriveUnsettledTurnId(
|
||||
latestTurn: TimelineLatestTurn | null,
|
||||
runningTurnId: TurnId | null,
|
||||
): TurnId | null {
|
||||
if (runningTurnId !== null) {
|
||||
return runningTurnId;
|
||||
}
|
||||
if (!latestTurn) {
|
||||
function deriveUnsettledRunId(latestRun: TimelineLatestRun | null): RunId | null {
|
||||
if (!latestRun) {
|
||||
return null;
|
||||
}
|
||||
const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
|
||||
return isSettled ? null : latestTurn.turnId;
|
||||
const isSettled =
|
||||
latestRun.completedAt !== null &&
|
||||
latestRun.status !== "running" &&
|
||||
latestRun.status !== "starting" &&
|
||||
latestRun.status !== "waiting";
|
||||
return isSettled ? null : latestRun.runId;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -285,9 +294,21 @@ function deriveUnsettledTurnId(
|
||||
function deriveTurnFolds(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
unsettledTurnId: TurnId | null;
|
||||
latestRun: TimelineLatestRun | null;
|
||||
unsettledRunId: RunId | null;
|
||||
}): ReadonlyMap<string, TurnFold> {
|
||||
const interruptedRunIds = new Set<RunId>();
|
||||
for (const entry of input.timelineEntries) {
|
||||
if (
|
||||
entry.kind === "event" &&
|
||||
entry.projectedItem.item.runId !== null &&
|
||||
(entry.projectedItem.item.type === "run_interrupt_request" ||
|
||||
entry.projectedItem.item.type === "run_interrupt_result")
|
||||
) {
|
||||
interruptedRunIds.add(entry.projectedItem.item.runId);
|
||||
}
|
||||
}
|
||||
|
||||
interface TurnGroup {
|
||||
entries: Array<TimelineEntry>;
|
||||
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
|
||||
@@ -300,7 +321,7 @@ function deriveTurnFolds(input: {
|
||||
*/
|
||||
startBoundary: string | null;
|
||||
}
|
||||
const groupsByTurnId = new Map<TurnId, TurnGroup>();
|
||||
const groupsByRunId = new Map<RunId, TurnGroup>();
|
||||
|
||||
let pendingUserBoundary: string | null = null;
|
||||
for (const entry of input.timelineEntries) {
|
||||
@@ -308,16 +329,16 @@ function deriveTurnFolds(input: {
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
const turnId =
|
||||
const runId =
|
||||
entry.kind === "message" && entry.message.role === "assistant"
|
||||
? (entry.message.turnId ?? null)
|
||||
? (entry.message.runId ?? null)
|
||||
: entry.kind === "work"
|
||||
? (entry.entry.turnId ?? null)
|
||||
? (entry.entry.runId ?? null)
|
||||
: null;
|
||||
if (!turnId) {
|
||||
if (!runId) {
|
||||
continue;
|
||||
}
|
||||
let group = groupsByTurnId.get(turnId);
|
||||
let group = groupsByRunId.get(runId);
|
||||
if (!group) {
|
||||
group = {
|
||||
entries: [],
|
||||
@@ -329,7 +350,7 @@ function deriveTurnFolds(input: {
|
||||
startBoundary: pendingUserBoundary,
|
||||
};
|
||||
pendingUserBoundary = null;
|
||||
groupsByTurnId.set(turnId, group);
|
||||
groupsByRunId.set(runId, group);
|
||||
}
|
||||
group.entries.push(entry);
|
||||
if (entry.kind === "message") {
|
||||
@@ -343,8 +364,8 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
|
||||
const foldsByAnchorEntryId = new Map<string, TurnFold>();
|
||||
for (const [turnId, group] of groupsByTurnId) {
|
||||
if (turnId === input.unsettledTurnId) {
|
||||
for (const [runId, group] of groupsByRunId) {
|
||||
if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) {
|
||||
continue;
|
||||
}
|
||||
if (group.hasStreamingMessage) {
|
||||
@@ -367,16 +388,14 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
|
||||
const isLatestInterruptedTurn =
|
||||
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
|
||||
input.latestRun?.runId === runId && input.latestRun.status === "interrupted";
|
||||
// A turn cut short by a steer leaves trailing work entries behind its
|
||||
// terminal message — take whichever ended last.
|
||||
const lastEntryEnd =
|
||||
lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
|
||||
const elapsedMs =
|
||||
input.latestTurn?.turnId === turnId &&
|
||||
input.latestTurn.startedAt &&
|
||||
input.latestTurn.completedAt
|
||||
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
|
||||
input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt
|
||||
? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt)
|
||||
: computeElapsedMs(
|
||||
group.startBoundary ?? firstEntry.createdAt,
|
||||
maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
|
||||
@@ -392,7 +411,7 @@ function deriveTurnFolds(input: {
|
||||
: "Worked";
|
||||
|
||||
foldsByAnchorEntryId.set(firstEntry.id, {
|
||||
turnId,
|
||||
runId,
|
||||
anchorEntryId: firstEntry.id,
|
||||
createdAt: firstEntry.createdAt,
|
||||
hiddenEntryIds,
|
||||
@@ -404,10 +423,8 @@ function deriveTurnFolds(input: {
|
||||
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
latestTurn?: TimelineLatestTurn | null;
|
||||
runningTurnId?: TurnId | null;
|
||||
expandedTurnIds?: ReadonlySet<TurnId>;
|
||||
expandedWorkGroupIds?: ReadonlySet<string>;
|
||||
latestRun?: TimelineLatestRun | null;
|
||||
expandedRunIds?: ReadonlySet<RunId>;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
@@ -418,19 +435,16 @@ export function deriveMessagesTimelineRows(input: {
|
||||
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
|
||||
const unsettledTurnId = deriveUnsettledTurnId(
|
||||
input.latestTurn ?? null,
|
||||
input.runningTurnId ?? null,
|
||||
);
|
||||
const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null);
|
||||
const foldsByAnchorEntryId = deriveTurnFolds({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
unsettledTurnId,
|
||||
latestRun: input.latestRun ?? null,
|
||||
unsettledRunId,
|
||||
});
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
for (const fold of foldsByAnchorEntryId.values()) {
|
||||
if (!input.expandedTurnIds?.has(fold.turnId)) {
|
||||
if (!input.expandedRunIds?.has(fold.runId)) {
|
||||
for (const entryId of fold.hiddenEntryIds) {
|
||||
collapsedEntryIds.add(entryId);
|
||||
}
|
||||
@@ -447,11 +461,11 @@ export function deriveMessagesTimelineRows(input: {
|
||||
if (turnFold) {
|
||||
nextRows.push({
|
||||
kind: "turn-fold",
|
||||
id: `turn-fold:${turnFold.turnId}`,
|
||||
id: `turn-fold:${turnFold.runId}`,
|
||||
createdAt: turnFold.createdAt,
|
||||
turnId: turnFold.turnId,
|
||||
runId: turnFold.runId,
|
||||
label: turnFold.label,
|
||||
expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
|
||||
expanded: input.expandedRunIds?.has(turnFold.runId) ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -527,10 +541,20 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "event") {
|
||||
nextRows.push({
|
||||
kind: "event",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
projectedItem: timelineEntry.projectedItem,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const assistantTurnStillInProgress =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
unsettledTurnId !== null &&
|
||||
timelineEntry.message.turnId === unsettledTurnId;
|
||||
unsettledRunId !== null &&
|
||||
timelineEntry.message.runId === unsettledRunId;
|
||||
|
||||
const durationStart =
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
|
||||
@@ -610,6 +634,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "event":
|
||||
return a.projectedItem === (b as typeof a).projectedItem;
|
||||
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
|
||||
@@ -176,8 +176,7 @@ function buildProps() {
|
||||
activeTurnInProgress: false,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
latestTurn: null,
|
||||
runningTurnId: null,
|
||||
latestRun: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: () => {},
|
||||
@@ -214,7 +213,7 @@ function buildUserTimelineEntry(text: string) {
|
||||
id: MessageId.make("message-1"),
|
||||
role: "user" as const,
|
||||
text,
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
updatedAt: MESSAGE_CREATED_AT,
|
||||
streaming: false,
|
||||
@@ -527,7 +526,116 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Work Log");
|
||||
});
|
||||
|
||||
it("formats changed file paths from the workspace root", () => {
|
||||
it("renders V2 interruption lifecycle entries as standalone rows", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "interrupt-request",
|
||||
kind: "event",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
projectedItem: {
|
||||
position: 0,
|
||||
visibility: "local",
|
||||
sourceThreadId: "thread-1",
|
||||
sourceItemId: "interrupt-request",
|
||||
item: {
|
||||
id: "interrupt-request",
|
||||
threadId: "thread-1",
|
||||
runId: "run-1",
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type: "run_interrupt_request",
|
||||
message: "Waiting for the provider to stop.",
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-v2-item-type="run_interrupt_request"');
|
||||
expect(markup).toContain("Interrupt requested");
|
||||
expect(markup).toContain("Waiting for the provider to stop.");
|
||||
expect(markup).toContain('data-v2-structured-details="true"');
|
||||
expect(markup).toContain("Structured details");
|
||||
expect(markup).toContain(""type": "run_interrupt_request"");
|
||||
});
|
||||
|
||||
it("keeps inherited V2 work provenance on the rendered row", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const item = {
|
||||
id: "command-inherited",
|
||||
threadId: "thread-source",
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type: "command_execution",
|
||||
input: "pwd",
|
||||
output: "/workspace",
|
||||
exitCode: 0,
|
||||
} as const;
|
||||
const projectedItem = {
|
||||
position: 0,
|
||||
visibility: "inherited",
|
||||
sourceThreadId: "thread-source",
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
} as const;
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={
|
||||
[
|
||||
{
|
||||
id: item.id,
|
||||
kind: "work",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
entry: {
|
||||
id: item.id,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
runId: null,
|
||||
label: "Ran command",
|
||||
command: item.input,
|
||||
tone: "tool",
|
||||
itemType: item.type,
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload: item,
|
||||
projectedItem,
|
||||
},
|
||||
},
|
||||
] as never
|
||||
}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-v2-item-type="command_execution"');
|
||||
expect(markup).toContain('data-v2-item-visibility="inherited"');
|
||||
expect(markup).toContain("Inherited");
|
||||
});
|
||||
|
||||
it("formats changed file paths from the workspace root", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
@@ -541,6 +649,8 @@ describe("MessagesTimeline", () => {
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Updated files",
|
||||
tone: "tool",
|
||||
itemType: "file_change",
|
||||
toolLifecycleStatus: "completed",
|
||||
changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
|
||||
},
|
||||
},
|
||||
@@ -575,7 +685,7 @@ describe("MessagesTimeline", () => {
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
updatedAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
@@ -614,7 +724,7 @@ describe("MessagesTimeline", () => {
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
updatedAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type OrchestrationV2TurnItem,
|
||||
type ScopedThreadRef,
|
||||
type ServerProviderSkill,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
@@ -78,8 +79,7 @@ import {
|
||||
resolveTimelineMinimapTopPercent,
|
||||
type StableMessagesTimelineRowsState,
|
||||
type MessagesTimelineRow,
|
||||
TIMELINE_MINIMAP_MIN_ITEMS,
|
||||
type TimelineLatestTurn,
|
||||
type TimelineLatestRun,
|
||||
} from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -132,9 +132,8 @@ interface TimelineRowSharedState {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onToggleTurnFold: (turnId: TurnId) => void;
|
||||
onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
onToggleTurnFold: (runId: RunId) => void;
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
@@ -161,11 +160,10 @@ interface MessagesTimelineProps {
|
||||
activeTurnStartedAt: string | null;
|
||||
listRef: React.RefObject<LegendListRef | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
runningTurnId: TurnId | null;
|
||||
latestRun: TimelineLatestRun | null;
|
||||
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
|
||||
routeThreadKey: string;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
isRevertingCheckpoint: boolean;
|
||||
@@ -196,8 +194,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
activeTurnStartedAt,
|
||||
listRef,
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
latestRun,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
routeThreadKey,
|
||||
onOpenTurnDiff,
|
||||
@@ -220,17 +217,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hideEmptyPlaceholder = false,
|
||||
topFadeEnabled = false,
|
||||
}: MessagesTimelineProps) {
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
|
||||
const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(new Set());
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
setExpandedTurnIds((existing) => {
|
||||
// Toggling a fold inserts/removes rows between the fold row and the final
|
||||
// message — everything above the trigger is unchanged, so the trigger stays
|
||||
// put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
|
||||
// exactly that (pin the bottom content when row data changes while scrolled
|
||||
// to the end), yanking the trigger out of view. Suppress it for the frames
|
||||
// in which the toggle's data change and item measurements settle.
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
setExpandedRunIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -271,41 +274,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
// An in-session interrupt leaves its turn expanded so the user keeps their
|
||||
// place; the next turn (or a reload, since this is local state) folds it.
|
||||
const previousLatestTurnRef = useRef(latestTurn);
|
||||
const previousLatestRunRef = useRef(latestRun);
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = latestTurn;
|
||||
if (!latestTurn || previous?.turnId === undefined) {
|
||||
const previous = previousLatestRunRef.current;
|
||||
previousLatestRunRef.current = latestRun;
|
||||
if (!latestRun || previous?.runId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && latestTurn.state === "interrupted") {
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && latestRun.status === "interrupted") {
|
||||
setExpandedRunIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
next.add(latestTurn.turnId);
|
||||
next.add(latestRun.runId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (!existing.has(previous.turnId)) {
|
||||
setExpandedRunIds((existing) => {
|
||||
if (!existing.has(previous.runId)) {
|
||||
return existing;
|
||||
}
|
||||
const next = new Set(existing);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return next;
|
||||
});
|
||||
}, [latestTurn]);
|
||||
}, [latestRun]);
|
||||
|
||||
const rawRows = useMemo(
|
||||
() =>
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -313,10 +314,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}),
|
||||
[
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -843,7 +842,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
// they sit closer to the work that follows them.
|
||||
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
|
||||
row.kind === "work" ||
|
||||
row.kind === "work-toggle"
|
||||
row.kind === "event"
|
||||
? "pb-2"
|
||||
: "pb-4",
|
||||
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
|
||||
@@ -861,6 +860,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
<AssistantTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
|
||||
{row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
|
||||
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -1005,7 +1005,7 @@ function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-
|
||||
type="button"
|
||||
aria-expanded={row.expanded}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => ctx.onToggleTurnFold(row.turnId)}
|
||||
onClick={() => ctx.onToggleTurnFold(row.runId)}
|
||||
className="flex cursor-pointer select-none items-center gap-1 rounded-md px-1 text-xs text-muted-foreground tabular-nums transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
|
||||
>
|
||||
<span>{row.label}</span>
|
||||
@@ -1091,6 +1091,173 @@ function ProposedPlanTimelineRow({
|
||||
);
|
||||
}
|
||||
|
||||
type V2EventTone = "muted" | "warning" | "danger" | "success";
|
||||
|
||||
function v2EventPresentation(item: OrchestrationV2TurnItem): {
|
||||
readonly label: string;
|
||||
readonly detail: string | null;
|
||||
readonly tone: V2EventTone;
|
||||
readonly icon: typeof CircleAlertIcon;
|
||||
} {
|
||||
switch (item.type) {
|
||||
case "run_interrupt_request":
|
||||
return {
|
||||
label: "Interrupt requested",
|
||||
detail: item.message,
|
||||
tone: "warning",
|
||||
icon: CircleAlertIcon,
|
||||
};
|
||||
case "run_interrupt_result":
|
||||
return {
|
||||
label: "Run interrupted",
|
||||
detail: item.message,
|
||||
tone: "danger",
|
||||
icon: XIcon,
|
||||
};
|
||||
case "handoff":
|
||||
return {
|
||||
label: "Context handoff",
|
||||
detail:
|
||||
item.summary ??
|
||||
`${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`,
|
||||
tone: item.status === "failed" ? "danger" : "muted",
|
||||
icon: ZapIcon,
|
||||
};
|
||||
case "fork":
|
||||
return {
|
||||
label: "Conversation fork",
|
||||
detail: `Continues in ${item.targetThreadId}`,
|
||||
tone: "muted",
|
||||
icon: HammerIcon,
|
||||
};
|
||||
case "compaction": {
|
||||
const tokenSummary =
|
||||
item.beforeTokenCount === undefined && item.afterTokenCount === undefined
|
||||
? null
|
||||
: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`;
|
||||
return {
|
||||
label: "Context compacted",
|
||||
detail: item.summary ?? tokenSummary,
|
||||
tone: item.status === "failed" ? "danger" : "muted",
|
||||
icon: MinusIcon,
|
||||
};
|
||||
}
|
||||
case "subagent":
|
||||
return {
|
||||
label: item.title ?? "Subagent",
|
||||
detail: item.result ?? item.prompt,
|
||||
tone:
|
||||
item.status === "failed" ? "danger" : item.status === "completed" ? "success" : "muted",
|
||||
icon: HammerIcon,
|
||||
};
|
||||
case "approval_request":
|
||||
return {
|
||||
label: "Approval requested",
|
||||
detail: item.prompt ?? item.requestKind,
|
||||
tone: item.status === "failed" ? "danger" : "warning",
|
||||
icon: MessageCircleIcon,
|
||||
};
|
||||
case "user_input_request":
|
||||
return {
|
||||
label: "Input requested",
|
||||
detail: item.questions.map((question) => question.question).join("\n"),
|
||||
tone: item.status === "failed" ? "danger" : "warning",
|
||||
icon: MessageCircleIcon,
|
||||
};
|
||||
case "todo_list": {
|
||||
const steps = item.steps.map((step) => `${step.status}: ${step.text}`).join("\n");
|
||||
return {
|
||||
label: "Plan updated",
|
||||
detail: [item.explanation, steps].filter(Boolean).join("\n\n") || null,
|
||||
tone: item.status === "failed" ? "danger" : "success",
|
||||
icon: CheckIcon,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return {
|
||||
label: item.title?.trim() || item.type.replaceAll("_", " "),
|
||||
detail: null,
|
||||
tone: item.status === "failed" ? "danger" : "muted",
|
||||
icon: WrenchIcon,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const { item, visibility, sourceThreadId } = row.projectedItem;
|
||||
const presentation = v2EventPresentation(item);
|
||||
const Icon = presentation.icon;
|
||||
return (
|
||||
<section
|
||||
className={cn(
|
||||
"rounded-lg border px-3 py-2",
|
||||
presentation.tone === "warning" && "border-amber-500/25 bg-amber-500/5",
|
||||
presentation.tone === "danger" && "border-destructive/25 bg-destructive/5",
|
||||
presentation.tone === "success" && "border-emerald-500/20 bg-emerald-500/5",
|
||||
presentation.tone === "muted" && "border-border/60 bg-card/30",
|
||||
)}
|
||||
data-v2-item-type={item.type}
|
||||
data-v2-item-visibility={visibility}
|
||||
>
|
||||
<div className="flex items-start gap-2.5">
|
||||
<Icon
|
||||
className={cn(
|
||||
"mt-0.5 size-3.5 shrink-0",
|
||||
presentation.tone === "warning" && "text-amber-600 dark:text-amber-400",
|
||||
presentation.tone === "danger" && "text-destructive",
|
||||
presentation.tone === "success" && "text-emerald-600 dark:text-emerald-400",
|
||||
presentation.tone === "muted" && "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="text-xs font-medium text-foreground/90">{presentation.label}</span>
|
||||
{item.status !== "completed" ? (
|
||||
<span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
|
||||
{item.status}
|
||||
</span>
|
||||
) : null}
|
||||
{visibility !== "local" ? (
|
||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||
{visibility === "inherited" ? "Inherited" : "Synthetic"}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{presentation.detail ? (
|
||||
<div className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
<ChatMarkdown
|
||||
text={presentation.detail}
|
||||
cwd={ctx.markdownCwd}
|
||||
threadRef={ctx.threadRef ?? undefined}
|
||||
skills={ctx.skills}
|
||||
lineBreaks
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{visibility === "inherited" ? (
|
||||
<p className="mt-1 font-mono text-[10px] text-muted-foreground/65">
|
||||
From {sourceThreadId}
|
||||
</p>
|
||||
) : null}
|
||||
<details
|
||||
className="group/v2-details mt-2 rounded-md border border-border/50 bg-background/45"
|
||||
data-v2-structured-details="true"
|
||||
>
|
||||
<summary className="flex cursor-pointer list-none items-center gap-1.5 px-2 py-1.5 text-[11px] font-medium text-muted-foreground select-none hover:text-foreground [&::-webkit-details-marker]:hidden">
|
||||
<ChevronRightIcon className="size-3 transition-transform group-open/v2-details:rotate-90" />
|
||||
Structured details
|
||||
</summary>
|
||||
<pre className="max-h-80 overflow-auto border-t border-border/50 px-2 py-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap text-muted-foreground">
|
||||
{JSON.stringify(item, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
|
||||
return (
|
||||
<div className="py-0.5 pl-1.5">
|
||||
@@ -1244,7 +1411,7 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
turnSummary: TurnDiffSummary | undefined;
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
@@ -1274,12 +1441,10 @@ function AssistantChangedFilesSectionInner({
|
||||
checkpointFiles: TurnDiffSummary["files"];
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
|
||||
const persistedExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId] ?? true,
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const [autoExpanded] = useState(() =>
|
||||
@@ -1289,19 +1454,46 @@ function AssistantChangedFilesSectionInner({
|
||||
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
|
||||
|
||||
return (
|
||||
<ChangedFilesCard
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
expanded={expanded}
|
||||
showCompactPreview={isLatestTurn}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onExpandedChange={(nextExpanded) =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
|
||||
}
|
||||
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="sticky top-2 z-10 mb-1.5 flex items-center justify-between gap-2 bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:absolute before:inset-x-0 before:-top-2 before:h-2 before:bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:content-['']">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.runId, checkpointFiles[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.runId}`}
|
||||
runId={turnSummary.runId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1850,8 +2042,8 @@ function buildToolCallExpandedBody(
|
||||
workspaceRoot: string | undefined,
|
||||
): string | null {
|
||||
const blocks: string[] = [];
|
||||
if (workEntry.itemType === "mcp_tool_call" && workEntry.toolData !== undefined) {
|
||||
blocks.push(`MCP call\n${JSON.stringify(workEntry.toolData, null, 2)}`);
|
||||
if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) {
|
||||
blocks.push(`Tool call\n${JSON.stringify(workEntry.toolData, null, 2)}`);
|
||||
}
|
||||
const raw = workEntryRawCommand(workEntry);
|
||||
if (raw?.trim()) {
|
||||
@@ -1870,14 +2062,25 @@ function buildToolCallExpandedBody(
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
if (workEntry.structuredPayload !== undefined) {
|
||||
const structured = JSON.stringify(workEntry.structuredPayload, null, 2);
|
||||
if (structured && !blocks.includes(structured)) {
|
||||
blocks.push(structured);
|
||||
}
|
||||
}
|
||||
if (workEntry.projectedItem?.visibility !== undefined) {
|
||||
const { visibility, sourceThreadId } = workEntry.projectedItem;
|
||||
if (visibility !== "local") {
|
||||
blocks.push(
|
||||
`${visibility === "inherited" ? "Inherited" : "Synthetic"} from ${sourceThreadId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return blocks.length > 0 ? blocks.join("\n\n") : null;
|
||||
}
|
||||
|
||||
function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
if (
|
||||
workEntry.sourceActivityKind === "user-input.requested" ||
|
||||
workEntry.sourceActivityKind === "user-input.resolved"
|
||||
) {
|
||||
if (workEntry.itemType === "user_input_request") {
|
||||
return "message-circle";
|
||||
}
|
||||
if (workEntry.requestKind === "command") return "terminal";
|
||||
@@ -1891,13 +2094,12 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
return "square-pen";
|
||||
}
|
||||
if (workEntry.itemType === "web_search") return "globe";
|
||||
if (workEntry.itemType === "image_view") return "eye";
|
||||
if (workEntry.itemType === "file_search") return "eye";
|
||||
|
||||
switch (workEntry.itemType) {
|
||||
case "mcp_tool_call":
|
||||
case "dynamic_tool":
|
||||
return "wrench";
|
||||
case "dynamic_tool_call":
|
||||
case "collab_agent_tool_call":
|
||||
case "subagent":
|
||||
return "hammer";
|
||||
}
|
||||
|
||||
@@ -1929,7 +2131,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
|
||||
const showWarningIndicator = false;
|
||||
const entryIconName = showWarningIndicator ? "x" : workEntryIconName(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
|
||||
@@ -1943,9 +2145,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot);
|
||||
const canExpand = expandedBody !== null;
|
||||
const showFailedIndicator = workEntryIndicatesToolFailure(workEntry);
|
||||
const showDestructiveRowStyle =
|
||||
showFailedIndicator &&
|
||||
(workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry));
|
||||
const showDestructiveRowStyle = showFailedIndicator && !workLogEntryIsToolLike(workEntry);
|
||||
const iconWrapperClass = cn(
|
||||
"flex size-5 shrink-0 items-center justify-center",
|
||||
showWarningIndicator
|
||||
@@ -1988,6 +2188,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
canExpand &&
|
||||
"cursor-pointer hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
|
||||
)}
|
||||
data-v2-item-type={workEntry.projectedItem?.item.type}
|
||||
data-v2-item-visibility={workEntry.projectedItem?.visibility}
|
||||
{...rowToggleProps}
|
||||
>
|
||||
<div className="flex select-none items-center gap-1.5 transition-[opacity,translate] duration-200">
|
||||
@@ -2001,6 +2203,12 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<p className="flex min-w-0 w-full items-baseline gap-1.5 text-[12px] leading-5">
|
||||
<span className={cn("min-w-0 shrink truncate", headingClass)}>{heading}</span>
|
||||
{workEntry.projectedItem?.visibility !== undefined &&
|
||||
workEntry.projectedItem.visibility !== "local" ? (
|
||||
<span className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[9px] leading-none text-muted-foreground">
|
||||
{workEntry.projectedItem.visibility === "inherited" ? "Inherited" : "Synthetic"}
|
||||
</span>
|
||||
) : null}
|
||||
{preview && (
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground/55">{preview}</span>
|
||||
)}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type SidebarProjectGroupingMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
@@ -2245,10 +2246,7 @@ export function ArchivedThreadsPanel() {
|
||||
),
|
||||
);
|
||||
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
|
||||
snapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
environmentId,
|
||||
})),
|
||||
snapshot.threads.map((thread) => presentThreadShell(environmentId, thread)),
|
||||
);
|
||||
|
||||
const archivedProjects = Array.from(projectsByEnvironmentAndId.values());
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
ConnectionTargetStore,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeCatalogValue,
|
||||
removeConnectionFromCatalog,
|
||||
@@ -17,14 +21,7 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -41,23 +38,9 @@ const THREAD_STORE_NAME = "thread";
|
||||
const SERVER_CONFIG_STORE_NAME = "server-config";
|
||||
const VCS_REFS_STORE_NAME = "vcs-refs";
|
||||
const CATALOG_KEY = "document";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
|
||||
// v2 stores the snapshot sequence alongside the thread so a warm cache can
|
||||
// resume via `afterSequence` instead of re-downloading the full thread body.
|
||||
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(2),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
|
||||
const StoredServerConfig = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
@@ -469,25 +452,24 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-shell", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
@@ -543,33 +525,36 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-thread", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
),
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: 2,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, snapshot.thread.id),
|
||||
threadCacheKey(environmentId, thread.thread.id),
|
||||
encoded,
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "./diffPanelStore";
|
||||
@@ -31,7 +31,7 @@ describe("diffPanelStore", () => {
|
||||
|
||||
it("clears incompatible selection fields when changing scopes", () => {
|
||||
const store = useDiffPanelStore.getState();
|
||||
store.selectTurn(THREAD_REF, TurnId.make("turn-1"), "src/app.ts");
|
||||
store.selectTurn(THREAD_REF, RunId.make("turn-1"), "src/app.ts");
|
||||
store.selectGitScope(THREAD_REF, "unstaged");
|
||||
|
||||
expect(
|
||||
@@ -45,7 +45,7 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("increments the reveal request when opening the same turn file again", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const turnId = RunId.make("turn-1");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
|
||||
@@ -65,8 +65,8 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("reconciles a missing turn selection to the latest available turn", () => {
|
||||
const missingTurnId = TurnId.make("turn-missing");
|
||||
const latestTurnId = TurnId.make("turn-latest");
|
||||
const missingTurnId = RunId.make("turn-missing");
|
||||
const latestTurnId = RunId.make("turn-latest");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, missingTurnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(THREAD_REF, [latestTurnId]);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { RunId, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
@@ -8,7 +8,7 @@ import { resolveStorage } from "./lib/storage";
|
||||
export type DiffPanelSelection =
|
||||
| { kind: "branch"; baseRef: string | null }
|
||||
| { kind: "unstaged" }
|
||||
| { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number };
|
||||
| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };
|
||||
|
||||
const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
|
||||
const DEFAULT_WORKING_TREE_SELECTION: DiffPanelSelection = { kind: "unstaged" };
|
||||
@@ -18,8 +18,8 @@ interface DiffPanelStoreState {
|
||||
branchBaseRefByThreadKey: Record<string, string | null>;
|
||||
selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;
|
||||
selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;
|
||||
selectTurn: (ref: ScopedThreadRef, turnId: TurnId, filePath?: string) => void;
|
||||
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<TurnId>) => void;
|
||||
selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
|
||||
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
|
||||
removeThread: (ref: ScopedThreadRef) => void;
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
|
||||
}),
|
||||
{
|
||||
name: "t3code:diff-panel-state:v1",
|
||||
version: 1,
|
||||
version: 2,
|
||||
storage: createJSONStorage(() =>
|
||||
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
|
||||
),
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "user",
|
||||
text: "hello",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -23,7 +23,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "assistant",
|
||||
text: "world",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -49,7 +49,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "user",
|
||||
text: "first question with details",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -58,7 +58,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "assistant",
|
||||
text: "first answer with details",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -67,7 +67,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "user",
|
||||
text: "second question with details",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -92,7 +92,7 @@ describe("buildBootstrapInput", () => {
|
||||
role: "user",
|
||||
text: "old context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -124,7 +124,7 @@ describe("buildBootstrapInput", () => {
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
|
||||
@@ -160,7 +160,7 @@ export function useThreadActions() {
|
||||
const resolved = resolveThreadTarget(target);
|
||||
if (!resolved) return AsyncResult.success(undefined);
|
||||
const { thread, threadRef } = resolved;
|
||||
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
|
||||
if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadArchiveBlockedError({
|
||||
@@ -277,7 +277,7 @@ export function useThreadActions() {
|
||||
shouldDeleteWorktree = confirmationResult.value;
|
||||
}
|
||||
|
||||
if (thread.session && thread.session.status !== "stopped") {
|
||||
if (thread.runtime !== null) {
|
||||
await stopThreadSession({
|
||||
environmentId: threadRef.environmentId,
|
||||
input: { threadId: threadRef.threadId },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo } from "react";
|
||||
import { inferCheckpointTurnCountByTurnId } from "../session-logic";
|
||||
import { inferCheckpointTurnCountByRunId } from "../session-logic";
|
||||
import type { Thread, TurnDiffSummary } from "../types";
|
||||
|
||||
export function useTurnDiffSummaries(activeThread: Thread | null | undefined) {
|
||||
@@ -10,10 +10,10 @@ export function useTurnDiffSummaries(activeThread: Thread | null | undefined) {
|
||||
return activeThread.checkpoints;
|
||||
}, [activeThread]);
|
||||
|
||||
const inferredCheckpointTurnCountByTurnId = useMemo(
|
||||
() => inferCheckpointTurnCountByTurnId(turnDiffSummaries),
|
||||
const inferredCheckpointTurnCountByRunId = useMemo(
|
||||
() => inferCheckpointTurnCountByRunId(turnDiffSummaries),
|
||||
[turnDiffSummaries],
|
||||
);
|
||||
|
||||
return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId };
|
||||
return { turnDiffSummaries, inferredCheckpointTurnCountByRunId };
|
||||
}
|
||||
@@ -1,84 +1,44 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { EventId, type OrchestrationThreadActivity, TurnId } from "@t3tools/contracts";
|
||||
|
||||
import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow";
|
||||
|
||||
function makeActivity(id: string, kind: string, payload: unknown): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: EventId.make(id),
|
||||
tone: "info",
|
||||
kind,
|
||||
summary: kind,
|
||||
payload,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
createdAt: "2026-03-23T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("contextWindow", () => {
|
||||
it("derives the latest valid context window snapshot", () => {
|
||||
describe("V2 context window presentation", () => {
|
||||
it("uses retained compaction token data when available", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {
|
||||
usedTokens: 1000,
|
||||
}),
|
||||
makeActivity("activity-2", "tool.started", {}),
|
||||
makeActivity("activity-3", "context-window.updated", {
|
||||
usedTokens: 14_000,
|
||||
maxTokens: 258_000,
|
||||
compactsAutomatically: true,
|
||||
}),
|
||||
{
|
||||
id: "compaction-1",
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
runId: null,
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
itemType: "compaction",
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload: {
|
||||
id: "compaction-1" as never,
|
||||
threadId: "thread-1" as never,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 1,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {} as never,
|
||||
type: "compaction",
|
||||
driver: null,
|
||||
beforeTokenCount: 10_000,
|
||||
afterTokenCount: 2_000,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.usedTokens).toBe(14_000);
|
||||
expect(snapshot?.totalProcessedTokens).toBeNull();
|
||||
expect(snapshot?.maxTokens).toBe(258_000);
|
||||
expect(snapshot?.compactsAutomatically).toBe(true);
|
||||
expect(snapshot?.usedTokens).toBe(2_000);
|
||||
expect(snapshot?.totalProcessedTokens).toBe(10_000);
|
||||
});
|
||||
|
||||
it("ignores malformed payloads", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {}),
|
||||
]);
|
||||
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps valid zero-usage snapshots", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {
|
||||
usedTokens: 0,
|
||||
maxTokens: 100_000,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(snapshot).toMatchObject({
|
||||
usedTokens: 0,
|
||||
maxTokens: 100_000,
|
||||
remainingTokens: 100_000,
|
||||
usedPercentage: 0,
|
||||
remainingPercentage: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it("formats compact token counts", () => {
|
||||
expect(formatContextWindowTokens(999)).toBe("999");
|
||||
expect(formatContextWindowTokens(1400)).toBe("1.4k");
|
||||
expect(formatContextWindowTokens(14_000)).toBe("14k");
|
||||
expect(formatContextWindowTokens(258_000)).toBe("258k");
|
||||
});
|
||||
|
||||
it("includes total processed tokens when available", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {
|
||||
usedTokens: 81_659,
|
||||
totalProcessedTokens: 748_126,
|
||||
maxTokens: 258_400,
|
||||
lastUsedTokens: 81_659,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(snapshot?.usedTokens).toBe(81_659);
|
||||
expect(snapshot?.totalProcessedTokens).toBe(748_126);
|
||||
it("formats compact token values", () => {
|
||||
expect(formatContextWindowTokens(1_500)).toBe("1.5k");
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,10 @@
|
||||
import type { OrchestrationThreadActivity, ThreadTokenUsageSnapshot } from "@t3tools/contracts";
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
import type { ThreadTokenUsageSnapshot } from "@t3tools/contracts";
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
function asFiniteNumber(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function asBoolean(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
type NullableContextWindowUsage = {
|
||||
readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key]
|
||||
? Exclude<ThreadTokenUsageSnapshot[Key], undefined> | null
|
||||
@@ -48,21 +41,20 @@ export function formatProviderDisplayName(provider: string | null | undefined):
|
||||
}
|
||||
|
||||
export function deriveLatestContextWindowSnapshot(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
entries: ReadonlyArray<ThreadWorkEntry>,
|
||||
): ContextWindowSnapshot | null {
|
||||
for (let index = activities.length - 1; index >= 0; index -= 1) {
|
||||
const activity = activities[index];
|
||||
if (!activity || activity.kind !== "context-window.updated") {
|
||||
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
||||
const entry = entries[index];
|
||||
if (!entry || entry.structuredPayload.type !== "compaction") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const payload = asRecord(activity.payload);
|
||||
const usedTokens = asFiniteNumber(payload?.usedTokens);
|
||||
const payload = entry.structuredPayload;
|
||||
const usedTokens = asFiniteNumber(payload.afterTokenCount);
|
||||
if (usedTokens === null || usedTokens < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const maxTokens = asFiniteNumber(payload?.maxTokens);
|
||||
const maxTokens = null;
|
||||
const usedPercentage =
|
||||
maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
|
||||
const remainingTokens =
|
||||
@@ -71,24 +63,24 @@ export function deriveLatestContextWindowSnapshot(
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
totalProcessedTokens: asFiniteNumber(payload?.totalProcessedTokens),
|
||||
totalProcessedTokens: asFiniteNumber(payload.beforeTokenCount),
|
||||
maxTokens,
|
||||
remainingTokens,
|
||||
usedPercentage,
|
||||
remainingPercentage,
|
||||
inputTokens: asFiniteNumber(payload?.inputTokens),
|
||||
cachedInputTokens: asFiniteNumber(payload?.cachedInputTokens),
|
||||
outputTokens: asFiniteNumber(payload?.outputTokens),
|
||||
reasoningOutputTokens: asFiniteNumber(payload?.reasoningOutputTokens),
|
||||
lastUsedTokens: asFiniteNumber(payload?.lastUsedTokens),
|
||||
lastInputTokens: asFiniteNumber(payload?.lastInputTokens),
|
||||
lastCachedInputTokens: asFiniteNumber(payload?.lastCachedInputTokens),
|
||||
lastOutputTokens: asFiniteNumber(payload?.lastOutputTokens),
|
||||
lastReasoningOutputTokens: asFiniteNumber(payload?.lastReasoningOutputTokens),
|
||||
toolUses: asFiniteNumber(payload?.toolUses),
|
||||
durationMs: asFiniteNumber(payload?.durationMs),
|
||||
compactsAutomatically: asBoolean(payload?.compactsAutomatically) ?? false,
|
||||
updatedAt: activity.createdAt,
|
||||
inputTokens: null,
|
||||
cachedInputTokens: null,
|
||||
outputTokens: null,
|
||||
reasoningOutputTokens: null,
|
||||
lastUsedTokens: null,
|
||||
lastInputTokens: null,
|
||||
lastCachedInputTokens: null,
|
||||
lastOutputTokens: null,
|
||||
lastReasoningOutputTokens: null,
|
||||
toolUses: null,
|
||||
durationMs: null,
|
||||
compactsAutomatically: true,
|
||||
updatedAt: entry.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,13 +7,14 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import { getLatestThreadForProject, sortThreads } from "./threadSort";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
@@ -21,7 +22,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
@@ -30,13 +31,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("sortThreads", () => {
|
||||
@@ -51,7 +50,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -67,7 +66,7 @@ describe("sortThreads", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
updatedAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
@@ -95,7 +94,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
+123
-1652
File diff suppressed because it is too large.
Load diff
+405
-1257
File diff suppressed because it is too large.
Load diff
@@ -3,21 +3,14 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRuntimeSummary,
|
||||
ThreadWorkEntry,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
type EnvironmentThreadStatus,
|
||||
mergeEnvironmentThread,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import type {
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThreadActivity,
|
||||
ScopedProjectRef,
|
||||
ScopedThreadRef,
|
||||
ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads";
|
||||
import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useMemo } from "react";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -28,9 +21,10 @@ import { environmentThreadDetails, environmentThreadShells } from "./threads";
|
||||
|
||||
const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);
|
||||
const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
|
||||
const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);
|
||||
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_MESSAGES: ReadonlyArray<ThreadConversationMessage> = Object.freeze([]);
|
||||
const EMPTY_WORK_ENTRIES: ReadonlyArray<ThreadWorkEntry> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<ThreadProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
|
||||
|
||||
const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
|
||||
Atom.withLabel("web-project:empty"),
|
||||
@@ -53,14 +47,17 @@ const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pip
|
||||
const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(
|
||||
Atom.withLabel("web-thread-messages:empty"),
|
||||
);
|
||||
const EMPTY_ACTIVITIES_ATOM = Atom.make(EMPTY_ACTIVITIES).pipe(
|
||||
Atom.withLabel("web-thread-activities:empty"),
|
||||
const EMPTY_WORK_ENTRIES_ATOM = Atom.make(EMPTY_WORK_ENTRIES).pipe(
|
||||
Atom.withLabel("web-thread-work-entries:empty"),
|
||||
);
|
||||
const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe(
|
||||
Atom.withLabel("web-thread-proposed-plans:empty"),
|
||||
);
|
||||
const EMPTY_SESSION_ATOM = Atom.make<OrchestrationSession | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-session:empty"),
|
||||
const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
|
||||
Atom.withLabel("web-thread-visible-turn-items:empty"),
|
||||
);
|
||||
const EMPTY_RUNTIME_ATOM = Atom.make<ThreadRuntimeSummary | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-runtime:empty"),
|
||||
);
|
||||
|
||||
export const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
|
||||
@@ -186,31 +183,39 @@ export function useThread(
|
||||
|
||||
export function useThreadMessages(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationMessage> {
|
||||
): ReadonlyArray<ThreadConversationMessage> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_MESSAGES_ATOM : environmentThreadDetails.messagesAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadActivities(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
export function useThreadWorkEntries(ref: ScopedThreadRef | null): ReadonlyArray<ThreadWorkEntry> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_ACTIVITIES_ATOM : environmentThreadDetails.activitiesAtom(ref),
|
||||
ref === null ? EMPTY_WORK_ENTRIES_ATOM : environmentThreadDetails.workEntriesAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadProposedPlans(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationProposedPlan> {
|
||||
): ReadonlyArray<ThreadProposedPlan> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_PROPOSED_PLANS_ATOM : environmentThreadDetails.proposedPlansAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadSession(ref: ScopedThreadRef | null): OrchestrationSession | null {
|
||||
export function useThreadVisibleTurnItems(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_SESSION_ATOM : environmentThreadDetails.sessionAtom(ref),
|
||||
ref === null
|
||||
? EMPTY_VISIBLE_TURN_ITEMS_ATOM
|
||||
: environmentThreadDetails.visibleTurnItemsAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadRuntime(ref: ScopedThreadRef | null): ThreadRuntimeSummary | null {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_RUNTIME_ATOM : environmentThreadDetails.runtimeAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,15 +9,8 @@ import {
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
ProjectContentMatch,
|
||||
ProjectEntryKind,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -56,7 +49,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type EnvironmentThreadState,
|
||||
createThreadEnvironmentAtoms,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { presentThread, type EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -32,14 +33,21 @@ const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_
|
||||
export function useEnvironmentThread(
|
||||
environmentId: EnvironmentId | null,
|
||||
threadId: ThreadId | null,
|
||||
): EnvironmentThreadState {
|
||||
): Omit<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
const result = useAtomValue(
|
||||
environmentId !== null && threadId !== null
|
||||
? environmentThreads.stateAtom(environmentId, threadId)
|
||||
: EMPTY_THREAD_STATE_ATOM,
|
||||
);
|
||||
return Option.getOrElse(
|
||||
const state = Option.getOrElse(
|
||||
AsyncResult.value(result),
|
||||
() => EMPTY_ENVIRONMENT_THREAD_STATE,
|
||||
) as EnvironmentThreadState;
|
||||
return {
|
||||
...state,
|
||||
data:
|
||||
environmentId === null
|
||||
? Option.none()
|
||||
: Option.map(state.data, (projection) => presentThread(environmentId, projection)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { presentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { Thread } from "./types";
|
||||
|
||||
const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
/** Creates a structurally complete V2 thread for UI unit tests. */
|
||||
export function makeThreadFixture(overrides: Partial<Thread> = {}): Thread {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const id = overrides.id ?? ThreadId.make("thread-test");
|
||||
const projectId = overrides.projectId ?? ProjectId.make("project-test");
|
||||
const providerInstanceId =
|
||||
overrides.providerInstanceId ??
|
||||
overrides.modelSelection?.instanceId ??
|
||||
ProviderInstanceId.make("codex");
|
||||
const modelSelection = overrides.modelSelection ?? {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
};
|
||||
// Presentation-level overrides are applied after projection. Keep the source
|
||||
// projection valid so tests can deliberately exercise malformed persisted
|
||||
// timestamps without failing inside Effect's DateTime constructor first.
|
||||
const createdAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const updatedAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const archivedAt =
|
||||
overrides.archivedAt === null || overrides.archivedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.archivedAt);
|
||||
const deletedAt =
|
||||
overrides.deletedAt === null || overrides.deletedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.deletedAt);
|
||||
const projection: OrchestrationV2ThreadProjection = {
|
||||
thread: {
|
||||
id,
|
||||
projectId,
|
||||
title: overrides.title ?? "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: overrides.runtimeMode ?? "full-access",
|
||||
interactionMode: overrides.interactionMode ?? "default",
|
||||
branch: overrides.branch ?? null,
|
||||
worktreePath: overrides.worktreePath ?? null,
|
||||
activeProviderThreadId: overrides.activeProviderThreadId ?? null,
|
||||
lineage: overrides.lineage ?? {
|
||||
rootThreadId: id,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: overrides.forkedFrom ?? null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt,
|
||||
updatedAt,
|
||||
archivedAt,
|
||||
deletedAt,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
return {
|
||||
...presentThread(environmentId, projection),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
+11
-12
@@ -1,11 +1,5 @@
|
||||
import type {
|
||||
ChatImageAttachment as ContractChatImageAttachment,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
ProjectScript as ContractProjectScript,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -14,6 +8,11 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadCheckpointSummary,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRunSummary,
|
||||
ThreadRuntimeSummary,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
@@ -37,21 +36,21 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
|
||||
|
||||
export type ChatAttachment = ChatImageAttachment;
|
||||
|
||||
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
|
||||
export interface ChatMessage extends Omit<ThreadConversationMessage, "attachments"> {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
export type ProposedPlan = OrchestrationProposedPlan;
|
||||
export type TurnDiffFileChange = OrchestrationCheckpointFile;
|
||||
export type TurnDiffSummary = OrchestrationCheckpointSummary;
|
||||
export type ProposedPlan = ThreadProposedPlan;
|
||||
export type TurnDiffFileChange = ThreadCheckpointSummary["files"][number];
|
||||
export type TurnDiffSummary = ThreadCheckpointSummary;
|
||||
|
||||
export type Project = EnvironmentProject;
|
||||
export type Thread = EnvironmentThread;
|
||||
export type ThreadShell = EnvironmentThreadShell;
|
||||
|
||||
export interface ThreadTurnState {
|
||||
latestTurn: OrchestrationLatestTurn | null;
|
||||
latestRun: ThreadRunSummary | null;
|
||||
}
|
||||
|
||||
export type SidebarThreadSummary = EnvironmentThreadShell;
|
||||
export type ThreadSession = OrchestrationSession;
|
||||
export type ThreadSession = ThreadRuntimeSummary;
|
||||
@@ -2,12 +2,13 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
|
||||
import { makeThreadFixture } from "./test-fixtures";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
@@ -18,10 +19,8 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
updatedAt: "2026-02-13T00:00:00.000Z",
|
||||
@@ -29,11 +28,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("getOrphanedWorktreePathForThread", () => {
|
||||
|
||||
Reference in new issue
Block a user