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:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:45:05 -04:00
1 parent 75e126993b
commit 3991a00629
111 files changed
+6306 -9244

No files matched your search

@@ -1,7 +1,7 @@
import {
type DesktopSshEnvironmentTarget,
EnvironmentId,
type OrchestrationShellSnapshot,
type OrchestrationV2ShellSnapshot,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
@@ -46,6 +46,7 @@ import * as EnvironmentRegistry from "./registry.ts";
import * as RpcSession from "../rpc/session.ts";
import * as EnvironmentSupervisor from "./supervisor.ts";
import * as ConnectionWakeups from "./wakeups.ts";
import { v2ShellSnapshot } from "../state/orchestrationV2TestFixtures.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -112,11 +113,9 @@ const SSH_PROFILE = new SshConnectionProfile({
target: SSH_TARGET,
});
const CACHED_SNAPSHOT: OrchestrationShellSnapshot = {
const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 1,
projects: [],
threads: [],
updatedAt: "2026-06-06T00:00:00.000Z",
};
interface SessionControl {
@@ -1,13 +1,22 @@
import {
CommandId,
EnvironmentId,
ORCHESTRATION_WS_METHODS,
MessageId,
ORCHESTRATION_V2_WS_METHODS,
PlanId,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
type ClientOrchestrationCommand,
WS_METHODS,
type OrchestrationV2Command,
type OrchestrationV2ThreadLaunchInput,
type OrchestrationV2ThreadProjection,
type ProjectMutation,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -21,13 +30,8 @@ import {
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
archiveThread,
createProject,
settleThread,
stopThreadSession,
unsettleThread,
} from "./commands.ts";
import { v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
import { archiveThread, createProject, startThreadTurn } from "./commands.ts";
const TEST_CRYPTO_LAYER = Layer.succeed(
Crypto.Crypto,
@@ -44,14 +48,45 @@ const TARGET = new PrimaryConnectionTarget({
wsBaseUrl: "wss://environment.example.test",
});
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (
dispatched: ClientOrchestrationCommand[],
) {
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
readonly commands: OrchestrationV2Command[];
readonly projects: ProjectMutation[];
readonly launches?: OrchestrationV2ThreadLaunchInput[];
readonly projection?: OrchestrationV2ThreadProjection;
}) {
const client = {
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command: ClientOrchestrationCommand) =>
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
Effect.sync(() => {
dispatched.push(command);
return { sequence: dispatched.length };
input.commands.push(command);
return { sequence: input.commands.length };
}),
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () =>
Effect.succeed(input.projection ?? v2Projection),
[ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
Effect.sync(() => {
input.launches?.push(launchInput);
return {
threadId: launchInput.threadId ?? v2ThreadId,
projection: input.projection ?? v2Projection,
resumed: false,
};
}),
[WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
Effect.sync(() => {
input.projects.push(mutation);
return {
id: mutation.projectId,
title: mutation.type === "project.create" ? mutation.title : "Project",
workspaceRoot:
mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
repositoryIdentity: null,
faviconPath: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-06T00:00:00.000Z",
updatedAt: "2026-06-06T00:00:00.000Z",
deletedAt: null,
};
}),
} as unknown as WsRpcProtocolClient;
const session: RpcSession.RpcSession = {
@@ -72,103 +107,222 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
});
describe("environment commands", () => {
it.effect("adds generated command metadata", () =>
describe("V2 environment commands", () => {
it.effect("routes projects through the event-sourced project transport", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
const projects: ProjectMutation[] = [];
const supervisor = yield* makeSupervisor({ commands: [], projects });
const result = yield* createProject({
yield* createProject({
projectId: ProjectId.make("project-1"),
title: "Project",
workspaceRoot: "/workspace/project",
createdAt: "2026-06-06T00:00:00.000Z",
createWorkspaceRootIfMissing: true,
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(result).toEqual({ sequence: 1 });
expect(dispatched).toEqual([
expect(projects).toEqual([
{
type: "project.create",
commandId: "00000000-0000-4000-8000-000000000000",
projectId: "project-1",
title: "Project",
workspaceRoot: "/workspace/project",
createdAt: "2026-06-06T00:00:00.000Z",
createWorkspaceRootIfMissing: true,
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("preserves caller metadata for idempotent queued commands", () =>
it.effect("preserves caller command ids for idempotent V2 commands", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
yield* stopThreadSession({
commandId: CommandId.make("queued-command"),
threadId: ThreadId.make("thread-1"),
createdAt: "2026-06-06T00:01:00.000Z",
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.session.stop",
commandId: "queued-command",
threadId: "thread-1",
createdAt: "2026-06-06T00:01:00.000Z",
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("does not add timestamps to commands without createdAt", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
const commands: OrchestrationV2Command[] = [];
const supervisor = yield* makeSupervisor({ commands, projects: [] });
yield* archiveThread({
commandId: CommandId.make("archive-command"),
commandId: CommandId.make("queued-command"),
threadId: ThreadId.make("thread-1"),
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.archive",
commandId: "archive-command",
threadId: "thread-1",
},
expect(commands).toEqual([
{ type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("dispatches settle and unsettle commands without timestamps", () =>
it.effect("preserves plan implementation provenance on V2 runs", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
const commands: OrchestrationV2Command[] = [];
const supervisor = yield* makeSupervisor({ commands, projects: [] });
yield* settleThread({
commandId: CommandId.make("settle-command"),
threadId: ThreadId.make("thread-1"),
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
yield* unsettleThread({
commandId: CommandId.make("unsettle-command"),
threadId: ThreadId.make("thread-1"),
reason: "user",
yield* startThreadTurn({
commandId: CommandId.make("implement-plan"),
threadId: v2ThreadId,
message: {
messageId: MessageId.make("message-implementation"),
role: "user",
text: "Implement the plan",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
sourceProposedPlan: {
threadId: ThreadId.make("thread-plan"),
planId: PlanId.make("plan-1"),
},
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.settle",
commandId: "settle-command",
threadId: "thread-1",
expect(commands).toHaveLength(1);
expect(commands[0]).toMatchObject({
type: "message.dispatch",
commandId: "implement-plan",
threadId: v2ThreadId,
sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
dispatchMode: { type: "start_immediately" },
});
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("preserves an existing worktree and branch during first-message launch", () =>
Effect.gen(function* () {
const launches: OrchestrationV2ThreadLaunchInput[] = [];
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
yield* startThreadTurn({
commandId: CommandId.make("launch-existing-worktree"),
threadId: v2ThreadId,
message: {
messageId: MessageId.make("message-existing-worktree"),
role: "user",
text: "Continue here",
attachments: [],
},
{
type: "thread.unsettle",
commandId: "unsettle-command",
threadId: "thread-1",
reason: "user",
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: v2Projection.thread.modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature",
worktreePath: "/workspace/project-worktrees/feature",
createdAt: "2026-06-20T00:00:00.000Z",
},
},
]);
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(launches[0]).toMatchObject({
threadId: v2ThreadId,
workspaceStrategy: {
type: "existing_worktree",
worktreePath: "/workspace/project-worktrees/feature",
branch: "feature",
},
});
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("provisions an origin-based worktree for an existing empty thread", () =>
Effect.gen(function* () {
const launches: OrchestrationV2ThreadLaunchInput[] = [];
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
yield* startThreadTurn({
commandId: CommandId.make("launch-existing-thread-worktree"),
threadId: v2ThreadId,
message: {
messageId: MessageId.make("message-existing-thread-worktree"),
role: "user",
text: "Move to a worktree",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
prepareWorktree: {
projectCwd: "/workspace/project",
baseBranch: "main",
branch: "feature",
startFromOrigin: true,
},
},
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(launches[0]).toMatchObject({
threadId: v2ThreadId,
reuseExistingThread: true,
projectId: v2Projection.thread.projectId,
workspaceStrategy: {
type: "worktree",
baseRef: "main",
branch: "feature",
startFromOrigin: true,
},
});
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("maps explicit active-run delivery modes to V2 dispatch semantics", () =>
Effect.gen(function* () {
const activeRunId = RunId.make("run-active");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const projection: OrchestrationV2ThreadProjection = {
...v2Projection,
runs: [
{
id: activeRunId,
threadId: v2ThreadId,
ordinal: 1,
providerInstanceId: v2Projection.thread.providerInstanceId,
modelSelection: v2Projection.thread.modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message-active"),
rootNodeId: null,
activeAttemptId: null,
status: "running",
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
],
};
const commands: OrchestrationV2Command[] = [];
const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
for (const [mode, expectedType] of [
["queue", "queue_after_active"],
["steer", "steer_active"],
["restart", "restart_active"],
] as const) {
yield* startThreadTurn({
commandId: CommandId.make(`command-${mode}`),
threadId: v2ThreadId,
message: {
messageId: MessageId.make(`message-${mode}`),
role: "user",
text: mode,
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
dispatchMode: mode,
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(commands.at(-1)).toMatchObject({
type: "message.dispatch",
dispatchMode: {
type: expectedType,
...(mode === "queue" ? {} : { targetRunId: activeRunId }),
},
});
}
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
});
+491 -243
View File
@@ -1,300 +1,548 @@
import {
CommandId,
ORCHESTRATION_WS_METHODS,
type ClientOrchestrationCommand,
ORCHESTRATION_V2_WS_METHODS,
WS_METHODS,
type ChatAttachment,
type MessageId,
type ModelSelection,
type OrchestrationV2Command,
type OrchestrationV2CreationSource,
type PlanId,
type ProjectId,
type ProjectScript,
type ProviderApprovalDecision,
type ProviderInteractionMode,
type ProviderUserInputAnswers,
type RunId,
type RuntimeMode,
type RuntimeRequestId,
type ThreadId,
type UploadChatAttachment,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import type { EnvironmentSupervisor } from "../connection/supervisor.ts";
import {
type EnvironmentRpcFailure,
type EnvironmentRpcSuccess,
type EnvironmentRpcUnavailableError,
request,
} from "../rpc/client.ts";
import { request } from "../rpc/client.ts";
type CommandType = ClientOrchestrationCommand["type"];
type CommandOf<T extends CommandType> = Extract<ClientOrchestrationCommand, { readonly type: T }>;
type CommandInput<T extends CommandType> = Omit<
CommandOf<T>,
"type" | "commandId" | "createdAt"
> & {
readonly commandId?: CommandId;
} & ("createdAt" extends keyof CommandOf<T>
? {
readonly createdAt?: CommandOf<T>["createdAt"];
}
: {});
export type CreateProjectInput = CommandInput<"project.create">;
export type UpdateProjectInput = CommandInput<"project.meta.update">;
export type DeleteProjectInput = CommandInput<"project.delete">;
export type CreateThreadInput = CommandInput<"thread.create">;
export type DeleteThreadInput = CommandInput<"thread.delete">;
export type ArchiveThreadInput = CommandInput<"thread.archive">;
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
export type SettleThreadInput = CommandInput<"thread.settle">;
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
export type StartThreadTurnInput = CommandInput<"thread.turn.start">;
export type InterruptThreadTurnInput = CommandInput<"thread.turn.interrupt">;
export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond">;
export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">;
export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">;
export type StopThreadSessionInput = CommandInput<"thread.session.stop">;
type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand;
type CommandEffect = Effect.Effect<
EnvironmentRpcSuccess<DispatchTag>,
EnvironmentRpcFailure<DispatchTag> | EnvironmentRpcUnavailableError,
Crypto.Crypto | EnvironmentSupervisor
>;
function commandId(input: { readonly commandId?: CommandId }) {
return Effect.gen(function* () {
if (input.commandId !== undefined) {
return input.commandId;
}
const crypto = yield* Crypto.Crypto;
return yield* crypto.randomUUIDv4.pipe(Effect.orDie, Effect.map(CommandId.make));
});
}
function timestampedCommandMetadata(input: {
interface CommandMetadata {
readonly commandId?: CommandId;
readonly createdAt?: string;
}) {
return Effect.all({
commandId: commandId(input),
createdAt:
input.createdAt === undefined
? DateTime.now.pipe(Effect.map(DateTime.formatIso))
: Effect.succeed(input.createdAt),
readonly creationSource?: OrchestrationV2CreationSource;
}
export interface CreateProjectInput extends CommandMetadata {
readonly projectId: ProjectId;
readonly title: string;
readonly workspaceRoot: string;
readonly createWorkspaceRootIfMissing?: boolean;
readonly defaultModelSelection?: ModelSelection | null;
readonly scripts?: ReadonlyArray<ProjectScript>;
}
export interface UpdateProjectInput extends CommandMetadata {
readonly projectId: ProjectId;
readonly title?: string;
readonly workspaceRoot?: string;
readonly defaultModelSelection?: ModelSelection | null;
readonly scripts?: ReadonlyArray<ProjectScript>;
}
export interface DeleteProjectInput extends CommandMetadata {
readonly projectId: ProjectId;
readonly force?: boolean;
}
export interface CreateThreadInput extends CommandMetadata {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly title: string;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly branch: string | null;
readonly worktreePath: string | null;
}
export interface ThreadCommandInput extends CommandMetadata {
readonly threadId: ThreadId;
}
export type DeleteThreadInput = ThreadCommandInput;
export type ArchiveThreadInput = ThreadCommandInput;
export type UnarchiveThreadInput = ThreadCommandInput;
export interface UpdateThreadMetadataInput extends ThreadCommandInput {
readonly title?: string;
readonly modelSelection?: ModelSelection;
readonly branch?: string | null;
readonly worktreePath?: string | null;
}
export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
readonly runtimeMode: RuntimeMode;
}
export interface SetThreadInteractionModeInput extends ThreadCommandInput {
readonly interactionMode: ProviderInteractionMode;
}
interface StartThreadBootstrap {
readonly createThread?: {
readonly projectId: ProjectId;
readonly title: string;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly branch: string | null;
readonly worktreePath: string | null;
readonly createdAt: string;
};
readonly prepareWorktree?: {
readonly projectCwd: string;
readonly baseBranch: string;
readonly branch?: string;
readonly startFromOrigin?: boolean;
};
readonly runSetupScript?: boolean;
}
export interface StartThreadTurnInput extends ThreadCommandInput {
readonly message: {
readonly messageId: MessageId;
readonly role: "user";
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
};
readonly modelSelection?: ModelSelection;
readonly titleSeed?: string;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly bootstrap?: StartThreadBootstrap;
readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
readonly dispatchMode?: "auto" | "queue" | "steer" | "restart";
}
export interface InterruptThreadTurnInput extends ThreadCommandInput {
readonly runId?: RunId;
/** Temporary caller compatibility while UI naming moves from turns to runs. */
readonly turnId?: string;
}
export interface RespondToThreadApprovalInput extends ThreadCommandInput {
readonly requestId: RuntimeRequestId;
readonly decision: ProviderApprovalDecision;
}
export interface RespondToThreadUserInputInput extends ThreadCommandInput {
readonly requestId: RuntimeRequestId;
readonly answers: ProviderUserInputAnswers;
}
export interface RevertThreadCheckpointInput extends ThreadCommandInput {
readonly checkpointId?: string;
readonly scopeId?: string;
readonly turnCount?: number;
}
export type StopThreadSessionInput = ThreadCommandInput;
const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
input: CommandMetadata,
) {
if (input.commandId !== undefined) return input.commandId;
const crypto = yield* Crypto.Crypto;
return CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie));
});
const dispatch = (command: OrchestrationV2Command) =>
request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
const getProjection = (threadId: ThreadId) =>
request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* (
threadId: ThreadId,
messageId: MessageId,
attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>,
) {
const stored = attachments.filter(
(attachment): attachment is ChatAttachment => "id" in attachment,
);
const uploads = attachments.filter(
(attachment): attachment is UploadChatAttachment => "dataUrl" in attachment,
);
if (uploads.length === 0) return stored;
const result = yield* request(WS_METHODS.assetsPersistChatAttachments, {
threadId,
messageId,
attachments: uploads,
});
}
if (stored.length === 0) return result.attachments;
const byUpload = new Map(
uploads.map((attachment, index) => [attachment, result.attachments[index]]),
);
return attachments.flatMap((attachment) => {
if ("id" in attachment) return [attachment];
const persisted = byUpload.get(attachment);
return persisted === undefined ? [] : [persisted];
});
});
function dispatch(command: ClientOrchestrationCommand) {
return request(ORCHESTRATION_WS_METHODS.dispatchCommand, command);
}
const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* (
mutation:
| {
readonly type: "project.create";
readonly commandId: CommandId;
readonly projectId: ProjectId;
readonly title: string;
readonly workspaceRoot: string;
readonly createWorkspaceRootIfMissing?: boolean;
readonly defaultModelSelection?: ModelSelection | null;
readonly scripts?: ReadonlyArray<ProjectScript>;
}
| {
readonly type: "project.update";
readonly commandId: CommandId;
readonly projectId: ProjectId;
readonly title?: string;
readonly workspaceRoot?: string;
readonly defaultModelSelection?: ModelSelection | null;
readonly scripts?: ReadonlyArray<ProjectScript>;
}
| {
readonly type: "project.delete";
readonly commandId: CommandId;
readonly projectId: ProjectId;
readonly force?: boolean;
},
) {
return yield* request(WS_METHODS.projectsMutate, mutation);
});
export const createProject: (input: CreateProjectInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.createProject",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
return yield* dispatch({
...input,
export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
input: CreateProjectInput,
) {
return yield* mutateProject({
type: "project.create",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
commandId: yield* allocateCommandId(input),
projectId: input.projectId,
title: input.title,
workspaceRoot: input.workspaceRoot,
...(input.createWorkspaceRootIfMissing === undefined
? {}
: { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
...(input.defaultModelSelection === undefined
? {}
: { defaultModelSelection: input.defaultModelSelection }),
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
});
});
export const updateProject: (input: UpdateProjectInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.updateProject",
)(function* (input) {
return yield* dispatch({
...input,
type: "project.meta.update",
commandId: yield* commandId(input),
export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
input: UpdateProjectInput,
) {
return yield* mutateProject({
type: "project.update",
commandId: yield* allocateCommandId(input),
projectId: input.projectId,
...(input.title === undefined ? {} : { title: input.title }),
...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
...(input.defaultModelSelection === undefined
? {}
: { defaultModelSelection: input.defaultModelSelection }),
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
});
});
export const deleteProject: (input: DeleteProjectInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.deleteProject",
)(function* (input) {
return yield* dispatch({
...input,
export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
input: DeleteProjectInput,
) {
return yield* mutateProject({
type: "project.delete",
commandId: yield* commandId(input),
commandId: yield* allocateCommandId(input),
projectId: input.projectId,
...(input.force === undefined ? {} : { force: input.force }),
});
});
export const createThread: (input: CreateThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.createThread",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
input: CreateThreadInput,
) {
return yield* dispatch({
...input,
type: "thread.create",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
commandId: yield* allocateCommandId(input),
createdBy: "user",
creationSource: input.creationSource ?? "web",
threadId: input.threadId,
projectId: input.projectId,
title: input.title,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
branch: input.branch,
worktreePath: input.worktreePath,
});
});
export const deleteThread: (input: DeleteThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.deleteThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.delete",
commandId: yield* commandId(input),
});
function simpleThreadCommand(
type: "thread.delete" | "thread.archive" | "thread.unarchive",
input: ThreadCommandInput,
) {
return allocateCommandId(input).pipe(
Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
);
}
export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
input: DeleteThreadInput,
) {
return yield* simpleThreadCommand("thread.delete", input);
});
export const archiveThread: (input: ArchiveThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.archiveThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.archive",
commandId: yield* commandId(input),
});
export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
input: ArchiveThreadInput,
) {
return yield* simpleThreadCommand("thread.archive", input);
});
export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.unarchiveThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.unarchive",
commandId: yield* commandId(input),
});
export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
input: UnarchiveThreadInput,
) {
return yield* simpleThreadCommand("thread.unarchive", input);
});
export const settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.settleThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.settle",
commandId: yield* commandId(input),
});
});
export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
function* (input: UpdateThreadMetadataInput) {
const commandId = yield* allocateCommandId(input);
let result = null;
if (
input.title !== undefined ||
input.branch !== undefined ||
input.worktreePath !== undefined
) {
result = yield* dispatch({
type: "thread.metadata.update",
commandId,
threadId: input.threadId,
...(input.title === undefined ? {} : { title: input.title }),
...(input.branch === undefined ? {} : { branch: input.branch }),
...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
});
}
if (input.modelSelection !== undefined) {
result = yield* dispatch({
type: "thread.model-selection.set",
commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
threadId: input.threadId,
modelSelection: input.modelSelection,
});
}
return result ?? { sequence: 0 };
},
);
export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.unsettleThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.unsettle",
commandId: yield* commandId(input),
});
});
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.snoozeThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.snooze",
commandId: yield* commandId(input),
});
});
export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.unsnoozeThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.unsnooze",
commandId: yield* commandId(input),
});
});
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.updateThreadMetadata",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.meta.update",
commandId: yield* commandId(input),
});
});
export const setThreadRuntimeMode: (input: SetThreadRuntimeModeInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.setThreadRuntimeMode",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
return yield* dispatch({
...input,
type: "thread.runtime-mode.set",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
});
});
export const setThreadInteractionMode: (input: SetThreadInteractionModeInput) => CommandEffect =
Effect.fn("EnvironmentCommands.setThreadInteractionMode")(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
function* (input: SetThreadRuntimeModeInput) {
return yield* dispatch({
type: "thread.runtime-mode.set",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runtimeMode: input.runtimeMode,
});
},
);
export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
function* (input: SetThreadInteractionModeInput) {
return yield* dispatch({
...input,
type: "thread.interaction-mode.set",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
interactionMode: input.interactionMode,
});
});
},
);
export const startThreadTurn: (input: StartThreadTurnInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.startThreadTurn",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
input: StartThreadTurnInput,
) {
const commandId = yield* allocateCommandId(input);
const attachments = yield* persistAttachments(
input.threadId,
input.message.messageId,
input.message.attachments,
);
const bootstrap = input.bootstrap?.createThread;
const prepareWorktree = input.bootstrap?.prepareWorktree;
if (bootstrap !== undefined || prepareWorktree !== undefined) {
const existingProjection =
bootstrap === undefined ? yield* getProjection(input.threadId) : null;
const thread = bootstrap ?? existingProjection!.thread;
const workspaceStrategy =
prepareWorktree !== undefined
? {
type: "worktree" as const,
baseRef: prepareWorktree.baseBranch,
...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
...(prepareWorktree.startFromOrigin === undefined
? {}
: { startFromOrigin: prepareWorktree.startFromOrigin }),
}
: bootstrap?.worktreePath
? {
type: "existing_worktree" as const,
worktreePath: bootstrap.worktreePath,
...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
}
: {
type: "root" as const,
...(bootstrap?.branch === null || bootstrap?.branch === undefined
? {}
: { branch: bootstrap.branch }),
};
return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
commandId,
creationSource: input.creationSource ?? "web",
threadId: input.threadId,
...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
projectId: thread.projectId,
title: thread.title,
modelSelection: input.modelSelection ?? thread.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
workspaceStrategy,
initialMessage: {
messageId: input.message.messageId,
text: input.message.text,
attachments,
},
});
}
const projection = yield* getProjection(input.threadId);
const activeRun = projection.runs.findLast(
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
);
const requestedMode = input.dispatchMode ?? "auto";
const activeProviderThread =
activeRun === undefined
? undefined
: projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
const activeProviderSession =
activeProviderThread?.providerSessionId === null ||
activeProviderThread?.providerSessionId === undefined
? undefined
: projection.providerSessions.find(
(session) => session.id === activeProviderThread.providerSessionId,
);
const turnCapabilities = activeProviderSession?.capabilities.turns;
const dispatchMode =
activeRun === undefined
? ({ type: "start_immediately" } as const)
: requestedMode === "steer"
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
: requestedMode === "restart"
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
: requestedMode === "queue"
? ({ type: "queue_after_active" } as const)
: turnCapabilities?.supportsActiveSteering === true
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
: turnCapabilities?.supportsQueuedMessages === true
? ({ type: "queue_after_active" } as const)
: turnCapabilities?.supportsSteeringByInterruptRestart === true
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
: ({ type: "queue_after_active" } as const);
return yield* dispatch({
...input,
type: "thread.turn.start",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
type: "message.dispatch",
commandId,
createdBy: "user",
creationSource: input.creationSource ?? "web",
threadId: input.threadId,
messageId: input.message.messageId,
text: input.message.text,
attachments,
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
dispatchMode,
});
});
export const interruptThreadTurn: (input: InterruptThreadTurnInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.interruptThreadTurn",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
input: InterruptThreadTurnInput,
) {
const projection = yield* getProjection(input.threadId);
const runId =
input.runId ??
(input.turnId as RunId | undefined) ??
projection.runs.findLast(
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
)?.id;
if (runId === undefined) return { sequence: 0 };
return yield* dispatch({
...input,
type: "thread.turn.interrupt",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
type: "run.interrupt",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runId,
});
});
export const respondToThreadApproval: (input: RespondToThreadApprovalInput) => CommandEffect =
Effect.fn("EnvironmentCommands.respondToThreadApproval")(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
function* (input: RespondToThreadApprovalInput) {
return yield* dispatch({
...input,
type: "thread.approval.respond",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
type: "runtime-request.respond",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
requestId: input.requestId,
decision: input.decision,
});
});
},
);
export const respondToThreadUserInput: (input: RespondToThreadUserInputInput) => CommandEffect =
Effect.fn("EnvironmentCommands.respondToThreadUserInput")(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
function* (input: RespondToThreadUserInputInput) {
return yield* dispatch({
...input,
type: "thread.user-input.respond",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
type: "runtime-request.respond",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
requestId: input.requestId,
answers: input.answers,
});
});
},
);
export const revertThreadCheckpoint: (input: RevertThreadCheckpointInput) => CommandEffect =
Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
function* (input: RevertThreadCheckpointInput) {
const projection = yield* getProjection(input.threadId);
const checkpoint =
projection.checkpoints.find(
(candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
) ??
projection.checkpoints.findLast((candidate) => candidate.appRunOrdinal === input.turnCount);
if (checkpoint === undefined) return { sequence: 0 };
return yield* dispatch({
...input,
type: "thread.checkpoint.revert",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
type: "checkpoint.rollback",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
scopeId: checkpoint.scopeId,
checkpointId: checkpoint.id,
});
});
},
);
export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.stopThreadSession",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
return yield* dispatch({
...input,
type: "thread.session.stop",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
});
export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
input: StopThreadSessionInput,
) {
const projection = yield* getProjection(input.threadId);
const commandId = yield* allocateCommandId(input);
let result = { sequence: 0 };
for (const session of projection.providerSessions) {
result = yield* dispatch({
type: "provider-session.detach",
commandId: CommandId.make(`${commandId}:detach:${session.id}`),
threadId: input.threadId,
providerSessionId: session.id,
reason: "client-requested",
});
}
return result;
});
@@ -1,4 +1,5 @@
export * from "./capabilities.ts";
export * from "./persistence.ts";
export * from "./orchestrationCache.ts";
export * from "./source.ts";
export * from "./storageDocument.ts";
@@ -0,0 +1,59 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
ORCHESTRATION_CACHE_SCHEMA_VERSION,
StoredOrchestrationShellSnapshot,
StoredOrchestrationThreadSnapshot,
decodeOrDiscardOrchestrationCache,
} from "./orchestrationCache.ts";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
const environmentId = EnvironmentId.make("environment-cache-test");
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationThreadSnapshot);
describe("orchestration cache envelopes", () => {
it.effect("accepts V2 shell and thread cache envelopes", () =>
Effect.gen(function* () {
const shell = yield* decodeStoredShellSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
snapshot: v2ShellSnapshot,
});
const thread = yield* decodeStoredThreadSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
threadId: v2ThreadId,
thread: v2Projection,
});
expect(shell.snapshot).toEqual(v2ShellSnapshot);
expect(thread.thread).toEqual(v2Projection);
}),
);
it.effect("discards V1-versioned cache envelopes after a decode failure", () =>
Effect.gen(function* () {
let discardCount = 0;
const decoded = decodeStoredShellSnapshot({
schemaVersion: 1,
environmentId,
snapshot: v2ShellSnapshot,
}).pipe(Effect.map(Option.some));
const result = yield* decodeOrDiscardOrchestrationCache(
decoded,
Effect.sync(() => {
discardCount += 1;
}),
);
expect(Option.isNone(result)).toBe(true);
expect(discardCount).toBe(1);
}),
);
});
@@ -0,0 +1,32 @@
import {
EnvironmentId,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadProjection,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 2 as const;
export const StoredOrchestrationShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationV2ShellSnapshot,
});
export const StoredOrchestrationThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationV2ThreadProjection,
});
/** Invalid orchestration caches are disposable and must never block live synchronization. */
export function decodeOrDiscardOrchestrationCache<A, E, R, E2, R2>(
decode: Effect.Effect<Option.Option<A>, E, R>,
discard: Effect.Effect<void, E2, R2>,
) {
return decode.pipe(Effect.catch(() => discard.pipe(Effect.as(Option.none<A>()))));
}
@@ -1,8 +1,7 @@
import {
type EnvironmentId,
type OrchestrationShellSnapshot,
type OrchestrationThreadDetailSnapshot,
type ServerConfig,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadProjection,
type ThreadId,
type VcsListRefsResult,
} from "@t3tools/contracts";
@@ -60,21 +59,18 @@ export class EnvironmentCacheStore extends Context.Service<
{
readonly loadShell: (
environmentId: EnvironmentId,
) => Effect.Effect<Option.Option<OrchestrationShellSnapshot>, ConnectionPersistenceError>;
) => Effect.Effect<Option.Option<OrchestrationV2ShellSnapshot>, ConnectionPersistenceError>;
readonly saveShell: (
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
snapshot: OrchestrationV2ShellSnapshot,
) => Effect.Effect<void, ConnectionPersistenceError>;
readonly loadThread: (
environmentId: EnvironmentId,
threadId: ThreadId,
) => Effect.Effect<
Option.Option<OrchestrationThreadDetailSnapshot>,
ConnectionPersistenceError
>;
) => Effect.Effect<Option.Option<OrchestrationV2ThreadProjection>, ConnectionPersistenceError>;
readonly saveThread: (
environmentId: EnvironmentId,
snapshot: OrchestrationThreadDetailSnapshot,
thread: OrchestrationV2ThreadProjection,
) => Effect.Effect<void, ConnectionPersistenceError>;
readonly removeThread: (
environmentId: EnvironmentId,
+3 -7
View File
@@ -1,8 +1,4 @@
import {
ORCHESTRATION_V2_WS_METHODS,
ORCHESTRATION_WS_METHODS,
WS_METHODS,
} from "@t3tools/contracts";
import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import type * as Duration from "effect/Duration";
@@ -44,8 +40,8 @@ export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string;
type RpcMethod<TTag extends EnvironmentRpcTag> = WsRpcProtocolClient[TTag];
export type EnvironmentSubscriptionRpcTag =
| typeof ORCHESTRATION_WS_METHODS.subscribeShell
| typeof ORCHESTRATION_WS_METHODS.subscribeThread
| typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell
| typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread
| typeof WS_METHODS.subscribeAuthAccess
| typeof WS_METHODS.subscribeServerConfig
| typeof WS_METHODS.subscribeServerLifecycle
@@ -1,4 +1,4 @@
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { expect, it } from "vite-plus/test";
@@ -22,7 +22,7 @@ it("does not expose an archived snapshot failure message", () => {
const snapshotsAtom = createArchivedThreadSnapshotsAtomFamily<Error>({
getSnapshotAtom: () =>
Atom.make(
AsyncResult.failure<OrchestrationShellSnapshot, Error>(
AsyncResult.failure<OrchestrationV2ArchivedShellSnapshot, Error>(
Cause.fail(new Error("credential=secret-value")),
),
),
@@ -1,4 +1,4 @@
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Option from "effect/Option";
@@ -7,7 +7,7 @@ import { AsyncResult, Atom } from "effect/unstable/reactivity";
export interface ArchivedSnapshotEntry {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
readonly snapshot: OrchestrationV2ArchivedShellSnapshot;
}
export interface ArchivedThreadSnapshotsState {
@@ -40,7 +40,7 @@ export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<E
export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
readonly getSnapshotAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationShellSnapshot, E>>;
) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2ArchivedShellSnapshot, E>>;
readonly labelPrefix: string;
}) {
return Atom.family((environmentKey: string) =>
+101 -356
View File
@@ -1,370 +1,115 @@
import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationShellSnapshot,
type OrchestrationThread,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Option from "effect/Option";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { EnvironmentId, MessageId, RunId, TurnItemId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import { PrimaryConnectionTarget } from "../connection/model.ts";
import {
InvalidScopedProjectKeyError,
InvalidScopedProjectRefCollectionKeyError,
InvalidScopedThreadKeyError,
parseProjectKey,
parseProjectRefCollectionKey,
parseThreadKey,
} from "./entities.ts";
import type { EnvironmentShellState } from "./shell.ts";
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
import { createEnvironmentProjectAtoms } from "./projectEntities.ts";
import { createEnvironmentSnapshotAtom } from "./snapshots.ts";
import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
import { mergeEnvironmentThread } from "./threadDetail.ts";
import { createEnvironmentThreadShellAtoms } from "./threadShell.ts";
import { presentThread, presentThreadShell } from "./models.ts";
import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const PROJECT_ID = ProjectId.make("project-1");
const OTHER_PROJECT_ID = ProjectId.make("project-2");
const THREAD_ID = ThreadId.make("thread-1");
const OTHER_THREAD_ID = ThreadId.make("thread-2");
const environmentId = EnvironmentId.make("environment-v2");
describe("scoped entity keys", () => {
it("preserves an invalid project key as structured error data", () => {
const key = "missing-project-key-separator";
let error: unknown;
try {
parseProjectKey(key);
} catch (cause) {
error = cause;
}
expect(error).toEqual(new InvalidScopedProjectKeyError({ key }));
describe("V2 client presentation", () => {
it("presents shell timestamps and status without constructing V1 state", () => {
const shell = presentThreadShell(environmentId, v2ThreadShell);
expect(shell.environmentId).toBe(environmentId);
expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z");
expect(shell.runtime).toBeNull();
expect(shell.source).toBe(v2ThreadShell);
});
it("preserves an invalid thread key as structured error data", () => {
const key = "missing-thread-key-separator";
let error: unknown;
try {
parseThreadKey(key);
} catch (cause) {
error = cause;
}
expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
});
it("preserves malformed project reference collection input and its cause", () => {
const key = "not-json";
let error: unknown;
try {
parseProjectRefCollectionKey(key);
} catch (cause) {
error = cause;
}
expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
expect(error).toMatchObject({ key, cause: expect.anything() });
});
it("rejects invalid project reference collection shapes", () => {
const key = JSON.stringify([["environment-1"]]);
expect(() => parseProjectRefCollectionKey(key)).toThrowError(
InvalidScopedProjectRefCollectionKeyError,
);
});
});
const THREAD_SHELL = {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
} as const;
const SNAPSHOT: OrchestrationShellSnapshot = {
snapshotSequence: 1,
updatedAt: "2026-06-01T00:00:00.000Z",
projects: [
{
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
},
{
id: OTHER_PROJECT_ID,
title: "Other project",
workspaceRoot: "/other-repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
},
],
threads: [
THREAD_SHELL,
{
...THREAD_SHELL,
id: OTHER_THREAD_ID,
projectId: OTHER_PROJECT_ID,
title: "Other thread",
},
],
};
function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
return {
snapshot: Option.some(snapshot),
status: "live",
error: Option.none(),
};
}
function makeHarness() {
const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
);
const threadStateAtoms = Atom.family((_key: string) =>
Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
);
const catalogValueAtom = Atom.make({
isReady: true,
entries: new Map([
[
ENVIRONMENT_ID,
it("retains the complete projection while deriving conversation parity", () => {
const runId = RunId.make("run-1");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const projection = {
...v2Projection,
runs: [
{
target: new PrimaryConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Environment",
httpBaseUrl: "https://example.test",
wsBaseUrl: "wss://example.test",
}),
profile: Option.none(),
id: runId,
threadId: v2Projection.thread.id,
ordinal: 1,
providerInstanceId: v2Projection.thread.providerInstanceId,
modelSelection: v2Projection.thread.modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message-user"),
rootNodeId: null,
activeAttemptId: null,
status: "running" as const,
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
],
]),
});
const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
const projects = createEnvironmentProjectAtoms({
catalogValueAtom,
snapshotAtom,
});
const threadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom,
snapshotAtom,
});
const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
threadStateAtoms(`${environmentId}\u0000${threadId}`),
);
return {
registry: AtomRegistry.make(),
shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
projects,
threadShells,
threadDetails,
};
}
describe("environment entity projections", () => {
it("composes detail collections with authoritative shell workspace metadata", () => {
const messages: OrchestrationThread["messages"] = [];
const detail = {
...THREAD_SHELL,
environmentId: ENVIRONMENT_ID,
title: "Cached thread",
branch: "stale-branch",
worktreePath: "/repo/stale-worktree",
deletedAt: null,
messages,
proposedPlans: [],
activities: [],
checkpoints: [],
} satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
const shell = {
...THREAD_SHELL,
environmentId: ENVIRONMENT_ID,
title: "Current thread",
branch: "current-branch",
worktreePath: "/repo/current-worktree",
messages: [
{
id: MessageId.make("message-user"),
threadId: v2Projection.thread.id,
runId,
nodeId: null,
role: "user" as const,
text: "Hello",
attachments: [],
streaming: false,
createdBy: "user" as const,
creationSource: "web" as const,
createdAt: now,
updatedAt: now,
},
],
updatedAt: now,
};
const merged = mergeEnvironmentThread(detail, shell);
const thread = presentThread(environmentId, projection);
expect(thread.projection).toBe(projection);
expect(thread.latestRun?.runId).toBe(runId);
expect(thread.runtime?.status).toBe("running");
expect(thread.runs).toHaveLength(1);
expect(thread.availableActions.canInterrupt).toBe(true);
expect(thread.messages[0]).toMatchObject({ text: "Hello", runId });
});
expect(merged).toMatchObject({
title: "Current thread",
branch: "current-branch",
worktreePath: "/repo/current-worktree",
it("keeps the complete payload for generic V2 work-item rendering", () => {
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const item = {
id: TurnItemId.make("item-dynamic"),
threadId: v2Projection.thread.id,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed" as const,
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "dynamic_tool" as const,
toolName: "custom_tool",
input: { nested: { value: 1 } },
output: { ok: true },
};
const projection = {
...v2Projection,
turnItems: [item],
visibleTurnItems: [
{
position: 0,
visibility: "local" as const,
sourceThreadId: v2Projection.thread.id,
sourceItemId: item.id,
item,
},
],
updatedAt: now,
};
const thread = presentThread(environmentId, projection);
expect(thread.workEntries[0]).toMatchObject({
itemType: "dynamic_tool",
label: "custom_tool",
structuredPayload: item,
});
expect(merged?.messages).toBe(messages);
});
it("preserves untouched project and thread identities across unrelated shell updates", () => {
const harness = makeHarness();
const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
const projectsAtom = harness.projects.projectsAtom;
const projectAtom = harness.projects.projectAtom({
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
});
const threadAtom = harness.threadShells.threadShellAtom({
environmentId: ENVIRONMENT_ID,
threadId: THREAD_ID,
});
const projectRefs = harness.registry.get(projectRefsAtom);
const threadRefs = harness.registry.get(threadRefsAtom);
const projects = harness.registry.get(projectsAtom);
const project = harness.registry.get(projectAtom);
const thread = harness.registry.get(threadAtom);
harness.registry.set(
harness.shellStateAtom,
AsyncResult.success(
shellState({
...SNAPSHOT,
snapshotSequence: 2,
threads: SNAPSHOT.threads.map((candidate) =>
candidate.id === OTHER_THREAD_ID
? { ...candidate, title: "Renamed other thread" }
: candidate,
),
}),
),
);
expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
expect(harness.registry.get(projectsAtom)).toBe(projects);
expect(harness.registry.get(projectAtom)).toBe(project);
expect(harness.registry.get(threadAtom)).toBe(thread);
});
it("preserves project-scoped thread collections across unrelated project updates", () => {
const harness = makeHarness();
const projectRef = {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
};
const refsByProjectAtom =
harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID);
const threads = harness.registry.get(threadsAtom);
expect(threads).toHaveLength(1);
expect(threads[0]?.id).toBe(THREAD_ID);
harness.registry.set(
harness.shellStateAtom,
AsyncResult.success(
shellState({
...SNAPSHOT,
snapshotSequence: 2,
threads: SNAPSHOT.threads.map((thread) =>
thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
),
}),
),
);
expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
expect(harness.registry.get(threadsAtom)).toBe(threads);
});
it("updates only the requested thread detail and preserves untouched field identities", () => {
const harness = makeHarness();
const threadRef = {
environmentId: ENVIRONMENT_ID,
threadId: THREAD_ID,
};
const otherThreadRef = {
environmentId: ENVIRONMENT_ID,
threadId: OTHER_THREAD_ID,
};
const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
const statusAtom = harness.threadDetails.statusAtom(threadRef);
const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
const otherValue = harness.registry.get(otherThreadDetailAtom);
const detail = {
...THREAD_SHELL,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
} satisfies OrchestrationThread;
harness.registry.set(
harness.threadStateAtom(THREAD_ID),
AsyncResult.success<EnvironmentThreadState>({
data: Option.some(detail),
status: "live",
error: Option.none(),
}),
);
const scopedDetail = harness.registry.get(threadDetailAtom);
const messages = harness.registry.get(messagesAtom);
const activities = harness.registry.get(activitiesAtom);
expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
expect(harness.registry.get(statusAtom)).toBe("live");
expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
harness.registry.set(
harness.threadStateAtom(THREAD_ID),
AsyncResult.success<EnvironmentThreadState>({
data: Option.some({
...detail,
session: {
threadId: THREAD_ID,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-06-01T00:01:00.000Z",
},
}),
status: "live",
error: Option.none(),
}),
);
expect(harness.registry.get(messagesAtom)).toBe(messages);
expect(harness.registry.get(activitiesAtom)).toBe(activities);
});
});
+705 -15
View File
@@ -1,25 +1,459 @@
import type {
ChatAttachment,
CheckpointId,
CheckpointRef,
CheckpointScopeId,
EnvironmentId,
OrchestrationMessage,
MessageId,
OrchestrationProjectShell,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadShell,
OrchestrationV2PlanArtifact,
OrchestrationV2ProviderCapabilities,
OrchestrationV2RunStatus,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadShell,
OrchestrationV2TurnItem,
PlanId,
ProjectId,
ProviderApprovalDecision,
ProviderInstanceId,
ProviderRequestKind,
RunId,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
export interface EnvironmentProject extends OrchestrationProjectShell {
readonly environmentId: EnvironmentId;
}
export interface EnvironmentThreadShell extends OrchestrationThreadShell {
/**
* A pristine V2 thread projection paired with the environment that produced it.
*
* Keep the projection nested so its identity and every structurally shared
* collection remain intact. This is the scoped detail boundary for rich V2
* consumers; it is intentionally not another presentation-shaped thread.
*/
export interface ScopedThreadProjection {
readonly environmentId: EnvironmentId;
readonly projection: OrchestrationV2ThreadProjection;
}
export type EnvironmentMessage = OrchestrationMessage;
export interface ThreadRunSummary {
readonly runId: RunId;
readonly status: OrchestrationV2RunStatus;
readonly requestedAt: string | null;
readonly startedAt: string | null;
readonly completedAt: string | null;
readonly assistantMessageId: MessageId | null;
readonly sourcePlanRef?: {
readonly threadId: ThreadId;
readonly planId: PlanId;
};
}
export interface EnvironmentThread extends OrchestrationThread {
export interface ThreadRuntimeSummary {
readonly status: OrchestrationV2RunStatus | "idle";
readonly activeRunId: RunId | null;
readonly providerInstanceId: ProviderInstanceId;
readonly providerName: string | null;
readonly lastError: string | null;
readonly updatedAt: string;
}
export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
}
export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
return (
status === "queued" || status === "starting" || status === "running" || status === "waiting"
);
}
export interface ThreadConversationMessage {
readonly id: MessageId;
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly runId: RunId | null;
readonly streaming: boolean;
readonly createdAt: string;
readonly updatedAt: string;
}
export interface ThreadProposedPlan {
readonly id: PlanId;
readonly runId: RunId | null;
readonly planMarkdown: string;
readonly status: OrchestrationV2PlanArtifact["status"];
readonly implementedAt: string | null;
readonly implementationThreadId: ThreadId | null;
readonly createdAt: string;
readonly updatedAt: string;
}
export interface ThreadTodoPlan {
readonly id: PlanId;
readonly runId: RunId | null;
readonly status: OrchestrationV2PlanArtifact["status"];
readonly explanation: string | null;
readonly steps: ReadonlyArray<{
readonly id: string;
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
readonly updatedAt: string;
}
export interface ThreadCheckpointSummary {
readonly checkpointId?: CheckpointId;
readonly scopeId?: CheckpointScopeId;
readonly runId: RunId;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
readonly status: "ready" | "missing" | "error" | "stale";
readonly files: ReadonlyArray<{
readonly path: string;
readonly kind: string;
readonly additions: number;
readonly deletions: number;
}>;
readonly assistantMessageId: MessageId | null;
readonly completedAt: string;
}
export interface ThreadPendingApproval {
readonly requestId: RuntimeRequestId;
readonly requestKind: ProviderRequestKind;
readonly createdAt: string;
readonly detail?: string;
readonly responseCapability: "live" | "not_resumable";
}
export interface ThreadUserInputQuestion {
readonly id: string;
readonly header: string;
readonly question: string;
readonly options: ReadonlyArray<{
readonly label: string;
readonly description: string;
}>;
readonly multiSelect: boolean;
}
export interface ThreadPendingUserInput {
readonly requestId: RuntimeRequestId;
readonly createdAt: string;
readonly questions: ReadonlyArray<ThreadUserInputQuestion>;
readonly responseCapability: "live" | "not_resumable";
}
export type ThreadWorkEntryTone = "thinking" | "tool" | "info" | "error";
export type ThreadWorkEntryStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
/**
* Stable parity presentation for a V2 turn item. `structuredPayload` always
* retains the complete source item so generic rendering never loses provider
* or tool data.
*/
export interface ThreadWorkEntry {
readonly id: string;
readonly createdAt: string;
readonly runId: RunId | null;
readonly label: string;
readonly detail?: string;
readonly command?: string;
readonly rawCommand?: string;
readonly changedFiles?: ReadonlyArray<string>;
readonly tone: ThreadWorkEntryTone;
readonly toolTitle?: string;
readonly toolData?: unknown;
readonly itemType: OrchestrationV2TurnItem["type"];
readonly requestKind?: ProviderRequestKind;
readonly toolLifecycleStatus: ThreadWorkEntryStatus;
readonly structuredPayload: OrchestrationV2TurnItem;
}
export interface EnvironmentThreadShell {
readonly environmentId: EnvironmentId;
readonly id: ThreadId;
readonly projectId: ProjectId;
readonly title: string;
readonly providerInstanceId: ProviderInstanceId;
readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
readonly branch: string | null;
readonly worktreePath: string | null;
readonly lineage: OrchestrationV2ThreadShell["lineage"];
readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
readonly latestRun: ThreadRunSummary | null;
readonly runtime: ThreadRuntimeSummary | null;
readonly latestUserMessageAt: string | null;
readonly hasPendingApprovals: boolean;
readonly hasPendingUserInput: boolean;
readonly hasActionableProposedPlan: boolean;
readonly itemCount: number;
readonly visibleItemCount: number;
readonly createdAt: string;
readonly updatedAt: string;
readonly archivedAt: string | null;
readonly deletedAt: string | null;
readonly source: OrchestrationV2ThreadShell;
}
export interface EnvironmentThread extends EnvironmentThreadShell {
readonly projection: OrchestrationV2ThreadProjection;
readonly runs: ReadonlyArray<ThreadRunSummary>;
readonly capabilities: OrchestrationV2ProviderCapabilities | null;
readonly availableActions: {
readonly canSendMessage: boolean;
readonly canInterrupt: boolean;
readonly canRespondToApproval: boolean;
readonly canRespondToUserInput: boolean;
readonly canRollback: boolean;
readonly canArchive: boolean;
readonly canUnarchive: boolean;
readonly canDelete: boolean;
readonly canUpdateSettings: boolean;
};
readonly messages: ReadonlyArray<ThreadConversationMessage>;
readonly workEntries: ReadonlyArray<ThreadWorkEntry>;
readonly proposedPlans: ReadonlyArray<ThreadProposedPlan>;
readonly todoPlans: ReadonlyArray<ThreadTodoPlan>;
readonly pendingApprovals: ReadonlyArray<ThreadPendingApproval>;
readonly pendingUserInputs: ReadonlyArray<ThreadPendingUserInput>;
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
}
function iso(value: DateTime.Utc): string {
return DateTime.formatIso(value);
}
function nullableIso(value: DateTime.Utc | null): string | null {
return value === null ? null : iso(value);
}
function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
return (
status === "completed" ||
status === "interrupted" ||
status === "failed" ||
status === "cancelled" ||
status === "rolled_back"
);
}
function workEntryStatus(item: OrchestrationV2TurnItem): ThreadWorkEntryStatus {
switch (item.status) {
case "pending":
case "running":
case "waiting":
return "inProgress";
case "completed":
return "completed";
case "failed":
return "failed";
case "cancelled":
case "interrupted":
return "stopped";
}
}
function workEntryTone(item: OrchestrationV2TurnItem): ThreadWorkEntryTone {
if (item.status === "failed") return "error";
if (item.type === "reasoning") return "thinking";
switch (item.type) {
case "command_execution":
case "file_change":
case "file_search":
case "web_search":
case "dynamic_tool":
case "subagent":
return "tool";
default:
return "info";
}
}
function summarizeWorkItem(item: OrchestrationV2TurnItem): {
readonly label: string;
readonly detail?: string;
readonly command?: string;
readonly rawCommand?: string;
readonly changedFiles?: ReadonlyArray<string>;
readonly toolTitle?: string;
readonly toolData?: unknown;
readonly requestKind?: ProviderRequestKind;
} {
const title = item.title?.trim() || null;
switch (item.type) {
case "reasoning":
return { label: title ?? "Thinking", ...(item.text ? { detail: item.text } : {}) };
case "command_execution":
return {
label: title ?? "Ran command",
command: item.input,
rawCommand: item.input,
...(item.output ? { detail: item.output } : {}),
toolTitle: title ?? "Command",
toolData: item,
};
case "file_change":
return {
label: title ?? `Changed ${item.fileName}`,
changedFiles: [item.fileName],
...(item.diffStr ? { detail: item.diffStr } : {}),
toolTitle: title ?? "File change",
toolData: item,
};
case "file_search":
return {
label: title ?? "Searched files",
...(item.pattern ? { detail: item.pattern } : {}),
toolTitle: title ?? "File search",
toolData: item,
};
case "web_search":
return {
label: title ?? "Searched the web",
...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
toolTitle: title ?? "Web search",
toolData: item,
};
case "approval_request":
return {
label: title ?? "Approval requested",
...(item.prompt ? { detail: item.prompt } : {}),
requestKind: item.requestKind,
toolData: item,
};
case "user_input_request":
return {
label: title ?? "Input requested",
detail: item.questions.map((question) => question.question).join("\n"),
toolData: item,
};
case "checkpoint":
return {
label: title ?? "Checkpoint captured",
changedFiles: item.files.map((file) => file.path),
toolData: item,
};
case "run_interrupt_request":
return { label: title ?? "Interrupt requested", detail: item.message, toolData: item };
case "run_interrupt_result":
return { label: title ?? "Run interrupted", detail: item.message, toolData: item };
case "compaction":
return {
label: title ?? "Context compacted",
...(item.summary ? { detail: item.summary } : {}),
toolData: item,
};
case "handoff":
return {
label: title ?? "Context handed off",
...(item.summary ? { detail: item.summary } : {}),
toolData: item,
};
case "fork":
return { label: title ?? "Thread forked", detail: item.targetThreadId, toolData: item };
case "subagent":
return {
label: title ?? "Subagent",
detail: item.result ?? item.prompt,
toolTitle: title ?? "Subagent",
toolData: item,
};
case "dynamic_tool":
return {
label: title ?? item.toolName ?? "Tool call",
toolTitle: title ?? item.toolName ?? "Tool",
toolData: { input: item.input, output: item.output },
};
case "user_message":
return { label: title ?? "User message", detail: item.text, toolData: item };
case "assistant_message":
return { label: title ?? "Assistant message", detail: item.text, toolData: item };
case "proposed_plan":
return { label: title ?? "Proposed plan", detail: item.markdown, toolData: item };
case "todo_list":
return {
label: title ?? "Plan updated",
detail: item.steps.map((step) => step.text).join("\n"),
toolData: item,
};
}
}
function presentWorkEntries(
projection: OrchestrationV2ThreadProjection,
): ReadonlyArray<ThreadWorkEntry> {
return projection.visibleTurnItems
.filter(
({ item }) =>
item.type !== "user_message" &&
item.type !== "assistant_message" &&
item.type !== "proposed_plan" &&
item.type !== "todo_list",
)
.map(({ item }) => {
const summary = summarizeWorkItem(item);
return {
id: item.id,
createdAt: iso(item.startedAt ?? item.updatedAt),
runId: item.runId,
...summary,
tone: workEntryTone(item),
itemType: item.type,
toolLifecycleStatus: workEntryStatus(item),
structuredPayload: item,
} satisfies ThreadWorkEntry;
});
}
function presentRuns(projection: OrchestrationV2ThreadProjection): ReadonlyArray<ThreadRunSummary> {
return projection.runs
.toSorted((left, right) => left.ordinal - right.ordinal)
.map((run) => ({
runId: run.id,
status: run.status,
requestedAt: iso(run.requestedAt),
startedAt: nullableIso(run.startedAt),
completedAt: nullableIso(run.completedAt),
assistantMessageId:
projection.messages.findLast(
(message) => message.runId === run.id && message.role === "assistant",
)?.id ?? null,
...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
}));
}
function presentLatestRun(projection: OrchestrationV2ThreadProjection): ThreadRunSummary | null {
return presentRuns(projection).at(-1) ?? null;
}
function presentRuntime(
shell: OrchestrationV2ThreadShell,
projection?: OrchestrationV2ThreadProjection,
): ThreadRuntimeSummary | null {
const latestRun = projection === undefined ? null : presentLatestRun(projection);
const hasRuntime = shell.latestRunId !== null || shell.activeProviderThreadId !== null;
if (!hasRuntime && latestRun === null) return null;
const providerSession = projection?.providerSessions.findLast(
(session) => session.providerInstanceId === shell.providerInstanceId,
);
return {
status: latestRun?.status ?? shell.status,
activeRunId: shell.activeRunId,
providerInstanceId: shell.providerInstanceId,
providerName: providerSession?.driver ?? null,
lastError: providerSession?.lastError ?? null,
updatedAt: iso(projection?.updatedAt ?? shell.updatedAt),
};
}
export function scopeProject(
@@ -29,25 +463,281 @@ export function scopeProject(
return { ...project, environmentId };
}
export function scopeThreadShell(
export function presentThreadShell(
environmentId: EnvironmentId,
thread: OrchestrationThreadShell,
thread: OrchestrationV2ThreadShell,
): EnvironmentThreadShell {
return { ...thread, environmentId };
const updatedAt = iso(thread.updatedAt);
const latestRun =
thread.latestRunId === null
? null
: ({
runId: thread.latestRunId,
status: thread.status === "idle" ? "completed" : thread.status,
requestedAt: null,
startedAt: null,
completedAt:
thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,
assistantMessageId: null,
} satisfies ThreadRunSummary);
return {
environmentId,
id: thread.id,
projectId: thread.projectId,
title: thread.title,
providerInstanceId: thread.providerInstanceId,
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
branch: thread.branch,
worktreePath: thread.worktreePath,
lineage: thread.lineage,
forkedFrom: thread.forkedFrom,
activeProviderThreadId: thread.activeProviderThreadId,
latestRun,
runtime: presentRuntime(thread),
latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
hasPendingApprovals:
thread.pendingRuntimeRequest !== null &&
thread.pendingRuntimeRequest.kind !== "user_input" &&
thread.pendingRuntimeRequest.kind !== "auth_refresh",
hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
hasActionableProposedPlan: thread.hasActionableProposedPlan,
itemCount: thread.itemCount,
visibleItemCount: thread.visibleItemCount,
createdAt: iso(thread.createdAt),
updatedAt,
archivedAt: nullableIso(thread.archivedAt),
deletedAt: nullableIso(thread.deletedAt),
source: thread,
};
}
export function scopeThread(
export const scopeThreadShell = presentThreadShell;
function presentMessages(
projection: OrchestrationV2ThreadProjection,
): ReadonlyArray<ThreadConversationMessage> {
return projection.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
attachments: message.attachments,
runId: message.runId,
streaming: message.streaming,
createdAt: iso(message.createdAt),
updatedAt: iso(message.updatedAt),
}));
}
function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
const item = projection.turnItems.findLast(
(candidate) =>
(candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
candidate.planId === planId,
);
return iso(item?.updatedAt ?? projection.updatedAt);
}
function presentProposedPlans(
projection: OrchestrationV2ThreadProjection,
): ReadonlyArray<ThreadProposedPlan> {
return projection.plans.flatMap((plan) => {
if (plan.kind !== "proposed_plan") return [];
const updatedAt = planItemTime(projection, plan.id);
return [
{
id: plan.id,
runId: plan.runId,
planMarkdown: plan.markdown,
status: plan.status,
implementedAt: plan.status === "completed" ? updatedAt : null,
implementationThreadId: null,
createdAt: updatedAt,
updatedAt,
} satisfies ThreadProposedPlan,
];
});
}
function presentTodoPlans(
projection: OrchestrationV2ThreadProjection,
): ReadonlyArray<ThreadTodoPlan> {
return projection.plans.flatMap((plan) => {
if (plan.kind !== "todo_list") return [];
return [
{
id: plan.id,
runId: plan.runId,
status: plan.status,
explanation: plan.explanation ?? null,
steps: plan.steps.map((step) => ({
id: step.id,
step: step.text,
status: step.status === "running" ? "inProgress" : step.status,
})),
updatedAt: planItemTime(projection, plan.id),
} satisfies ThreadTodoPlan,
];
});
}
function presentPendingRequests(projection: OrchestrationV2ThreadProjection): {
readonly approvals: ReadonlyArray<ThreadPendingApproval>;
readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
} {
const approvals: ThreadPendingApproval[] = [];
const userInputs: ThreadPendingUserInput[] = [];
for (const request of projection.runtimeRequests) {
if (request.status !== "pending") continue;
const responseCapability = request.responseCapability.type;
if (request.kind === "user_input") {
const item = projection.turnItems.findLast(
(candidate) =>
candidate.type === "user_input_request" && candidate.requestId === request.id,
);
if (item === undefined || item.type !== "user_input_request") continue;
userInputs.push({
requestId: request.id,
createdAt: iso(request.createdAt),
questions: item.questions.map((question) => ({ ...question, multiSelect: false })),
responseCapability,
});
continue;
}
if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
const item = projection.turnItems.findLast(
(candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
);
approvals.push({
requestId: request.id,
requestKind: request.kind,
createdAt: iso(request.createdAt),
...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
responseCapability,
});
}
return { approvals, userInputs };
}
function presentCheckpoints(
projection: OrchestrationV2ThreadProjection,
): ReadonlyArray<ThreadCheckpointSummary> {
return projection.checkpoints.flatMap((checkpoint) => {
if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return [];
const assistantMessageId =
projection.messages.findLast(
(message) => message.runId === checkpoint.runId && message.role === "assistant",
)?.id ?? null;
return [
{
checkpointId: checkpoint.id,
scopeId: checkpoint.scopeId,
runId: checkpoint.runId,
checkpointTurnCount: checkpoint.appRunOrdinal,
checkpointRef: checkpoint.ref,
status: checkpoint.status,
files: checkpoint.files,
assistantMessageId,
completedAt: iso(checkpoint.capturedAt),
} satisfies ThreadCheckpointSummary,
];
});
}
export function presentThread(
environmentId: EnvironmentId,
thread: OrchestrationThread,
projection: OrchestrationV2ThreadProjection,
): EnvironmentThread {
return { ...thread, environmentId };
const shell = presentThreadShell(environmentId, {
...projection.thread,
latestRunId:
projection.runs.reduce<(typeof projection.runs)[number] | null>(
(latest, candidate) =>
latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,
null,
)?.id ?? null,
activeRunId:
projection.runs.findLast(
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
)?.id ?? null,
status: presentLatestRun(projection)?.status ?? "idle",
pendingRuntimeRequest:
projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null,
latestVisibleMessage:
projection.messages.length === 0
? null
: (() => {
const message = projection.messages.at(-1)!;
return {
id: message.id,
role: message.role,
text: message.text,
updatedAt: message.updatedAt,
};
})(),
latestUserMessageAt:
projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null,
hasActionableProposedPlan: projection.plans.some(
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
),
itemCount: projection.turnItems.length,
visibleItemCount: projection.visibleTurnItems.length,
});
const requests = presentPendingRequests(projection);
const proposedPlans = presentProposedPlans(projection);
const checkpoints = presentCheckpoints(projection);
const runs = presentRuns(projection);
const capabilities =
projection.providerSessions.findLast(
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
)?.capabilities ?? null;
const active = runs.some((run) => threadRunStatusIsActive(run.status));
const mutable = projection.thread.archivedAt === null && projection.thread.deletedAt === null;
return {
...shell,
latestRun: presentLatestRun(projection),
runtime: presentRuntime(shell.source, projection),
hasPendingApprovals: requests.approvals.length > 0,
hasPendingUserInput: requests.userInputs.length > 0,
hasActionableProposedPlan: proposedPlans.some((plan) => plan.status === "active"),
projection,
runs,
capabilities,
availableActions: {
canSendMessage: mutable,
canInterrupt: mutable && active && (capabilities?.turns.supportsInterrupt ?? true),
canRespondToApproval: requests.approvals.some(
(request) => request.responseCapability === "live",
),
canRespondToUserInput: requests.userInputs.some(
(request) => request.responseCapability === "live",
),
canRollback: mutable && checkpoints.some((checkpoint) => checkpoint.status === "ready"),
canArchive: projection.thread.archivedAt === null && projection.thread.deletedAt === null,
canUnarchive: projection.thread.archivedAt !== null && projection.thread.deletedAt === null,
canDelete: projection.thread.deletedAt === null,
canUpdateSettings: mutable,
},
messages: presentMessages(projection),
workEntries: presentWorkEntries(projection),
proposedPlans,
todoPlans: presentTodoPlans(projection),
pendingApprovals: requests.approvals,
pendingUserInputs: requests.userInputs,
checkpoints,
};
}
export function selectEnvironmentThreadShell(
snapshot: OrchestrationShellSnapshot | null,
snapshot: OrchestrationV2ShellSnapshot | null,
environmentId: EnvironmentId,
threadId: ThreadId,
): EnvironmentThreadShell | null {
const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;
return thread ? scopeThreadShell(environmentId, thread) : null;
return thread ? presentThreadShell(environmentId, thread) : null;
}
export function providerApprovalDecisionIsFinal(_decision: ProviderApprovalDecision): boolean {
return true;
}
@@ -1,4 +1,4 @@
import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
@@ -10,11 +10,11 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
return {
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
}),
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:full-thread-diff",
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
}),
threadSearch: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:thread-search",
@@ -24,7 +24,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
}),
archivedShellSnapshot: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:archived-shell-snapshot",
tag: ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot,
}),
};
}
@@ -1,10 +1,15 @@
import { describe, expect, it } from "vite-plus/test";
import {
type OrchestrationV2DomainEvent,
type OrchestrationV2Run,
type OrchestrationV2ThreadProjection,
type OrchestrationV2TurnItem,
MessageId,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
@@ -12,6 +17,47 @@ import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const threadId = ThreadId.make("thread-reducer");
const runId = RunId.make("run-reducer");
const run = {
id: runId,
threadId,
ordinal: 1,
providerInstanceId: ProviderInstanceId.make("codex"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
providerThreadId: null,
userMessageId: MessageId.make("message-reducer"),
rootNodeId: null,
activeAttemptId: null,
status: "completed",
requestedAt: now,
startedAt: now,
completedAt: now,
checkpointId: null,
contextHandoffId: null,
} satisfies OrchestrationV2Run;
function commandItem(id: string, output = "done"): OrchestrationV2TurnItem {
return {
id: TurnItemId.make(id),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "completed",
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "command_execution",
input: "pwd",
output,
exitCode: 0,
};
}
const emptyProjection = {
thread: {
id: threadId,
@@ -79,4 +125,112 @@ describe("applyOrchestrationV2ProjectionEvent", () => {
expect(applyOrchestrationV2ProjectionEvent(emptyProjection, event)).toBe(emptyProjection);
});
it("preserves visible row identity when run updates do not change membership", () => {
const item = commandItem("item-stable");
const visibleTurnItems = [
{
position: 0,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: item.id,
item,
},
];
const projection = {
...emptyProjection,
runs: [run],
turnItems: [item],
visibleTurnItems,
};
const event = {
id: "event-run-update",
type: "run.updated",
threadId,
runId,
occurredAt: now,
payload: { ...run, status: "completed" },
} as OrchestrationV2DomainEvent;
const next = applyOrchestrationV2ProjectionEvent(projection, event);
expect(next?.visibleTurnItems).toBe(visibleTurnItems);
expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]);
});
it("replaces only the updated visible item when membership is unchanged", () => {
const first = commandItem("item-first", "first");
const second = commandItem("item-second", "second");
const firstRow = {
position: 0,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: first.id,
item: first,
};
const secondRow = {
position: 1,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: second.id,
item: second,
};
const updated = commandItem("item-first", "streamed output");
const projection = {
...emptyProjection,
runs: [run],
turnItems: [first, second],
visibleTurnItems: [firstRow, secondRow],
};
const event = {
id: "event-item-update",
type: "turn-item.updated",
threadId,
runId,
occurredAt: now,
payload: updated,
} as OrchestrationV2DomainEvent;
const next = applyOrchestrationV2ProjectionEvent(projection, event);
expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems);
expect(next?.visibleTurnItems[0]).not.toBe(firstRow);
expect(next?.visibleTurnItems[0]?.item).toBe(updated);
expect(next?.visibleTurnItems[1]).toBe(secondRow);
});
it("removes only hidden local items while preserving inherited rows", () => {
const inherited = commandItem("item-inherited");
const local = commandItem("item-local");
const inheritedRow = {
position: 0,
visibility: "inherited" as const,
sourceThreadId: ThreadId.make("thread-source"),
sourceItemId: inherited.id,
item: inherited,
};
const localRow = {
position: 1,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: local.id,
item: local,
};
const projection = {
...emptyProjection,
runs: [run],
turnItems: [local],
visibleTurnItems: [inheritedRow, localRow],
};
const event = {
id: "event-run-rollback",
type: "run.updated",
threadId,
runId,
occurredAt: now,
payload: { ...run, status: "rolled_back" },
} as OrchestrationV2DomainEvent;
const next = applyOrchestrationV2ProjectionEvent(projection, event);
expect(next?.visibleTurnItems).toEqual([inheritedRow]);
expect(next?.visibleTurnItems[0]).toBe(inheritedRow);
});
});
@@ -20,9 +20,15 @@ function removeVisibleItem(
rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
sourceItemId: OrchestrationV2TurnItem["id"],
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
return rows
.filter((row) => row.sourceItemId !== sourceItemId)
.map((row, position) => ({ ...row, position }));
const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
if (index === -1) return rows;
return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
}
function renumberVisibleItems(
rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
}
function shouldShowLocalTurnItem(
@@ -39,9 +45,18 @@ function shouldShowLocalTurnItem(
function activeVisibleTurnItems(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
return projection.visibleTurnItems
.filter((row) => row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item))
.map((row, position) => ({ ...row, position }));
const rows = projection.visibleTurnItems;
let next: Array<(typeof rows)[number]> | null = null;
for (let index = 0; index < rows.length; index += 1) {
const row = rows[index]!;
const keep = row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item);
if (!keep) {
next ??= rows.slice(0, index);
continue;
}
next?.push(row);
}
return next === null ? rows : renumberVisibleItems(next);
}
function upsertVisibleTurnItem(
@@ -57,9 +72,19 @@ function upsertVisibleTurnItem(
sourceItemId: item.id,
item,
};
return index === -1
? [...rows, next]
: rows.map((row, rowIndex) => (rowIndex === index ? next : row));
if (index === -1) return [...rows, next];
const previous = rows[index]!;
if (
previous.visibility === next.visibility &&
previous.sourceThreadId === next.sourceThreadId &&
previous.sourceItemId === next.sourceItemId &&
previous.item === item
) {
return rows;
}
const updated = [...rows];
updated[index] = next;
return updated;
}
/** Applies one committed event to a matching thread projection. */
@@ -0,0 +1,104 @@
import {
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationProjectShell,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
export const v2Now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
export const v2ProjectId = ProjectId.make("project-v2");
export const v2ThreadId = ThreadId.make("thread-v2");
export const v2ProviderInstanceId = ProviderInstanceId.make("codex");
export const v2Project: OrchestrationProjectShell = {
id: v2ProjectId,
title: "Project",
workspaceRoot: "/workspace/project",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-20T00:00:00.000Z",
updatedAt: "2026-06-20T00:00:00.000Z",
};
export const v2ThreadShell: OrchestrationV2ThreadShell = {
id: v2ThreadId,
projectId: v2ProjectId,
title: "Thread",
providerInstanceId: v2ProviderInstanceId,
modelSelection: { instanceId: v2ProviderInstanceId, model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: { rootThreadId: v2ThreadId, parentThreadId: null, relationshipToParent: null },
forkedFrom: null,
createdBy: "user",
creationSource: "web",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: null,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
deletedAt: null,
};
export const v2Projection: OrchestrationV2ThreadProjection = {
thread: {
id: v2ThreadShell.id,
projectId: v2ThreadShell.projectId,
title: v2ThreadShell.title,
providerInstanceId: v2ThreadShell.providerInstanceId,
modelSelection: v2ThreadShell.modelSelection,
runtimeMode: v2ThreadShell.runtimeMode,
interactionMode: v2ThreadShell.interactionMode,
branch: v2ThreadShell.branch,
worktreePath: v2ThreadShell.worktreePath,
activeProviderThreadId: v2ThreadShell.activeProviderThreadId,
lineage: v2ThreadShell.lineage,
forkedFrom: v2ThreadShell.forkedFrom,
createdBy: v2ThreadShell.createdBy,
creationSource: v2ThreadShell.creationSource,
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
deletedAt: null,
},
runs: [],
attempts: [],
nodes: [],
subagents: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runtimeRequests: [],
messages: [],
plans: [],
turnItems: [],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
contextTransfers: [],
visibleTurnItems: [],
updatedAt: v2Now,
};
export const v2ShellSnapshot: OrchestrationV2ShellSnapshot = {
schemaVersion: 1,
snapshotSequence: 0,
projects: [v2Project],
threads: [v2ThreadShell],
archivedThreads: [],
};
@@ -1,7 +1,7 @@
import type {
EnvironmentId,
OrchestrationProjectShell,
OrchestrationShellSnapshot,
OrchestrationV2ShellSnapshot,
ProjectId,
ScopedProjectRef,
} from "@t3tools/contracts";
@@ -19,7 +19,7 @@ export function createEnvironmentProjectAtoms(input: {
readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
readonly snapshotAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<OrchestrationShellSnapshot | null>;
) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
}) {
const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make(
@@ -1,8 +1,8 @@
import {
EnvironmentId,
ORCHESTRATION_WS_METHODS,
type OrchestrationShellSnapshot,
type OrchestrationShellStreamItem,
ORCHESTRATION_V2_WS_METHODS,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ShellStreamItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -22,7 +22,8 @@ import * as ConnectionWakeups from "../connection/wakeups.ts";
import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
import { makeEnvironmentShellState } from "./shell.ts";
import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -31,20 +32,9 @@ const TARGET = new PrimaryConnectionTarget({
wsBaseUrl: "wss://environment.example.test",
});
const PREPARED: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
httpBaseUrl: TARGET.httpBaseUrl,
socketUrl: TARGET.wsBaseUrl,
httpAuthorization: null,
target: TARGET,
};
const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 1,
projects: [],
threads: [],
updatedAt: "2026-06-06T00:00:00.000Z",
};
function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
@@ -60,9 +50,9 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
describe("environment shell synchronization", () => {
it.effect("publishes live state before persistence and preserves it when ready", () =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
const client = {
[ORCHESTRATION_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
@@ -2,11 +2,13 @@ import type { ServerConfig } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Option from "effect/Option";
import * as DateTime from "effect/DateTime";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { PrimaryConnectionTarget } from "../connection/model.ts";
import type { EnvironmentShellState } from "./shell.ts";
import { createEnvironmentServerConfigsAtom, createEnvironmentShellSummaryAtom } from "./shell.ts";
import { v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const OTHER_ENVIRONMENT_ID = EnvironmentId.make("environment-2");
@@ -34,10 +36,16 @@ function shellState(input: {
input.updatedAt === undefined
? Option.none()
: Option.some({
schemaVersion: 1,
snapshotSequence: input.snapshotSequence ?? 1,
updatedAt: input.updatedAt,
projects: [],
threads: [],
threads: [
{
...v2ThreadShell,
updatedAt: DateTime.makeUnsafe(input.updatedAt),
},
],
archivedThreads: [],
}),
status: input.status,
error: input.error === undefined ? Option.none() : Option.some(input.error),
+31 -62
View File
@@ -1,11 +1,12 @@
import {
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_V2_WS_METHODS,
type EnvironmentId,
type OrchestrationShellSnapshot,
type OrchestrationShellStreamItem,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ShellStreamItem,
type ServerConfig,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
@@ -29,7 +30,7 @@ import { followStreamInEnvironment } from "./runtime.ts";
export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
export interface EnvironmentShellState {
readonly snapshot: Option.Option<OrchestrationShellSnapshot>;
readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
readonly status: EnvironmentShellStatus;
readonly error: Option.Option<string>;
}
@@ -41,7 +42,7 @@ const EMPTY_SHELL_STATE: EnvironmentShellState = {
};
function shellStatusForSnapshot(
snapshot: Option.Option<OrchestrationShellSnapshot>,
snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
): EnvironmentShellStatus {
return Option.isSome(snapshot) ? "cached" : "empty";
}
@@ -61,7 +62,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
environmentId,
...safeErrorLogAttributes(error),
}),
Effect.as(Option.none<OrchestrationShellSnapshot>()),
Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
),
),
);
@@ -70,11 +71,10 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
status: shellStatusForSnapshot(cachedSnapshot),
error: Option.none(),
});
const awaitingCompletion = yield* Ref.make(false);
const persistence = yield* Queue.sliding<OrchestrationShellSnapshot>(1);
const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
const persist = Effect.fn("EnvironmentShellState.persist")(function* (
snapshot: OrchestrationShellSnapshot,
snapshot: OrchestrationV2ShellSnapshot,
) {
yield* cache.saveShell(environmentId, snapshot).pipe(
Effect.catch((error) =>
@@ -133,7 +133,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
);
const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
item: OrchestrationShellStreamItem,
item: OrchestrationV2ShellStreamItem,
) {
if (item.kind === "synchronized") {
yield* Ref.set(awaitingCompletion, false);
@@ -169,56 +169,13 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
yield* Queue.offer(persistence, nextSnapshot);
});
const foregroundResubscriptions = Option.match(wakeups, {
onNone: () => Stream.never,
onSome: (service) =>
service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
});
yield* setSynchronizing;
yield* Effect.forkScoped(
subscribeDynamic(
ORCHESTRATION_WS_METHODS.subscribeShell,
Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
const supportsCompletionMarker = yield* session.initialConfig.pipe(
Effect.map((config) => config.shellResumeCompletionMarker === true),
Effect.orElseSucceed(() => false),
);
yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
yield* setSynchronizing;
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
SubscriptionRef.changes(supervisor.prepared).pipe(
Stream.filter(Option.isSome),
Stream.map((value) => value.value),
Stream.runHead,
Effect.map(Option.getOrThrow),
),
}),
),
);
const httpSnapshot = yield* snapshotLoader.load(prepared);
if (Option.isSome(httpSnapshot)) {
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
return {
afterSequence: httpSnapshot.value.snapshotSequence,
...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
};
}
return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
}),
{
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
retryExpectedFailureAfter: "250 millis",
resubscribe: foregroundResubscriptions,
},
).pipe(Stream.runForEach(applyItem)),
);
yield* subscribe(
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
{},
{
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
},
).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
yield* SubscriptionRef.changes(supervisor.state).pipe(
Stream.runForEach((connectionState) => {
switch (connectionProjectionPhase(connectionState)) {
@@ -314,8 +271,20 @@ export function createEnvironmentShellSummaryAtom(input: {
continue;
}
hasSnapshot = true;
const updatedAt = state.snapshot.value.updatedAt;
if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
const snapshot = state.snapshot.value;
const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<string | null>(
(latest, thread) => {
const value = DateTime.formatIso(thread.updatedAt);
return latest === null || value > latest ? value : latest;
},
snapshot.projects.reduce<string | null>((latest, project) => {
return latest === null || project.updatedAt > latest ? project.updatedAt : latest;
}, null),
);
if (
updatedAt !== null &&
(latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt)
) {
latestSnapshotUpdatedAt = updatedAt;
}
}
@@ -1,185 +1,84 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
const baseSnapshot: OrchestrationShellSnapshot = {
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-04-01T00:00:00.000Z",
};
const stubProject = {
id: ProjectId.make("project-1"),
title: "Test Project",
workspaceRoot: "/workspace/test",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
} as const;
const stubThread = {
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Test Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
session: null,
} as const;
describe("applyShellStreamEvent", () => {
it("ignores stale project upserts without mutating the snapshot", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
it("ignores stale project updates without mutating the snapshot", () => {
const snapshotWithProject = {
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [stubProject],
projects: [v2Project],
};
for (const sequence of [3, 4]) {
const next = applyShellStreamEvent(snapshotWithProject, {
kind: "project-upserted",
kind: "project.updated",
sequence,
project: { ...stubProject, title: "Stale Title" },
project: { ...v2Project, title: "Stale Title" },
});
expect(next).toBe(snapshotWithProject);
expect(next.snapshotSequence).toBe(4);
expect(next.projects[0]?.title).toBe("Test Project");
expect(next.projects[0]?.title).toBe(v2Project.title);
}
});
describe("project-upserted", () => {
it("adds a new project", () => {
const event: OrchestrationShellStreamEvent = {
kind: "project-upserted",
sequence: 1,
project: stubProject,
};
const next = applyShellStreamEvent(baseSnapshot, event);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-1");
expect(next.snapshotSequence).toBe(1);
it("applies project updates and removals", () => {
const updated = applyShellStreamEvent(v2ShellSnapshot, {
kind: "project.updated",
sequence: 1,
project: { ...v2Project, title: "Updated" },
});
expect(updated.projects[0]?.title).toBe("Updated");
expect(updated.snapshotSequence).toBe(1);
it("updates an existing project", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
projects: [stubProject],
};
const updatedProject = { ...stubProject, title: "Updated Title" };
const event: OrchestrationShellStreamEvent = {
kind: "project-upserted",
sequence: 2,
project: updatedProject,
};
const next = applyShellStreamEvent(snapshotWithProject, event);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.title).toBe("Updated Title");
expect(next.snapshotSequence).toBe(2);
const removed = applyShellStreamEvent(updated, {
kind: "project.removed",
sequence: 2,
projectId: ProjectId.make(v2Project.id),
});
expect(removed.projects).toEqual([]);
});
describe("project-removed", () => {
it("removes a project by id", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
projects: [stubProject],
};
const event: OrchestrationShellStreamEvent = {
kind: "project-removed",
sequence: 3,
projectId: ProjectId.make("project-1"),
};
const next = applyShellStreamEvent(snapshotWithProject, event);
expect(next.projects).toHaveLength(0);
expect(next.snapshotSequence).toBe(3);
it("moves a thread between active and archive without duplicating it", () => {
const archived = applyShellStreamEvent(v2ShellSnapshot, {
kind: "thread.updated",
sequence: 3,
location: "archive",
thread: { ...v2ThreadShell, archivedAt: v2ThreadShell.updatedAt },
});
expect(archived.threads).toEqual([]);
expect(archived.archivedThreads).toHaveLength(1);
const active = applyShellStreamEvent(archived, {
kind: "thread.updated",
sequence: 4,
location: "active",
thread: v2ThreadShell,
});
expect(active.threads).toHaveLength(1);
expect(active.archivedThreads).toEqual([]);
});
describe("thread-upserted", () => {
it("adds a new thread", () => {
const event: OrchestrationShellStreamEvent = {
kind: "thread-upserted",
sequence: 4,
thread: stubThread,
};
const next = applyShellStreamEvent(baseSnapshot, event);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-1");
expect(next.snapshotSequence).toBe(4);
});
it("updates an existing thread", () => {
const snapshotWithThread: OrchestrationShellSnapshot = {
...baseSnapshot,
threads: [stubThread],
};
const updatedThread = { ...stubThread, title: "Updated Thread" };
const event: OrchestrationShellStreamEvent = {
kind: "thread-upserted",
sequence: 5,
thread: updatedThread,
};
const next = applyShellStreamEvent(snapshotWithThread, event);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.title).toBe("Updated Thread");
it("removes a thread from either collection", () => {
const next = applyShellStreamEvent(v2ShellSnapshot, {
kind: "thread.removed",
sequence: 5,
location: "active",
threadId: ThreadId.make(v2ThreadShell.id),
});
expect(next.threads).toEqual([]);
expect(next.snapshotSequence).toBe(5);
});
describe("thread-removed", () => {
it("removes a thread by id", () => {
const snapshotWithThread: OrchestrationShellSnapshot = {
...baseSnapshot,
threads: [stubThread],
};
it("leaves unknown future events unchanged", () => {
const next = applyShellStreamEvent(
v2ShellSnapshot,
{ kind: "future.event", sequence: 99 } as never,
);
const event: OrchestrationShellStreamEvent = {
kind: "thread-removed",
sequence: 6,
threadId: ThreadId.make("thread-1"),
};
const next = applyShellStreamEvent(snapshotWithThread, event);
expect(next.threads).toHaveLength(0);
expect(next.snapshotSequence).toBe(6);
});
});
it("returns original snapshot for unrecognized event kinds", () => {
const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any;
const next = applyShellStreamEvent(baseSnapshot, unknownEvent);
expect(next).toBe(baseSnapshot);
expect(next).toBe(v2ShellSnapshot);
});
});
@@ -1,43 +1,58 @@
import * as Arr from "effect/Array";
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
import type {
OrchestrationV2ShellSnapshot,
OrchestrationV2ShellStreamItem,
} from "@t3tools/contracts";
/**
* Reduce a single shell stream event into an existing snapshot, returning a new
* snapshot with the event's changes applied. This is a pure reducer that both
* web and mobile can use to keep their local shell snapshot in sync.
*
* Returns the original snapshot reference unchanged if the event is not
* recognized (forward-compatible).
*/
function upsertById<T extends { readonly id: unknown }>(
items: ReadonlyArray<T>,
item: T,
): ReadonlyArray<T> {
const index = items.findIndex((candidate) => candidate.id === item.id);
if (index === -1) return [...items, item];
return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate));
}
/** Applies one committed V2 shell delta while preserving active/archive exclusivity. */
export function applyShellStreamEvent(
snapshot: OrchestrationShellSnapshot,
event: OrchestrationShellStreamEvent,
): OrchestrationShellSnapshot {
snapshot: OrchestrationV2ShellSnapshot,
event: Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>,
): OrchestrationV2ShellSnapshot {
if (event.sequence <= snapshot.snapshotSequence) return snapshot;
switch (event.kind) {
case "project-upserted": {
const projects = snapshot.projects.some((p) => p.id === event.project.id)
? Arr.map(snapshot.projects, (p) => (p.id === event.project.id ? event.project : p))
: Arr.append(snapshot.projects, event.project);
return { ...snapshot, projects, snapshotSequence: event.sequence };
}
case "project-removed":
case "project.updated":
return {
...snapshot,
projects: Arr.filter(snapshot.projects, (p) => p.id !== event.projectId),
projects: upsertById(snapshot.projects, event.project),
snapshotSequence: event.sequence,
};
case "thread-upserted": {
const threads = snapshot.threads.some((t) => t.id === event.thread.id)
? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))
: Arr.append(snapshot.threads, event.thread);
return { ...snapshot, threads, snapshotSequence: event.sequence };
}
case "thread-removed":
case "project.removed":
return {
...snapshot,
threads: Arr.filter(snapshot.threads, (t) => t.id !== event.threadId),
projects: snapshot.projects.filter((project) => project.id !== event.projectId),
snapshotSequence: event.sequence,
};
case "thread.updated": {
const withoutThread = (threads: OrchestrationV2ShellSnapshot["threads"]) =>
threads.filter((thread) => thread.id !== event.thread.id);
return {
...snapshot,
threads:
event.location === "active"
? upsertById(withoutThread(snapshot.threads), event.thread)
: withoutThread(snapshot.threads),
archivedThreads:
event.location === "archive"
? upsertById(withoutThread(snapshot.archivedThreads), event.thread)
: withoutThread(snapshot.archivedThreads),
snapshotSequence: event.sequence,
};
}
case "thread.removed":
return {
...snapshot,
threads: snapshot.threads.filter((thread) => thread.id !== event.threadId),
archivedThreads: snapshot.archivedThreads.filter((thread) => thread.id !== event.threadId),
snapshotSequence: event.sequence,
};
default:
@@ -1,4 +1,4 @@
import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
@@ -10,7 +10,7 @@ export function createEnvironmentSnapshotAtom<E>(
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
) {
return Atom.family((environmentId: EnvironmentId) =>
Atom.make((get): OrchestrationShellSnapshot | null =>
Atom.make((get): OrchestrationV2ShellSnapshot | null =>
Option.match(AsyncResult.value(get(shellStateAtom(environmentId))), {
onNone: () => null,
onSome: (state) => Option.getOrNull(state.snapshot),
@@ -54,6 +54,7 @@ export type {
SnoozeThreadInput,
StartThreadTurnInput,
StopThreadSessionInput,
ThreadCommandInput,
UnarchiveThreadInput,
UnsettleThreadInput,
UnsnoozeThreadInput,
@@ -0,0 +1,45 @@
import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { describe, expect, it } from "vite-plus/test";
import { v2Projection } from "./orchestrationV2TestFixtures.ts";
import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
import type { EnvironmentThreadState } from "./threads.ts";
const ref: ScopedThreadRef = {
environmentId: EnvironmentId.make("environment-detail"),
threadId: ThreadId.make(v2Projection.thread.id),
};
describe("createEnvironmentThreadDetailAtoms", () => {
it("adds environment scope while preserving the pristine projection", () => {
const initial: AsyncResult.AsyncResult<EnvironmentThreadState, never> = AsyncResult.success({
data: Option.some(v2Projection),
status: "cached",
error: Option.none(),
});
const sourceAtom = Atom.make(initial);
const details = createEnvironmentThreadDetailAtoms(() => sourceAtom);
const registry = AtomRegistry.make();
const thread = registry.get(details.threadAtom(ref));
expect(thread).toEqual({ environmentId: ref.environmentId, projection: v2Projection });
expect(thread?.projection).toBe(v2Projection);
expect(registry.get(details.visibleTurnItemsAtom(ref))).toBe(v2Projection.visibleTurnItems);
expect(registry.get(details.statusAtom(ref))).toBe("cached");
registry.set(
sourceAtom,
AsyncResult.success({
data: Option.some(v2Projection),
status: "synchronizing",
error: Option.none(),
}),
);
expect(registry.get(details.threadAtom(ref))).toBe(thread);
expect(registry.get(details.statusAtom(ref))).toBe("synchronizing");
registry.dispose();
});
});
+112 -125
View File
@@ -1,67 +1,48 @@
import type {
OrchestrationCheckpointSummary,
OrchestrationLatestTurn,
OrchestrationMessage,
OrchestrationProposedPlan,
OrchestrationSession,
OrchestrationThread,
OrchestrationThreadActivity,
ScopedThreadRef,
} from "@t3tools/contracts";
import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import type { EnvironmentThread, EnvironmentThreadShell } from "./models.ts";
import { scopeThread } from "./models.ts";
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
import type {
EnvironmentThread,
EnvironmentThreadShell,
ThreadCheckpointSummary,
ThreadConversationMessage,
ThreadPendingApproval,
ThreadPendingUserInput,
ThreadProposedPlan,
ThreadRunSummary,
ThreadRuntimeSummary,
ScopedThreadProjection,
ThreadWorkEntry,
} from "./models.ts";
import { presentThread } from "./models.ts";
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
import { parseThreadKey, threadKey } from "./entities.ts";
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);
const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);
const EMPTY_CHECKPOINTS: ReadonlyArray<OrchestrationCheckpointSummary> = 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_CHECKPOINTS: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
const EMPTY_APPROVALS: ReadonlyArray<ThreadPendingApproval> = Object.freeze([]);
const EMPTY_USER_INPUTS: ReadonlyArray<ThreadPendingUserInput> = Object.freeze([]);
const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
[],
);
/**
* Combine detail-only collections with the shell's authoritative thread metadata.
*
* Shell and detail subscriptions are intentionally independent. A cached detail can
* therefore briefly outlive a newer shell snapshot after reconnecting. Workspace
* consumers must use the shell branch/worktree/project fields so they do not target
* a stale checkout while retaining messages, activities, plans, and checkpoints
* from the detail subscription.
*/
/** Shell metadata wins over an independently cached detail projection. */
export function mergeEnvironmentThread(
detail: EnvironmentThread | null,
shell: EnvironmentThreadShell | null,
): EnvironmentThread | null {
if (detail === null || shell === null) {
return detail;
}
if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) {
return detail;
}
if (detail === null || shell === null) return detail;
if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) return detail;
return {
...detail,
environmentId: shell.environmentId,
id: shell.id,
projectId: shell.projectId,
title: shell.title,
modelSelection: shell.modelSelection,
runtimeMode: shell.runtimeMode,
interactionMode: shell.interactionMode,
branch: shell.branch,
worktreePath: shell.worktreePath,
latestTurn: shell.latestTurn,
createdAt: shell.createdAt,
updatedAt: shell.updatedAt,
archivedAt: shell.archivedAt,
settledOverride: shell.settledOverride,
settledAt: shell.settledAt,
snoozedUntil: shell.snoozedUntil,
snoozedAt: shell.snoozedAt,
session: shell.session,
...shell,
latestRun: detail.latestRun,
runtime: detail.runtime,
source: shell.source,
};
}
@@ -86,15 +67,13 @@ export function createEnvironmentThreadDetailAtoms<E>(
const threadDetailAtomFamily = Atom.family((key: string) => {
const ref = parseThreadKey(key);
let previousSource: OrchestrationThread | null = null;
let previousSource: OrchestrationV2ThreadProjection | null = null;
let previousValue: EnvironmentThread | null = null;
return Atom.make((get) => {
const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
if (source === previousSource) {
return previousValue;
}
if (source === previousSource) return previousValue;
previousSource = source;
previousValue = source === null ? null : scopeThread(ref.environmentId, source);
previousValue = source === null ? null : presentThread(ref.environmentId, source);
return previousValue;
}).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
@@ -102,88 +81,96 @@ export function createEnvironmentThreadDetailAtoms<E>(
);
});
const threadStatusAtomFamily = Atom.family((key: string) =>
const scopedThreadProjectionAtomFamily = Atom.family((key: string) => {
const ref = parseThreadKey(key);
let previousProjection: OrchestrationV2ThreadProjection | null = null;
let previousValue: ScopedThreadProjection | null = null;
return Atom.make((get) => {
const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
if (projection === previousProjection) return previousValue;
previousProjection = projection;
previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
return previousValue;
}).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`scoped-thread-projection:${key}`),
);
});
const visibleTurnItemsAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): OrchestrationV2ThreadProjection["visibleTurnItems"] =>
Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.visibleTurnItems ??
EMPTY_VISIBLE_TURN_ITEMS,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-visible-turn-items:${key}`),
),
);
const family = <A>(label: string, select: (thread: EnvironmentThread) => A, empty: A) =>
Atom.family((key: string) =>
Atom.make((get): A => {
const thread = get(threadDetailAtomFamily(key));
return thread === null ? empty : select(thread);
}).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-${label}:${key}`),
),
);
const messages = family("messages", (thread) => thread.messages, EMPTY_MESSAGES);
const workEntries = family("work-entries", (thread) => thread.workEntries, EMPTY_WORK_ENTRIES);
const proposedPlans = family(
"proposed-plans",
(thread) => thread.proposedPlans,
EMPTY_PROPOSED_PLANS,
);
const checkpoints = family("checkpoints", (thread) => thread.checkpoints, EMPTY_CHECKPOINTS);
const pendingApprovals = family(
"pending-approvals",
(thread) => thread.pendingApprovals,
EMPTY_APPROVALS,
);
const pendingUserInputs = family(
"pending-user-inputs",
(thread) => thread.pendingUserInputs,
EMPTY_USER_INPUTS,
);
const runtime = family<ThreadRuntimeSummary | null>("runtime", (thread) => thread.runtime, null);
const latestRun = family<ThreadRunSummary | null>(
"latest-run",
(thread) => thread.latestRun,
null,
);
const status = Atom.family((key: string) =>
Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-status:${key}`),
),
);
const threadErrorAtomFamily = Atom.family((key: string) =>
const error = Atom.family((key: string) =>
Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-error:${key}`),
),
);
const threadMessagesAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): ReadonlyArray<OrchestrationMessage> =>
get(threadDetailAtomFamily(key))?.messages ?? EMPTY_MESSAGES,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-messages:${key}`),
),
);
const threadActivitiesAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): ReadonlyArray<OrchestrationThreadActivity> =>
get(threadDetailAtomFamily(key))?.activities ?? EMPTY_ACTIVITIES,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-activities:${key}`),
),
);
const threadProposedPlansAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): ReadonlyArray<OrchestrationProposedPlan> =>
get(threadDetailAtomFamily(key))?.proposedPlans ?? EMPTY_PROPOSED_PLANS,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-proposed-plans:${key}`),
),
);
const threadCheckpointsAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): ReadonlyArray<OrchestrationCheckpointSummary> =>
get(threadDetailAtomFamily(key))?.checkpoints ?? EMPTY_CHECKPOINTS,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-checkpoints:${key}`),
),
);
const threadSessionAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): OrchestrationSession | null => get(threadDetailAtomFamily(key))?.session ?? null,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-session:${key}`),
),
);
const threadLatestTurnAtomFamily = Atom.family((key: string) =>
Atom.make(
(get): OrchestrationLatestTurn | null => get(threadDetailAtomFamily(key))?.latestTurn ?? null,
).pipe(
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
Atom.withLabel(`environment-thread-latest-turn:${key}`),
),
);
return {
stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
threadAtom: (ref: ScopedThreadRef) => scopedThreadProjectionAtomFamily(threadKey(ref)),
visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)),
statusAtom: (ref: ScopedThreadRef) => threadStatusAtomFamily(threadKey(ref)),
errorAtom: (ref: ScopedThreadRef) => threadErrorAtomFamily(threadKey(ref)),
messagesAtom: (ref: ScopedThreadRef) => threadMessagesAtomFamily(threadKey(ref)),
activitiesAtom: (ref: ScopedThreadRef) => threadActivitiesAtomFamily(threadKey(ref)),
proposedPlansAtom: (ref: ScopedThreadRef) => threadProposedPlansAtomFamily(threadKey(ref)),
checkpointsAtom: (ref: ScopedThreadRef) => threadCheckpointsAtomFamily(threadKey(ref)),
sessionAtom: (ref: ScopedThreadRef) => threadSessionAtomFamily(threadKey(ref)),
latestTurnAtom: (ref: ScopedThreadRef) => threadLatestTurnAtomFamily(threadKey(ref)),
statusAtom: (ref: ScopedThreadRef) => status(threadKey(ref)),
errorAtom: (ref: ScopedThreadRef) => error(threadKey(ref)),
messagesAtom: (ref: ScopedThreadRef) => messages(threadKey(ref)),
workEntriesAtom: (ref: ScopedThreadRef) => workEntries(threadKey(ref)),
proposedPlansAtom: (ref: ScopedThreadRef) => proposedPlans(threadKey(ref)),
checkpointsAtom: (ref: ScopedThreadRef) => checkpoints(threadKey(ref)),
pendingApprovalsAtom: (ref: ScopedThreadRef) => pendingApprovals(threadKey(ref)),
pendingUserInputsAtom: (ref: ScopedThreadRef) => pendingUserInputs(threadKey(ref)),
runtimeAtom: (ref: ScopedThreadRef) => runtime(threadKey(ref)),
latestRunAtom: (ref: ScopedThreadRef) => latestRun(threadKey(ref)),
};
}
@@ -1,767 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
CheckpointRef,
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import type { OrchestrationThread } from "@t3tools/contracts";
import { applyThreadDetailEvent } from "./threadReducer.ts";
const baseEventFields = {
eventId: EventId.make("event-1"),
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
} as const;
const baseThread: OrchestrationThread = {
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Test Thread",
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,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
describe("applyThreadDetailEvent", () => {
describe("project events", () => {
it("returns unchanged for project.created", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "project",
aggregateId: ProjectId.make("project-1"),
type: "project.created",
payload: {
projectId: ProjectId.make("project-1"),
title: "T3 Code",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
deletedAt: null,
},
} as any);
expect(result.kind).toBe("unchanged");
});
});
describe("thread.created", () => {
it("creates a fresh thread", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 1,
occurredAt: "2026-04-01T01:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-2"),
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-1"),
title: "New Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.id).toBe("thread-2");
expect(result.thread.title).toBe("New Thread");
expect(result.thread.branch).toBe("main");
expect(result.thread.messages).toEqual([]);
expect(result.thread.session).toBeNull();
}
});
});
describe("thread.deleted", () => {
it("returns deleted signal", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 2,
occurredAt: "2026-04-01T02:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.deleted",
payload: {
threadId: ThreadId.make("thread-1"),
deletedAt: "2026-04-01T02:00:00.000Z",
},
});
expect(result.kind).toBe("deleted");
});
});
describe("thread.archived / thread.unarchived", () => {
it("sets archivedAt and clears title regeneration", () => {
const regeneratingThread: OrchestrationThread = {
...baseThread,
titleRegeneration: {
requestId: CommandId.make("regenerate-title"),
startedAt: "2026-04-01T02:00:00.000Z",
},
};
const result = applyThreadDetailEvent(regeneratingThread, {
...baseEventFields,
sequence: 3,
occurredAt: "2026-04-01T03:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.archived",
payload: {
threadId: ThreadId.make("thread-1"),
archivedAt: "2026-04-01T03:00:00.000Z",
updatedAt: "2026-04-01T03:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.archivedAt).toBe("2026-04-01T03:00:00.000Z");
expect(result.thread.titleRegeneration).toBeNull();
}
});
it("clears archivedAt", () => {
const archivedThread = { ...baseThread, archivedAt: "2026-04-01T03:00:00.000Z" };
const result = applyThreadDetailEvent(archivedThread, {
...baseEventFields,
sequence: 4,
occurredAt: "2026-04-01T04:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.unarchived",
payload: {
threadId: ThreadId.make("thread-1"),
updatedAt: "2026-04-01T04:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.archivedAt).toBeNull();
}
});
});
describe("thread.settled / thread.unsettled", () => {
it("sets the settled override and timestamp", () => {
const settledAt = "2026-04-01T05:00:00.000Z";
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 5,
occurredAt: settledAt,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.settled",
payload: {
threadId: ThreadId.make("thread-1"),
settledAt,
updatedAt: settledAt,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.settledOverride).toBe("settled");
expect(result.thread.settledAt).toBe(settledAt);
}
});
it.each([
["user", "active"],
["activity", null],
] as const)("unsettles for %s with override %s", (reason, settledOverride) => {
const settledThread: OrchestrationThread = {
...baseThread,
settledOverride: "settled",
settledAt: "2026-04-01T05:00:00.000Z",
};
const updatedAt = "2026-04-01T06:00:00.000Z";
const result = applyThreadDetailEvent(settledThread, {
...baseEventFields,
sequence: 6,
occurredAt: updatedAt,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.unsettled",
payload: {
threadId: ThreadId.make("thread-1"),
reason,
updatedAt,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.settledOverride).toBe(settledOverride);
expect(result.thread.settledAt).toBeNull();
}
});
});
describe("thread.meta-updated", () => {
it("patches title and branch", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 5,
occurredAt: "2026-04-01T05:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.meta-updated",
payload: {
threadId: ThreadId.make("thread-1"),
title: "Updated Title",
branch: "feature/demo",
updatedAt: "2026-04-01T05:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.title).toBe("Updated Title");
expect(result.thread.branch).toBe("feature/demo");
// Model selection should be unchanged since it wasn't in the payload
expect(result.thread.modelSelection).toEqual(baseThread.modelSelection);
}
});
});
describe("thread.message-sent", () => {
it("appends a new message", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 6,
occurredAt: "2026-04-01T06:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-1"),
role: "user",
text: "Hello, world!",
turnId: null,
streaming: false,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
}
});
it("appends text for streaming messages", () => {
const threadWithMessage: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("msg-2"),
role: "assistant",
text: "Hello",
turnId: TurnId.make("turn-1"),
streaming: true,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:00:00.000Z",
},
],
};
const result = applyThreadDetailEvent(threadWithMessage, {
...baseEventFields,
sequence: 7,
occurredAt: "2026-04-01T06:01:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-2"),
role: "assistant",
text: ", world!",
turnId: TurnId.make("turn-1"),
streaming: true,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:01:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
}
});
it("updates latestTurn for assistant messages with a turn", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 8,
occurredAt: "2026-04-01T07:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-3"),
role: "assistant",
text: "Done.",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("completed");
expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3");
}
});
it("keeps latestTurn running for interim assistant messages while the session runs the turn", () => {
const threadWithRunningSession: OrchestrationThread = {
...baseThread,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T06:59:00.000Z",
},
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T06:59:00.000Z",
startedAt: "2026-04-01T06:59:00.000Z",
completedAt: null,
assistantMessageId: null,
},
};
const result = applyThreadDetailEvent(threadWithRunningSession, {
...baseEventFields,
sequence: 8,
occurredAt: "2026-04-01T07:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-3"),
role: "assistant",
text: "Interim commentary between tool calls.",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.state).toBe("running");
expect(result.thread.latestTurn?.completedAt).toBeNull();
}
});
});
describe("thread.session-set", () => {
it("settles a running latestTurn when the session leaves the running status", () => {
const threadWithRunningTurn: OrchestrationThread = {
...baseThread,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T07:00:00.000Z",
startedAt: "2026-04-01T07:00:00.000Z",
completedAt: null,
assistantMessageId: MessageId.make("msg-3"),
},
};
const result = applyThreadDetailEvent(threadWithRunningTurn, {
...baseEventFields,
sequence: 9,
occurredAt: "2026-04-01T08:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-set",
payload: {
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.state).toBe("completed");
expect(result.thread.latestTurn?.completedAt).toBe("2026-04-01T08:00:00.000Z");
}
});
it("updates session and latestTurn for a running session", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 9,
occurredAt: "2026-04-01T08:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-set",
payload: {
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.session?.status).toBe("running");
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("running");
}
});
});
describe("thread.session-stop-requested", () => {
it("marks session as stopped", () => {
const threadWithSession: OrchestrationThread = {
...baseThread,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
};
const result = applyThreadDetailEvent(threadWithSession, {
...baseEventFields,
sequence: 10,
occurredAt: "2026-04-01T09:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-stop-requested",
payload: {
threadId: ThreadId.make("thread-1"),
createdAt: "2026-04-01T09:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.session?.status).toBe("stopped");
expect(result.thread.session?.activeTurnId).toBeNull();
}
});
it("returns unchanged when no session exists", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 10,
occurredAt: "2026-04-01T09:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-stop-requested",
payload: {
threadId: ThreadId.make("thread-1"),
createdAt: "2026-04-01T09:00:00.000Z",
},
});
expect(result.kind).toBe("unchanged");
});
});
describe("thread.proposed-plan-upserted", () => {
it("adds a proposed plan", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 11,
occurredAt: "2026-04-01T10:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.proposed-plan-upserted",
payload: {
threadId: ThreadId.make("thread-1"),
proposedPlan: {
id: "plan-1",
turnId: TurnId.make("turn-1"),
planMarkdown: "## Plan\n- Do stuff",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-04-01T10:00:00.000Z",
updatedAt: "2026-04-01T10:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.proposedPlans).toHaveLength(1);
expect(result.thread.proposedPlans[0]?.id).toBe("plan-1");
}
});
});
describe("thread.activity-appended", () => {
it("adds an activity", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 12,
occurredAt: "2026-04-01T11:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-1"),
tone: "tool",
kind: "file-edit",
summary: "Edited src/index.ts",
payload: {},
turnId: TurnId.make("turn-1"),
createdAt: "2026-04-01T11:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.activities).toHaveLength(1);
expect(result.thread.activities[0]?.kind).toBe("file-edit");
}
});
it("preserves the complete activity history when live events arrive", () => {
const existingActivities = Array.from({ length: 129 }, (_, index) => ({
id: EventId.make(`activity-${index}`),
tone: "tool" as const,
kind: "command",
summary: `Ran command ${index}`,
payload: {},
turnId: TurnId.make("turn-1"),
sequence: index,
createdAt: "2026-04-01T11:00:00.000Z",
}));
const result = applyThreadDetailEvent(
{ ...baseThread, activities: existingActivities },
{
...baseEventFields,
sequence: 130,
occurredAt: "2026-04-01T11:01:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-1"),
activity: {
id: EventId.make("activity-129"),
tone: "tool",
kind: "command",
summary: "Ran command 129",
payload: {},
turnId: TurnId.make("turn-1"),
sequence: 129,
createdAt: "2026-04-01T11:01:00.000Z",
},
},
},
);
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.activities).toHaveLength(130);
expect(result.thread.activities[0]?.id).toBe("activity-0");
}
});
});
describe("thread.turn-diff-completed", () => {
it("adds a checkpoint and updates latestTurn", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 13,
occurredAt: "2026-04-01T12:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.turn-diff-completed",
payload: {
threadId: ThreadId.make("thread-1"),
turnId: TurnId.make("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("ref-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-3"),
completedAt: "2026-04-01T12:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.checkpoints).toHaveLength(1);
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
expect(result.thread.latestTurn?.state).toBe("completed");
}
});
});
describe("thread.reverted", () => {
it("filters entities to retained turns", () => {
const threadWithData: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("msg-1"),
role: "user",
text: "First",
turnId: null,
streaming: false,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
{
id: MessageId.make("msg-2"),
role: "assistant",
text: "Response 1",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T02:00:00.000Z",
updatedAt: "2026-04-01T02:00:00.000Z",
},
{
id: MessageId.make("msg-3"),
role: "assistant",
text: "Response 2",
turnId: TurnId.make("turn-2"),
streaming: false,
createdAt: "2026-04-01T03:00:00.000Z",
updatedAt: "2026-04-01T03:00:00.000Z",
},
],
checkpoints: [
{
turnId: TurnId.make("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("ref-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-2"),
completedAt: "2026-04-01T02:00:00.000Z",
},
{
turnId: TurnId.make("turn-2"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.make("ref-2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-3"),
completedAt: "2026-04-01T03:00:00.000Z",
},
],
};
const result = applyThreadDetailEvent(threadWithData, {
...baseEventFields,
sequence: 14,
occurredAt: "2026-04-01T04:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.reverted",
payload: {
threadId: ThreadId.make("thread-1"),
turnCount: 1,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
// turn-2 checkpoint is filtered out (turnCount 2 > revert target 1)
expect(result.thread.checkpoints).toHaveLength(1);
expect(result.thread.checkpoints[0]?.turnId).toBe("turn-1");
// msg-3 (turn-2) is filtered, msg-1 (no turn) and msg-2 (turn-1) remain
expect(result.thread.messages).toHaveLength(2);
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
}
});
});
describe("no-op events", () => {
it("returns unchanged for approval-response-requested", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 15,
occurredAt: "2026-04-01T13:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.approval-response-requested",
payload: {
threadId: ThreadId.make("thread-1"),
requestId: "req-1",
decision: "approve",
createdAt: "2026-04-01T13:00:00.000Z",
},
} as any);
expect(result.kind).toBe("unchanged");
});
});
});
@@ -1,599 +0,0 @@
import { pipe } from "effect/Function";
import * as Arr from "effect/Array";
import * as O from "effect/Order";
import type {
MessageId,
OrchestrationCheckpointSummary,
OrchestrationEvent,
OrchestrationLatestTurn,
OrchestrationMessage,
OrchestrationSession,
OrchestrationThread,
OrchestrationThreadActivity,
TurnId,
} from "@t3tools/contracts";
export type ThreadDetailReducerResult =
| { readonly kind: "updated"; readonly thread: OrchestrationThread }
| { readonly kind: "deleted" }
| { readonly kind: "unchanged" };
const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
O.mapInput(O.String, (p) => p.createdAt),
O.mapInput(O.String, (p) => p.id),
);
const checkpointOrder = O.mapInput(
O.Number,
(cp: OrchestrationThread["checkpoints"][number]) =>
cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
);
const activityOrder = O.combineAll<OrchestrationThreadActivity>([
O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
O.mapInput(O.String, (a) => a.createdAt),
O.mapInput(O.String, (a) => a.id),
]);
/**
* Apply a single orchestration event to an `OrchestrationThread`, returning
* the updated thread, a deletion signal, or an "unchanged" marker when the
* event doesn't affect this thread.
*
* This is a pure reducer operating on contract types. UI-specific mapping
* (e.g. resolving attachment preview URLs, normalising model slugs, adding
* scoped fields like `environmentId`) is the caller's responsibility.
*/
export function applyThreadDetailEvent(
thread: OrchestrationThread,
event: OrchestrationEvent,
): ThreadDetailReducerResult {
switch (event.type) {
// ── Project events (irrelevant to thread detail) ────────────────
case "project.created":
case "project.meta-updated":
case "project.deleted":
return { kind: "unchanged" };
// ── Thread lifecycle ────────────────────────────────────────────
case "thread.created":
return {
kind: "updated",
thread: {
id: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
worktreePath: event.payload.worktreePath,
latestTurn: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
};
case "thread.deleted":
return { kind: "deleted" };
case "thread.archived":
return {
kind: "updated",
thread: {
...thread,
archivedAt: event.payload.archivedAt,
titleRegeneration: null,
updatedAt: event.payload.updatedAt,
},
};
case "thread.unarchived":
return {
kind: "updated",
thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
};
case "thread.settled":
return {
kind: "updated",
thread: {
...thread,
settledOverride: "settled",
settledAt: event.payload.settledAt,
updatedAt: event.payload.updatedAt,
},
};
case "thread.unsettled":
return {
kind: "updated",
thread: {
...thread,
settledOverride: event.payload.reason === "user" ? "active" : null,
settledAt: null,
updatedAt: event.payload.updatedAt,
},
};
case "thread.snoozed":
return {
kind: "updated",
thread: {
...thread,
snoozedUntil: event.payload.snoozedUntil,
snoozedAt: event.payload.snoozedAt,
updatedAt: event.payload.updatedAt,
},
};
case "thread.unsnoozed":
return {
kind: "updated",
thread: {
...thread,
snoozedUntil: null,
snoozedAt: null,
updatedAt: event.payload.updatedAt,
},
};
// ── Thread metadata ─────────────────────────────────────────────
case "thread.meta-updated":
return {
kind: "updated",
thread: {
...thread,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.titleRegeneration !== undefined
? { titleRegeneration: event.payload.titleRegeneration }
: {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
: {}),
updatedAt: event.payload.updatedAt,
},
};
case "thread.runtime-mode-set":
return {
kind: "updated",
thread: {
...thread,
runtimeMode: event.payload.runtimeMode,
updatedAt: event.payload.updatedAt,
},
};
case "thread.interaction-mode-set":
return {
kind: "updated",
thread: {
...thread,
interactionMode: event.payload.interactionMode,
updatedAt: event.payload.updatedAt,
},
};
// ── Turn lifecycle ──────────────────────────────────────────────
case "thread.turn-start-requested":
return {
kind: "updated",
thread: {
...thread,
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
updatedAt: event.occurredAt,
},
};
case "thread.turn-interrupt-requested": {
if (event.payload.turnId === undefined) {
return { kind: "unchanged" };
}
const latestTurn = thread.latestTurn;
if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
return { kind: "unchanged" };
}
return {
kind: "updated",
thread: {
...thread,
latestTurn: {
...latestTurn,
state: "interrupted",
startedAt: latestTurn.startedAt ?? event.payload.createdAt,
completedAt: latestTurn.completedAt ?? event.payload.createdAt,
},
updatedAt: event.occurredAt,
},
};
}
// ── Messages ────────────────────────────────────────────────────
case "thread.message-sent": {
const message: OrchestrationMessage = {
id: event.payload.messageId,
role: event.payload.role,
text: event.payload.text,
...(event.payload.attachments !== undefined
? { attachments: event.payload.attachments }
: {}),
turnId: event.payload.turnId,
streaming: event.payload.streaming,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
};
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = existingMessage
? Arr.map(thread.messages, (entry) =>
entry.id !== message.id
? entry
: {
...entry,
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
...(message.streaming ? {} : { updatedAt: message.updatedAt }),
...(message.attachments !== undefined
? { attachments: message.attachments }
: {}),
},
)
: Arr.append(thread.messages, message);
// Update latestTurn for assistant messages bound to a turn. A completed
// assistant message only settles the turn once the session is no longer
// running it — providers may emit several assistant messages per turn
// (commentary between tool calls), and the turn must stay unsettled
// until the provider reports turn end.
const turnStillRunning =
event.payload.turnId !== null &&
thread.session?.status === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const latestTurn: OrchestrationThread["latestTurn"] =
event.payload.role === "assistant" &&
event.payload.turnId !== null &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
state: settlesTurn
? thread.latestTurn?.state === "interrupted"
? "interrupted"
: thread.latestTurn?.state === "error"
? "error"
: "completed"
: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.turnId
? thread.latestTurn.requestedAt
: event.payload.createdAt,
startedAt:
thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
: event.payload.createdAt,
completedAt: settlesTurn
? event.payload.updatedAt
: thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.completedAt ?? null)
: null,
assistantMessageId: event.payload.messageId,
}
: thread.latestTurn;
// Rebind checkpoint assistant message IDs for assistant messages.
const checkpoints =
event.payload.role === "assistant" && event.payload.turnId !== null
? rebindCheckpointAssistantMessage(
thread.checkpoints,
event.payload.turnId,
event.payload.messageId,
)
: thread.checkpoints;
return {
kind: "updated",
thread: {
...thread,
messages,
checkpoints,
latestTurn,
updatedAt: event.occurredAt,
},
};
}
// ── Session ─────────────────────────────────────────────────────
case "thread.session-set": {
// Leaving the "running" session status is the turn-end signal: settle a
// still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
const latestTurn: OrchestrationLatestTurn | null =
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
? {
turnId: event.payload.session.activeTurnId,
state: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.requestedAt
: event.payload.session.updatedAt,
startedAt:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
: event.payload.session.updatedAt,
completedAt: null,
assistantMessageId:
thread.latestTurn?.turnId === event.payload.session.activeTurnId
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}
: thread.latestTurn;
return {
kind: "updated",
thread: {
...thread,
session: event.payload.session,
latestTurn,
updatedAt: event.occurredAt,
},
};
}
case "thread.session-stop-requested":
return thread.session === null
? { kind: "unchanged" }
: {
kind: "updated",
thread: {
...thread,
session: {
...thread.session,
status: "stopped",
activeTurnId: null,
updatedAt: event.payload.createdAt,
},
updatedAt: event.occurredAt,
},
};
// ── Proposed plans ──────────────────────────────────────────────
case "thread.proposed-plan-upserted": {
const proposedPlan = event.payload.proposedPlan;
const proposedPlans = pipe(
thread.proposedPlans,
Arr.filter((entry) => entry.id !== proposedPlan.id),
Arr.append(proposedPlan),
Arr.sort(proposedPlanOrder),
);
return {
kind: "updated",
thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
};
}
// ── Checkpoints / turn diffs ────────────────────────────────────
case "thread.turn-diff-completed": {
const checkpoint: OrchestrationCheckpointSummary = {
turnId: event.payload.turnId,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
status: event.payload.status,
files: event.payload.files,
assistantMessageId: event.payload.assistantMessageId,
completedAt: event.payload.completedAt,
};
const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
// Don't overwrite a non-missing checkpoint with a missing one.
if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
return { kind: "unchanged" };
}
const checkpoints = pipe(
thread.checkpoints,
Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
Arr.append(checkpoint),
Arr.sort(checkpointOrder),
);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const diffTurnStillRunning =
thread.session?.status === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const latestTurn =
!diffTurnStillRunning &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
state: checkpointStatusToTurnState(event.payload.status),
requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
completedAt: event.payload.completedAt,
assistantMessageId: event.payload.assistantMessageId,
}
: thread.latestTurn;
return {
kind: "updated",
thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
};
}
// ── Revert ──────────────────────────────────────────────────────
case "thread.reverted": {
const checkpoints = pipe(
thread.checkpoints,
Arr.filter(
(entry) =>
entry.checkpointTurnCount !== undefined &&
entry.checkpointTurnCount <= event.payload.turnCount,
),
Arr.sort(checkpointOrder),
);
const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds);
const proposedPlans = pipe(
thread.proposedPlans,
Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
);
const activities = pipe(
thread.activities,
Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
);
const latestCheckpoint = checkpoints.at(-1) ?? null;
return {
kind: "updated",
thread: {
...thread,
checkpoints,
messages,
proposedPlans,
activities,
latestTurn:
latestCheckpoint === null
? null
: {
turnId: latestCheckpoint.turnId,
state: checkpointStatusToTurnState(
latestCheckpoint.status as "ready" | "missing" | "error",
),
requestedAt: latestCheckpoint.completedAt,
startedAt: latestCheckpoint.completedAt,
completedAt: latestCheckpoint.completedAt,
assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
},
updatedAt: event.occurredAt,
},
};
}
// ── Activities ──────────────────────────────────────────────────
case "thread.activity-appended": {
const activities = pipe(
thread.activities,
Arr.filter((activity) => activity.id !== event.payload.activity.id),
Arr.append(event.payload.activity),
Arr.sort(activityOrder),
);
return {
kind: "updated",
thread: { ...thread, activities, updatedAt: event.occurredAt },
};
}
// ── Events that don't mutate thread state directly ──────────────
case "thread.approval-response-requested":
case "thread.user-input-response-requested":
case "thread.checkpoint-revert-requested":
return { kind: "unchanged" };
}
// Forward-compatible: ignore unrecognized event types.
return { kind: "unchanged" };
}
// ── Helpers ──────────────────────────────────────────────────────────
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function checkpointStatusToTurnState(
status: "ready" | "missing" | "error",
): OrchestrationLatestTurn["state"] {
switch (status) {
case "ready":
return "completed";
case "error":
return "error";
case "missing":
return "completed";
}
}
function rebindCheckpointAssistantMessage(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
turnId: TurnId,
messageId: MessageId,
): OrchestrationCheckpointSummary[] {
return Arr.map(checkpoints, (entry) =>
entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
);
}
function retainMessagesAfterRevert(
messages: ReadonlyArray<OrchestrationMessage>,
retainedTurnIds: ReadonlySet<string>,
): OrchestrationMessage[] {
// Keep messages that belong to a retained turn, plus system messages and
// messages without a turn binding (pre-turn-0 user messages).
return Arr.filter(messages, (message) => {
if (message.role === "system") {
return true;
}
if (message.turnId === null) {
return true;
}
return retainedTurnIds.has(message.turnId);
});
}
@@ -1,7 +1,7 @@
import type {
EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadShell,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadShell,
ProjectId,
ScopedProjectRef,
ScopedThreadRef,
@@ -10,7 +10,7 @@ import type {
import { Atom } from "effect/unstable/reactivity";
import type { EnvironmentThreadShell } from "./models.ts";
import { scopeThreadShell } from "./models.ts";
import { presentThreadShell } from "./models.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import {
arrayElementsEqual,
@@ -21,9 +21,9 @@ import {
threadRefsEqual,
} from "./entities.ts";
const EMPTY_THREADS: ReadonlyArray<OrchestrationThreadShell> = Object.freeze([]);
const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([]);
const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationThreadShell> = new Map();
const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
ProjectId,
ReadonlyArray<ScopedThreadRef>
@@ -33,17 +33,17 @@ export function createEnvironmentThreadShellAtoms(input: {
readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
readonly snapshotAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<OrchestrationShellSnapshot | null>;
) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
}) {
const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make(
(get): ReadonlyArray<OrchestrationThreadShell> =>
(get): ReadonlyArray<OrchestrationV2ThreadShell> =>
get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
);
const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make((get): ReadonlyMap<ThreadId, OrchestrationThreadShell> => {
Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
const threads = get(environmentThreadsAtom(environmentId));
if (threads.length === 0) {
return EMPTY_THREAD_INDEX;
@@ -102,7 +102,7 @@ export function createEnvironmentThreadShellAtoms(input: {
const threadShellAtomFamily = Atom.family((key: string) => {
const ref = parseThreadKey(key);
let previousSource: OrchestrationThreadShell | null = null;
let previousSource: OrchestrationV2ThreadShell | null = null;
let previousValue: EnvironmentThreadShell | null = null;
return Atom.make((get) => {
const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
@@ -110,7 +110,7 @@ export function createEnvironmentThreadShellAtoms(input: {
return previousValue;
}
previousSource = source;
previousValue = source === null ? null : scopeThreadShell(ref.environmentId, source);
previousValue = source === null ? null : presentThreadShell(ref.environmentId, source);
return previousValue;
}).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
});
@@ -1,41 +1,29 @@
import {
EnvironmentId,
EventId,
ORCHESTRATION_WS_METHODS,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
ORCHESTRATION_V2_WS_METHODS,
type OrchestrationV2ThreadStreamItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
AVAILABLE_CONNECTION_STATE,
PrimaryConnectionTarget,
type PreparedConnection,
type SupervisorConnectionState,
} from "../connection/model.ts";
import * as ConnectionWakeups from "../connection/wakeups.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "../rpc/session.ts";
import {
EMPTY_ENVIRONMENT_THREAD_STATE,
makeEnvironmentThreadState,
ThreadSnapshotLoader,
type EnvironmentThreadState,
} from "./threads.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
import { makeEnvironmentThreadState } from "./threads.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -43,559 +31,73 @@ const TARGET = new PrimaryConnectionTarget({
httpBaseUrl: "https://environment.example.test",
wsBaseUrl: "wss://environment.example.test",
});
const THREAD_ID = ThreadId.make("thread-1");
const CACHED_SNAPSHOT_SEQUENCE = 7;
const PREPARED: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
httpBaseUrl: TARGET.httpBaseUrl,
socketUrl: TARGET.wsBaseUrl,
httpAuthorization: null,
target: TARGET,
};
const BASE_THREAD: OrchestrationThread = {
id: THREAD_ID,
projectId: ProjectId.make("project-1"),
title: "Cached thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
const ACTIVE_THREAD: OrchestrationThread = {
...BASE_THREAD,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T00:01:00.000Z",
startedAt: "2026-04-01T00:01:00.000Z",
completedAt: null,
assistantMessageId: null,
},
session: {
threadId: THREAD_ID,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T00:01:00.000Z",
},
};
type TestThreadInput = OrchestrationThreadStreamItem | Error;
function testSession(
client: WsRpcProtocolClient,
options?: { readonly completionMarker?: boolean },
): RpcSession.RpcSession {
return {
client,
initialConfig: Effect.succeed(
options?.completionMarker === true
? ({ threadResumeCompletionMarker: true } as never)
: ({} as never),
),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
};
}
function awaitThreadState(
observed: Queue.Queue<EnvironmentThreadState>,
predicate: (state: EnvironmentThreadState) => boolean,
) {
return Queue.take(observed).pipe(
Effect.repeat({
until: predicate,
}),
);
}
const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
readonly cached?: OrchestrationThread;
readonly httpSnapshot?: Option.Option<OrchestrationThreadDetailSnapshot>;
readonly completionMarker?: boolean;
}) {
const inputs = yield* Queue.unbounded<TestThreadInput>();
const observed = yield* Queue.unbounded<EnvironmentThreadState>();
const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
const retryCount = yield* Ref.make(0);
const subscriptionCount = yield* Ref.make(0);
const loaderCalls = yield* Ref.make(0);
const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
const lastRequestCompletionMarker = yield* Ref.make<boolean | undefined>(undefined);
const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
AVAILABLE_CONNECTION_STATE,
);
const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
Stream.fromQueue(queue).pipe(
Stream.mapEffect((input) =>
input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
),
);
const client = {
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input: {
readonly afterSequence?: number;
readonly requestCompletionMarker?: boolean;
}) =>
Stream.unwrap(
Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
Effect.andThen(Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker)),
Effect.as(streamFrom(inputs)),
),
),
} as unknown as WsRpcProtocolClient;
const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(
testSession(
describe("V2 thread synchronization", () => {
it.effect("applies a snapshot followed by committed projection events", () =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<OrchestrationV2ThreadStreamItem>();
const client = {
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const rpcSession: RpcSession.RpcSession = {
client,
options?.completionMarker === true ? { completionMarker: true } : undefined,
),
),
);
const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
Option.some(PREPARED),
);
const snapshotLoader = ThreadSnapshotLoader.of({
load: (_prepared, threadId) =>
Ref.update(loaderCalls, (count) => count + 1).pipe(
Effect.as(
threadId === THREAD_ID
? (options?.httpSnapshot ?? Option.none<OrchestrationThreadDetailSnapshot>())
: Option.none<OrchestrationThreadDetailSnapshot>(),
),
),
});
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: supervisorSession,
prepared,
connect: Effect.void,
disconnect: Effect.void,
retryNow: Ref.update(retryCount, (count) => count + 1),
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: () => Effect.void,
loadThread: (_environmentId, threadId) =>
Effect.succeed(
threadId === THREAD_ID && options?.cached !== undefined
? Option.some({
snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
thread: options.cached,
})
: Option.none(),
),
saveThread: (_environmentId, thread) =>
Ref.update(savedThreads, (current) => [...current, thread]),
removeThread: (_environmentId, threadId) =>
Ref.update(removedThreads, (current) => [...current, threadId]),
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
removeVcsRefs: () => Effect.void,
clearVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
Effect.provideService(
ConnectionWakeups.ConnectionWakeups,
ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
),
);
yield* SubscriptionRef.changes(threadState).pipe(
Stream.runForEach((state) =>
Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
),
Effect.forkScoped,
);
return {
inputs,
observed,
latest,
retryCount,
subscriptionCount,
loaderCalls,
lastSubscribeAfterSequence,
lastRequestCompletionMarker,
supervisorState,
supervisorSession,
savedThreads,
removedThreads,
wakeups,
replaceSession: SubscriptionRef.set(
supervisorSession,
Option.some(
testSession(
client,
options?.completionMarker === true ? { completionMarker: true } : undefined,
),
),
),
};
});
const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({
kind: "snapshot",
snapshot: {
snapshotSequence: 1,
thread,
},
});
const synchronized = (): OrchestrationThreadStreamItem => ({ kind: "synchronized" });
const titleUpdated = (title: string, sequence = 2): OrchestrationThreadStreamItem => ({
kind: "event",
event: {
eventId: EventId.make("event-title"),
sequence,
occurredAt: "2026-04-01T01:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
aggregateKind: "thread",
aggregateId: THREAD_ID,
type: "thread.meta-updated",
payload: {
threadId: THREAD_ID,
title,
updatedAt: "2026-04-01T01:00:00.000Z",
},
},
});
const deleted = (): OrchestrationThreadStreamItem => ({
kind: "event",
event: {
eventId: EventId.make("event-deleted"),
sequence: 3,
occurredAt: "2026-04-01T02:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
aggregateKind: "thread",
aggregateId: THREAD_ID,
type: "thread.deleted",
payload: {
threadId: THREAD_ID,
deletedAt: "2026-04-01T02:00:00.000Z",
},
},
});
describe("EnvironmentThreads", () => {
it.effect("publishes cached data immediately from a warm cache", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
expect(Option.isNone(state.error)).toBe(true);
}),
);
it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
// The warm cache reaches live from the cached data, and a live event
// applies on top of it.
yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
// The subscription resumed from the cached sequence and never fetched the
// full snapshot over HTTP.
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
}),
);
it.effect("reduces live events and persists the latest thread", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
const state = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
yield* TestClock.adjust("500 millis");
yield* Effect.yieldNow;
expect(Option.getOrThrow(state.data).title).toBe("Live title");
expect((yield* Ref.get(harness.savedThreads)).at(-1)?.thread.title).toBe("Live title");
expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
}),
);
it.effect("does not persist active thread snapshots during streaming or teardown", () =>
Effect.gen(function* () {
const savedThreads = yield* Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: ACTIVE_THREAD });
yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.session?.status === "running",
);
yield* TestClock.adjust("500 millis");
yield* Effect.yieldNow;
expect(yield* Ref.get(harness.savedThreads)).toEqual([]);
return harness.savedThreads;
}),
);
expect(yield* Ref.get(savedThreads)).toEqual([]);
}),
);
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
Effect.gen(function* () {
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
const harness = yield* makeHarness({
httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }),
initialConfig: Effect.never,
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
};
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
session: yield* SubscriptionRef.make(Option.some(rpcSession)),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
});
// No socket snapshot is pushed; only a live event arrives over the socket.
// It can only be applied if the HTTP snapshot already seeded the thread.
yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
const state = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
expect(Option.getOrThrow(state.data).title).toBe("Live title");
// Cold cache: the full snapshot was loaded over HTTP and the socket
// resumed from that snapshot's sequence.
expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
}),
);
it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
const state = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
expect(Option.getOrThrow(state.data).title).toBe("Live title");
}),
);
it.effect("removes cached data when the thread is deleted", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* Queue.offer(harness.inputs, deleted());
const state = yield* awaitThreadState(
harness.observed,
(value) => value.status === "deleted",
);
expect(Option.isNone(state.data)).toBe(true);
expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
}),
);
it.effect("does not resurrect a deleted thread when the app returns to the foreground", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
cached: BASE_THREAD,
completionMarker: true,
httpSnapshot: Option.some({
snapshotSequence: 4,
thread: { ...BASE_THREAD, title: "Stale HTTP thread" },
}),
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: () => Effect.void,
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
clear: () => Effect.void,
});
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* Queue.offer(harness.inputs, deleted());
yield* awaitThreadState(harness.observed, (value) => value.status === "deleted");
expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
yield* Queue.offer(harness.wakeups, "application-active");
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
yield* Effect.yieldNow;
}
const latest = yield* Ref.get(harness.latest);
expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
expect(latest.status).toBe("deleted");
expect(Option.isNone(latest.data)).toBe(true);
}),
);
it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* Queue.offer(harness.inputs, new Error("stream failed"));
const state = yield* awaitThreadState(harness.observed, (value) =>
Option.isSome(value.error),
const state = yield* makeEnvironmentThreadState(v2ThreadId).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
);
expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
expect(Option.getOrThrow(state.error)).toBe("stream failed");
expect(yield* Ref.get(harness.retryCount)).toBe(0);
yield* harness.replaceSession;
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
break;
}
yield* Effect.yieldNow;
}
yield* Queue.offer(
harness.inputs,
snapshot({
...BASE_THREAD,
title: "Recovered thread",
}),
);
const recovered = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Recovered thread",
);
expect(Option.isNone(recovered.error)).toBe(true);
expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
}),
);
it.effect("recovers from a transient domain failure without replacing the session", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
const failed = yield* awaitThreadState(harness.observed, (value) =>
Option.isSome(value.error),
);
expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
yield* TestClock.adjust("250 millis");
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
break;
}
yield* Effect.yieldNow;
}
yield* Queue.offer(
harness.inputs,
snapshot({
...BASE_THREAD,
title: "Materialized thread",
}),
);
const recovered = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Materialized thread",
);
expect(Option.isNone(recovered.error)).toBe(true);
expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
expect(yield* Ref.get(harness.retryCount)).toBe(0);
}),
);
it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* SubscriptionRef.set(harness.supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 1,
generation: 0,
lastFailure: null,
retryAt: null,
yield* Queue.offer(events, {
kind: "snapshot",
snapshotSequence: 1,
projection: v2Projection,
});
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
yield* awaitThreadState(harness.observed, (value) => value.status === "live");
yield* SubscriptionRef.changes(state).pipe(
Stream.filter((current) => current.status === "live"),
Stream.runHead,
);
yield* SubscriptionRef.set(harness.supervisorState, {
desired: true,
network: "online",
phase: "connected",
stage: null,
attempt: 1,
generation: 1,
lastFailure: null,
retryAt: null,
const occurredAt = DateTime.makeUnsafe("2026-06-20T02:00:00.000Z");
yield* Queue.offer(events, {
kind: "event",
sequence: 2,
event: {
id: EventId.make("event-title"),
type: "thread.metadata-updated",
threadId: v2ThreadId,
occurredAt,
payload: { ...v2Projection.thread, title: "Updated", updatedAt: occurredAt },
},
});
for (let index = 0; index < 10; index += 1) {
yield* Effect.yieldNow;
}
yield* SubscriptionRef.changes(state).pipe(
Stream.filter((current) => Option.getOrNull(current.data)?.thread.title === "Updated"),
Stream.runHead,
);
expect((yield* Ref.get(harness.latest)).status).toBe("live");
expect(Option.getOrThrow((yield* SubscriptionRef.get(state)).data).thread.title).toBe(
"Updated",
);
}),
);
+45 -88
View File
@@ -1,9 +1,8 @@
import {
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_V2_WS_METHODS,
type EnvironmentId as EnvironmentIdType,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadStreamItem,
type ThreadId as ThreadIdType,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -23,16 +22,27 @@ import { EnvironmentCacheStore } from "../platform/persistence.ts";
import { subscribeDynamic } from "../rpc/client.ts";
import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
import { parseThreadKey, threadKey } from "./entities.ts";
import { applyThreadDetailEvent } from "./threadReducer.ts";
import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
import { followStreamInEnvironment } from "./runtime.ts";
import {
EMPTY_ENVIRONMENT_THREAD_STATE,
type EnvironmentThreadState,
type EnvironmentThreadStatus,
} from "./threadState.ts";
function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted";
export interface EnvironmentThreadState {
readonly data: Option.Option<OrchestrationV2ThreadProjection>;
readonly status: EnvironmentThreadStatus;
readonly error: Option.Option<string>;
}
export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
data: Option.none(),
status: "empty",
error: Option.none(),
};
function statusWithoutLiveData(
data: Option.Option<OrchestrationV2ThreadProjection>,
): EnvironmentThreadStatus {
return Option.isSome(data) ? "cached" : "empty";
}
@@ -64,7 +74,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
threadId,
error: error.message,
}),
Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
Effect.as(Option.none<OrchestrationV2ThreadProjection>()),
),
),
);
@@ -74,16 +84,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
status: statusWithoutLiveData(cachedThread),
error: Option.none(),
});
// Seed the resume cursor from the cached snapshot so a warm cache can catch up
// via `afterSequence` instead of re-downloading the full thread body.
const lastSequence = yield* SubscriptionRef.make(
Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
);
const awaitingCompletion = yield* Ref.make(false);
const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
const lastSequence = yield* SubscriptionRef.make(0);
const persistence = yield* Queue.sliding<OrchestrationV2ThreadProjection>(1);
const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
snapshot: OrchestrationThreadDetailSnapshot,
thread: OrchestrationV2ThreadProjection,
) {
yield* cache.saveThread(environmentId, snapshot).pipe(
Effect.catch((error) =>
@@ -142,7 +147,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
);
const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
thread: OrchestrationThread,
thread: OrchestrationV2ThreadProjection,
) {
const waiting = yield* Ref.get(awaitingCompletion);
yield* SubscriptionRef.set(state, {
@@ -180,7 +185,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
});
const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
item: OrchestrationThreadStreamItem,
item: OrchestrationV2ThreadStreamItem,
) {
if (item.kind === "synchronized") {
yield* Ref.set(awaitingCompletion, false);
@@ -193,16 +198,16 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
}
if (item.kind === "snapshot") {
yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
yield* setThread(item.snapshot.thread);
yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
yield* setThread(item.projection);
return;
}
const sequence = yield* SubscriptionRef.get(lastSequence);
if (item.event.sequence <= sequence) {
if (item.sequence <= sequence) {
return;
}
yield* SubscriptionRef.set(lastSequence, item.event.sequence);
yield* SubscriptionRef.set(lastSequence, item.sequence);
const current = yield* SubscriptionRef.get(state);
if (Option.isNone(current.data)) {
@@ -211,11 +216,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
}
return;
}
const result = applyThreadDetailEvent(current.data.value, item.event);
if (result.kind === "updated") {
yield* setThread(result.thread);
} else if (result.kind === "deleted") {
if (item.event.type === "thread.deleted") {
yield* setDeleted();
return;
}
const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event);
if (next !== null) {
yield* setThread(next);
}
});
@@ -240,63 +247,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
});
yield* setSynchronizing;
yield* Effect.forkScoped(
subscribeDynamic(
ORCHESTRATION_WS_METHODS.subscribeThread,
Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
const supportsCompletionMarker = yield* session.initialConfig.pipe(
Effect.map((config) => config.threadResumeCompletionMarker === true),
Effect.orElseSucceed(() => false),
);
yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
yield* setSynchronizing;
let current = yield* SubscriptionRef.get(state);
if (Option.isNone(current.data) && current.status !== "deleted") {
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
SubscriptionRef.changes(supervisor.prepared).pipe(
Stream.filter(Option.isSome),
Stream.map((value) => value.value),
Stream.runHead,
Effect.map(Option.getOrThrow),
),
}),
),
);
const httpSnapshot = yield* snapshotLoader.load(prepared, threadId);
if (Option.isSome(httpSnapshot)) {
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
current = yield* SubscriptionRef.get(state);
}
}
const sequence = yield* SubscriptionRef.get(lastSequence);
const canResume = Option.isSome(current.data);
if (!supportsCompletionMarker && canResume) {
yield* SubscriptionRef.update(state, (value) => ({
...value,
status: value.status === "deleted" ? value.status : ("live" as const),
error: Option.none(),
}));
}
return {
threadId,
...(canResume ? { afterSequence: sequence } : {}),
...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
};
}),
{
onExpectedFailure: setStreamError,
retryExpectedFailureAfter: "250 millis",
resubscribe: foregroundResubscriptions,
},
).pipe(Stream.runForEach(applyItem)),
);
yield* subscribe(
ORCHESTRATION_V2_WS_METHODS.subscribeThread,
{ threadId },
{
onExpectedFailure: setStreamError,
retryExpectedFailureAfter: "250 millis",
},
).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
yield* Effect.addFinalizer(() =>
Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
@@ -350,6 +308,5 @@ export * from "./threadSnapshotHttp.ts";
export * from "./composerPathSearch.ts";
export * from "./threadCommands.ts";
export * from "./threadDetail.ts";
export * from "./threadReducer.ts";
export * from "./threadShell.ts";
export * from "./threadState.ts";