Complete orchestration V2 frontend cutover
- Migrate web and mobile state, commands, and persistence to V2 projections - Render conversations from authoritative visible turn items - Harden runtime policy, launch handling, attachments, and cache invalidation
This commit is contained in:
1 parent
75e126993b
commit
3991a00629
111 files changed
+6306
-9244
No files matched your search
@@ -7,11 +7,22 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
createDeterministicAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
|
||||
describe("attachmentStore", () => {
|
||||
it("derives stable attachment ids for idempotent message retries", () => {
|
||||
const first = createDeterministicAttachmentId("thread-1", "message-1:0");
|
||||
const retry = createDeterministicAttachmentId("thread-1", "message-1:0");
|
||||
const next = createDeterministicAttachmentId("thread-1", "message-1:1");
|
||||
|
||||
expect(first).toBe(retry);
|
||||
expect(next).not.toBe(first);
|
||||
expect(first && parseThreadSegmentFromAttachmentId(first)).toBe("thread-1");
|
||||
});
|
||||
|
||||
it("sanitizes thread ids when creating attachment ids", () => {
|
||||
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
|
||||
@@ -42,6 +42,17 @@ export function createAttachmentId(threadId: string): string | null {
|
||||
return `${threadSegment}-${NodeCrypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
export function createDeterministicAttachmentId(
|
||||
threadId: string,
|
||||
stableKey: string,
|
||||
): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) return null;
|
||||
const hash = NodeCrypto.createHash("sha256").update(stableKey).digest("hex").slice(0, 32);
|
||||
const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
|
||||
return `${threadSegment}-${uuid}`;
|
||||
}
|
||||
|
||||
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2DomainEvent,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
@@ -60,6 +62,7 @@ const TestLayer = Layer.mergeAll(
|
||||
);
|
||||
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const providerDriver = ProviderDriverKind.make("codex");
|
||||
const modelSelection = {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
@@ -404,7 +407,32 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:foundation-many-items");
|
||||
const runId = RunId.make("run:foundation-many-items");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread:foundation-many-items");
|
||||
const thread = makeThread(threadId, now);
|
||||
const providerThreadEvent = {
|
||||
id: EventId.make("event:foundation-many-items:provider-thread"),
|
||||
type: "provider-thread.updated" as const,
|
||||
threadId,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: providerThreadId,
|
||||
driver: providerDriver,
|
||||
providerInstanceId,
|
||||
providerSessionId: null,
|
||||
appThreadId: threadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: null,
|
||||
nativeConversationHeadRef: null,
|
||||
status: "active" as const,
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 1,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
} satisfies OrchestrationV2DomainEvent;
|
||||
const runEvent = {
|
||||
id: EventId.make("event:foundation-many-items:run"),
|
||||
type: "run.created" as const,
|
||||
@@ -467,11 +495,13 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
|
||||
yield* eventSink.write({
|
||||
events: [
|
||||
threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }),
|
||||
providerThreadEvent,
|
||||
runEvent,
|
||||
...itemEvents,
|
||||
],
|
||||
});
|
||||
const beforeUpdate = yield* projectionStore.getThreadProjection(threadId);
|
||||
assert.equal(beforeUpdate.thread.activeProviderThreadId, providerThreadId);
|
||||
const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal);
|
||||
assert.lengthOf(ordinals, 151);
|
||||
assert.equal(new Set(ordinals).size, 151);
|
||||
|
||||
@@ -1649,6 +1649,54 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const projection = yield* getProjectionWithPendingEvents(command.threadId, events);
|
||||
const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
|
||||
const dispatchMode = command.dispatchMode;
|
||||
const sourcePlanProjection =
|
||||
command.sourcePlanRef === undefined
|
||||
? null
|
||||
: yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
|
||||
const sourcePlan =
|
||||
command.sourcePlanRef === undefined
|
||||
? null
|
||||
: (sourcePlanProjection?.plans.find(
|
||||
(plan) => plan.id === command.sourcePlanRef?.planId && plan.kind === "proposed_plan",
|
||||
) ?? null);
|
||||
if (command.sourcePlanRef !== undefined && sourcePlan === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
sourcePlanProjection !== null &&
|
||||
sourcePlanProjection.thread.projectId !== projection.thread.projectId
|
||||
) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
|
||||
});
|
||||
}
|
||||
if (sourcePlan !== null && sourcePlan.status !== "active") {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Proposed plan ${sourcePlan.id} is not active.`,
|
||||
});
|
||||
}
|
||||
const completeSourcePlan = (occurredAt: DateTime.Utc) =>
|
||||
sourcePlan === null
|
||||
? Effect.void
|
||||
: emit(
|
||||
events,
|
||||
command,
|
||||
)({
|
||||
type: "plan.updated",
|
||||
threadId: sourcePlan.threadId,
|
||||
...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
|
||||
nodeId: sourcePlan.nodeId,
|
||||
occurredAt,
|
||||
payload: { ...sourcePlan, status: "completed" },
|
||||
});
|
||||
|
||||
if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
|
||||
yield* dispatchSteerIntoRun({
|
||||
@@ -1783,6 +1831,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -1861,6 +1910,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
@@ -2030,6 +2080,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -2116,6 +2167,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
@@ -2613,6 +2665,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
checkpointId: null,
|
||||
contextHandoffId:
|
||||
portableForkHandoff?.id ?? providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
|
||||
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -2917,6 +2970,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* completeSourcePlan(now);
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.created",
|
||||
threadId: command.threadId,
|
||||
|
||||
@@ -223,6 +223,13 @@ export function applyToProjection(
|
||||
case "provider-thread.updated":
|
||||
return {
|
||||
...base,
|
||||
thread:
|
||||
event.payload.appThreadId === base.thread.id
|
||||
? {
|
||||
...base.thread,
|
||||
activeProviderThreadId: event.payload.id,
|
||||
}
|
||||
: base.thread,
|
||||
providerThreads: upsertById(base.providerThreads, event.payload),
|
||||
};
|
||||
case "provider-turn.updated":
|
||||
@@ -288,6 +295,8 @@ type ShellThreadRow = {
|
||||
readonly active_run_id: string | null;
|
||||
readonly pending_request_payload_json: string | null;
|
||||
readonly latest_message_payload_json: string | null;
|
||||
readonly latest_user_message_at: string | null;
|
||||
readonly has_actionable_proposed_plan: number;
|
||||
readonly item_count: number;
|
||||
};
|
||||
|
||||
@@ -638,6 +647,13 @@ export function threadShellFromProjection(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
const latestUserMessage =
|
||||
projection.messages
|
||||
.filter((message) => message.role === "user")
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
return {
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
@@ -673,6 +689,10 @@ export function threadShellFromProjection(
|
||||
text: latestVisibleMessage.text,
|
||||
updatedAt: latestVisibleMessage.updatedAt,
|
||||
},
|
||||
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
|
||||
hasActionableProposedPlan: projection.plans.some(
|
||||
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
|
||||
),
|
||||
itemCount: activeLocalTurnItems(projection).length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
createdAt: projection.thread.createdAt,
|
||||
@@ -693,6 +713,8 @@ type ShellThreadState = {
|
||||
readonly activeRunId: RunId | null;
|
||||
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
|
||||
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
|
||||
readonly latestUserMessageAt: DateTime.Utc | null;
|
||||
readonly hasActionableProposedPlan: boolean;
|
||||
readonly itemCount: number;
|
||||
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
|
||||
readonly runOrdinalById: ReadonlyMap<RunId, number>;
|
||||
@@ -819,6 +841,8 @@ function shellFromState(input: {
|
||||
text: input.state.latestVisibleMessage.text,
|
||||
updatedAt: input.state.latestVisibleMessage.updatedAt,
|
||||
},
|
||||
latestUserMessageAt: input.state.latestUserMessageAt,
|
||||
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
|
||||
itemCount: input.state.itemCount,
|
||||
visibleItemCount: input.visibleItemCount,
|
||||
createdAt: input.state.thread.createdAt,
|
||||
@@ -1949,6 +1973,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
ORDER BY message.updated_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_message_payload_json,
|
||||
(
|
||||
SELECT message.updated_at
|
||||
FROM orchestration_v2_projection_messages message
|
||||
WHERE message.thread_id = t.thread_id
|
||||
AND message.role = 'user'
|
||||
ORDER BY message.updated_at DESC, message.message_id DESC
|
||||
LIMIT 1
|
||||
) AS latest_user_message_at,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM orchestration_v2_projection_plans plan
|
||||
WHERE plan.thread_id = t.thread_id
|
||||
AND plan.kind = 'proposed_plan'
|
||||
AND plan.status = 'active'
|
||||
) AS has_actionable_proposed_plan,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM orchestration_v2_projection_turn_items i
|
||||
@@ -2015,6 +2054,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
|
||||
pendingRuntimeRequest,
|
||||
latestVisibleMessage,
|
||||
latestUserMessageAt:
|
||||
row.latest_user_message_at === null
|
||||
? null
|
||||
: DateTime.makeUnsafe(row.latest_user_message_at),
|
||||
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
|
||||
itemCount: row.item_count,
|
||||
updatedAt: thread.updatedAt,
|
||||
runOrdinalById:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
type ModelSelection,
|
||||
type OrchestrationV2AppThread,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
|
||||
import { layerFromProjectRepository, RuntimePolicyV2 } from "./RuntimePolicy.ts";
|
||||
|
||||
const projectId = ProjectId.make("project:runtime-policy");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const modelSelection = {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.5",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
function makeThread(input: {
|
||||
readonly now: DateTime.Utc;
|
||||
readonly worktreePath: string | null;
|
||||
}): OrchestrationV2AppThread {
|
||||
const threadId = ThreadId.make("thread:runtime-policy");
|
||||
return {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Runtime policy",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
const TestLayer = layerFromProjectRepository.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionProjects.ProjectionProjectRepository)({
|
||||
getById: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/project-root",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-21T00:00:00.000Z",
|
||||
updatedAt: "2026-06-21T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("RuntimePolicyV2", (it) => {
|
||||
it.effect("uses the project root for local-checkout threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* RuntimePolicyV2;
|
||||
const now = yield* DateTime.now;
|
||||
const resolved = yield* policy.resolve({
|
||||
thread: makeThread({ now, worktreePath: null }),
|
||||
modelSelection,
|
||||
});
|
||||
assert.equal(resolved.cwd, "/project-root");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers a provisioned worktree over the project root", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* RuntimePolicyV2;
|
||||
const now = yield* DateTime.now;
|
||||
const resolved = yield* policy.resolve({
|
||||
thread: makeThread({ now, worktreePath: "/project-worktree" }),
|
||||
modelSelection,
|
||||
});
|
||||
assert.equal(resolved.cwd, "/project-worktree");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
import { ModelSelection, OrchestrationV2AppThread, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import {
|
||||
ModelSelection,
|
||||
OrchestrationV2AppThread,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
|
||||
import {
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2RuntimePolicy as ProviderAdapterV2RuntimePolicyType,
|
||||
@@ -15,12 +22,13 @@ import {
|
||||
export class RuntimePolicyResolveError extends Schema.TaggedErrorClass<RuntimePolicyResolveError>()(
|
||||
"RuntimePolicyResolveError",
|
||||
{
|
||||
driver: ProviderDriverKind,
|
||||
projectId: ProjectId,
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve runtime policy for ${this.driver}.`;
|
||||
return `Failed to resolve runtime policy for provider instance ${this.providerInstanceId} in project ${this.projectId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +69,51 @@ export const layer: Layer.Layer<RuntimePolicyV2> = Layer.succeed(RuntimePolicyV2
|
||||
}),
|
||||
});
|
||||
|
||||
export const layerFromProjectRepository: Layer.Layer<
|
||||
RuntimePolicyV2,
|
||||
never,
|
||||
ProjectionProjects.ProjectionProjectRepository
|
||||
> = Layer.effect(
|
||||
RuntimePolicyV2,
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* ProjectionProjects.ProjectionProjectRepository;
|
||||
return RuntimePolicyV2.of({
|
||||
resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
|
||||
const cwd =
|
||||
input.thread.worktreePath ??
|
||||
(yield* projects.getById({ projectId: input.thread.projectId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RuntimePolicyResolveError({
|
||||
projectId: input.thread.projectId,
|
||||
providerInstanceId: input.modelSelection.instanceId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new RuntimePolicyResolveError({
|
||||
projectId: input.thread.projectId,
|
||||
providerInstanceId: input.modelSelection.instanceId,
|
||||
cause: "Project not found.",
|
||||
}),
|
||||
),
|
||||
onSome: (project) => Effect.succeed(project.workspaceRoot),
|
||||
}),
|
||||
),
|
||||
));
|
||||
return ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: input.thread.runtimeMode,
|
||||
interactionMode: input.thread.interactionMode,
|
||||
cwd,
|
||||
});
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export function layerWithOverride(
|
||||
override: RuntimePolicyV2Override,
|
||||
): Layer.Layer<RuntimePolicyV2, never, RuntimePolicyV2> {
|
||||
|
||||
@@ -80,6 +80,20 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
(
|
||||
command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0],
|
||||
): Effect.Effect<OrchestratorV2DispatchResult, OrchestratorDispatchError> => {
|
||||
if (command.type === "thread.metadata.update") {
|
||||
const existing = projections.get(command.threadId);
|
||||
if (existing === undefined) return Effect.die("missing existing projection");
|
||||
projections.set(command.threadId, {
|
||||
...existing,
|
||||
thread: {
|
||||
...existing.thread,
|
||||
...(command.title === undefined ? {} : { title: command.title }),
|
||||
...(command.branch === undefined ? {} : { branch: command.branch }),
|
||||
...(command.worktreePath === undefined ? {} : { worktreePath: command.worktreePath }),
|
||||
},
|
||||
});
|
||||
return Effect.succeed({ sequence: 1, storedEvents: [] });
|
||||
}
|
||||
if (command.type !== "thread.create") return Effect.die("unexpected command");
|
||||
if (options?.failCreate) {
|
||||
return Effect.fail(
|
||||
@@ -90,16 +104,37 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
}),
|
||||
);
|
||||
}
|
||||
projections.set(command.threadId, projectionFor(command.threadId));
|
||||
const projection = projectionFor(command.threadId);
|
||||
projections.set(command.threadId, {
|
||||
...projection,
|
||||
thread: {
|
||||
...projection.thread,
|
||||
title: command.title,
|
||||
branch: command.branch,
|
||||
worktreePath: command.worktreePath,
|
||||
},
|
||||
});
|
||||
return Effect.succeed({ sequence: 1, storedEvents: [] });
|
||||
},
|
||||
);
|
||||
const createWorktree = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
|
||||
} as never),
|
||||
const createWorktree = vi.fn(
|
||||
(_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
|
||||
} as never),
|
||||
);
|
||||
const removeWorktree = vi.fn(() => Effect.void);
|
||||
const fetchRemote = vi.fn(
|
||||
(_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["fetchRemote"]>[0]) =>
|
||||
Effect.void,
|
||||
);
|
||||
const resolveRemoteTrackingCommit = vi.fn(
|
||||
(
|
||||
_input: Parameters<
|
||||
GitWorkflow.GitWorkflowService["Service"]["resolveRemoteTrackingCommit"]
|
||||
>[0],
|
||||
) => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
|
||||
);
|
||||
const runForThread = vi.fn(() =>
|
||||
options?.failSetup
|
||||
? Effect.fail(
|
||||
@@ -126,7 +161,12 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
|
||||
snapshot: Effect.die("unused"),
|
||||
}),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({
|
||||
createWorktree,
|
||||
fetchRemote,
|
||||
removeWorktree,
|
||||
resolveRemoteTrackingCommit,
|
||||
}),
|
||||
Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
|
||||
runForThread,
|
||||
}),
|
||||
@@ -150,8 +190,11 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
),
|
||||
dispatch,
|
||||
fetchRemote,
|
||||
createWorktree,
|
||||
projections,
|
||||
removeWorktree,
|
||||
resolveRemoteTrackingCommit,
|
||||
runForThread,
|
||||
sendToThread,
|
||||
};
|
||||
@@ -213,6 +256,104 @@ it.effect(
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("preserves an existing worktree when launching a new thread", () => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
const result = yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_existing_worktree"),
|
||||
threadId: ThreadId.make("thread_existing_worktree"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: {
|
||||
type: "existing_worktree",
|
||||
worktreePath: "/repo-worktrees/existing",
|
||||
branch: "existing",
|
||||
},
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
assert.equal(result.projection.thread.worktreePath, "/repo-worktrees/existing");
|
||||
assert.equal(result.projection.thread.branch, "existing");
|
||||
assert.equal(test.createWorktree.mock.calls.length, 0);
|
||||
assert.equal(test.removeWorktree.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("fetches and resolves origin before provisioning an origin-based worktree", () => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_origin_worktree"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: {
|
||||
type: "worktree",
|
||||
baseRef: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
assert.deepEqual(test.fetchRemote.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
remoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(test.resolveRemoteTrackingCommit.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "main",
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(test.createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "remote-main-sha",
|
||||
newRefName: "feature",
|
||||
baseRefName: "main",
|
||||
path: null,
|
||||
});
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("provisions a worktree for an existing empty thread before sending", () => {
|
||||
const test = makeLayer();
|
||||
const threadId = ThreadId.make("thread_existing_empty");
|
||||
test.projections.set(threadId, projectionFor(threadId));
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service.launch({
|
||||
commandId: CommandId.make("command_launch_existing_empty"),
|
||||
threadId,
|
||||
reuseExistingThread: true,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" },
|
||||
initialMessage: { text: "Implement it", attachments: [] },
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
const updateCommand = test.dispatch.mock.calls.find(
|
||||
([command]) => command.type === "thread.metadata.update",
|
||||
)?.[0];
|
||||
assert.equal(updateCommand?.type, "thread.metadata.update");
|
||||
if (updateCommand?.type === "thread.metadata.update") {
|
||||
assert.equal(updateCommand.worktreePath, "/repo-worktrees/feature");
|
||||
assert.equal(updateCommand.branch, "feature");
|
||||
}
|
||||
assert.equal(test.sendToThread.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("removes a new worktree and does not create a thread when setup fails", () => {
|
||||
const test = makeLayer({ failSetup: true });
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ChatAttachment,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Actor,
|
||||
type OrchestrationV2CreationSource,
|
||||
@@ -27,20 +28,29 @@ import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
export type ThreadLaunchWorkspaceStrategy =
|
||||
| { readonly type: "root" }
|
||||
| { readonly type: "root"; readonly branch?: string | undefined }
|
||||
| {
|
||||
readonly type: "existing_worktree";
|
||||
readonly worktreePath: string;
|
||||
readonly branch?: string | undefined;
|
||||
}
|
||||
| {
|
||||
readonly type: "worktree";
|
||||
readonly baseRef: string;
|
||||
readonly branch?: string;
|
||||
readonly branch?: string | undefined;
|
||||
readonly startFromOrigin?: boolean | undefined;
|
||||
};
|
||||
|
||||
export interface ThreadLaunchInitialMessage {
|
||||
readonly messageId?: MessageId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}
|
||||
|
||||
export interface ThreadLaunchInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly reuseExistingThread?: boolean;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title: string;
|
||||
readonly modelSelection: ModelSelection;
|
||||
@@ -69,6 +79,7 @@ export class ThreadLaunchError extends Schema.TaggedErrorClass<ThreadLaunchError
|
||||
"provision-worktree",
|
||||
"run-setup-script",
|
||||
"create-thread",
|
||||
"update-thread",
|
||||
"dispatch-message",
|
||||
"compensate-worktree",
|
||||
]),
|
||||
@@ -185,11 +196,18 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const stored = yield* loadWorkflow(input);
|
||||
if (input.reuseExistingThread === true && input.threadId === undefined) {
|
||||
return yield* mapError(
|
||||
input,
|
||||
"update-thread",
|
||||
)("Reusing an existing thread requires a thread id.");
|
||||
}
|
||||
const threadId =
|
||||
stored === null
|
||||
? yield* ids.allocate
|
||||
? (input.threadId ??
|
||||
(yield* ids.allocate
|
||||
.thread({ projectId: input.projectId })
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))))
|
||||
: ThreadId.make(stored.thread_id);
|
||||
if (stored?.status === "completed") {
|
||||
return {
|
||||
@@ -201,7 +219,38 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
let branch = stored?.branch ?? null;
|
||||
const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(
|
||||
function* () {
|
||||
const projection = yield* threads
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
|
||||
if (
|
||||
projection.thread.projectId !== input.projectId ||
|
||||
projection.thread.archivedAt !== null ||
|
||||
projection.thread.deletedAt !== null ||
|
||||
projection.messages.length > 0 ||
|
||||
projection.runs.length > 0
|
||||
) {
|
||||
return yield* mapError(
|
||||
input,
|
||||
"update-thread",
|
||||
threadId,
|
||||
)(
|
||||
"Only an empty active thread in the target project can change workspace during launch.",
|
||||
);
|
||||
}
|
||||
return projection;
|
||||
},
|
||||
);
|
||||
if (input.reuseExistingThread === true && stored?.thread_committed !== 1) {
|
||||
yield* validateReusableThread();
|
||||
}
|
||||
|
||||
let branch =
|
||||
stored?.branch ??
|
||||
(input.workspaceStrategy.type === "worktree"
|
||||
? null
|
||||
: (input.workspaceStrategy.branch ?? null));
|
||||
let title = stored?.title ?? input.title;
|
||||
if (input.initialMessage !== undefined) {
|
||||
if (title === "New thread") {
|
||||
@@ -235,15 +284,36 @@ export const make = Effect.gen(function* () {
|
||||
branch = branch ?? input.workspaceStrategy.branch ?? `thread-${threadId}`;
|
||||
}
|
||||
|
||||
let worktreePath = stored?.worktree_path ?? null;
|
||||
let worktreePath =
|
||||
stored?.worktree_path ??
|
||||
(input.workspaceStrategy.type === "existing_worktree"
|
||||
? input.workspaceStrategy.worktreePath
|
||||
: null);
|
||||
const ownsProvisionedWorktree = input.workspaceStrategy.type === "worktree";
|
||||
const threadCommitted = stored?.thread_committed === 1;
|
||||
let setupCommitted = stored?.setup_committed === 1;
|
||||
let messageCommitted = stored?.message_committed === 1;
|
||||
if (input.workspaceStrategy.type === "worktree" && worktreePath === null) {
|
||||
let startRef = input.workspaceStrategy.baseRef;
|
||||
if (input.workspaceStrategy.startFromOrigin === true) {
|
||||
yield* git
|
||||
.fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" })
|
||||
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
|
||||
startRef = yield* git
|
||||
.resolveRemoteTrackingCommit({
|
||||
cwd: project.workspaceRoot,
|
||||
refName: input.workspaceStrategy.baseRef,
|
||||
fallbackRemoteName: "origin",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((resolved) => resolved.commitSha),
|
||||
Effect.mapError(mapError(input, "provision-worktree", threadId)),
|
||||
);
|
||||
}
|
||||
const worktree = yield* git
|
||||
.createWorktree({
|
||||
cwd: project.workspaceRoot,
|
||||
refName: input.workspaceStrategy.baseRef,
|
||||
refName: startRef,
|
||||
newRefName: branch!,
|
||||
baseRefName: input.workspaceStrategy.baseRef,
|
||||
path: null,
|
||||
@@ -278,7 +348,7 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
if (setupExit._tag === "Failure") {
|
||||
if (worktreePath !== null && !threadCommitted) {
|
||||
if (ownsProvisionedWorktree && worktreePath !== null && !threadCommitted) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
@@ -313,24 +383,36 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (!threadCommitted) {
|
||||
const createExit = yield* Effect.exit(
|
||||
threads.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch,
|
||||
worktreePath,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
}),
|
||||
);
|
||||
const commitThread =
|
||||
input.reuseExistingThread === true
|
||||
? Effect.gen(function* () {
|
||||
yield* validateReusableThread();
|
||||
return yield* threads.dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
title,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
})
|
||||
: threads.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch,
|
||||
worktreePath,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
});
|
||||
const createExit = yield* Effect.exit(commitThread);
|
||||
if (createExit._tag === "Failure") {
|
||||
if (worktreePath !== null) {
|
||||
if (ownsProvisionedWorktree && worktreePath !== null) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
@@ -339,17 +421,27 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "thread_create_failed",
|
||||
status:
|
||||
input.reuseExistingThread === true ? "thread_update_failed" : "thread_create_failed",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted: false,
|
||||
messageCommitted,
|
||||
lastError: "Thread creation failed.",
|
||||
lastError:
|
||||
input.reuseExistingThread === true
|
||||
? "Thread workspace update failed."
|
||||
: "Thread creation failed.",
|
||||
});
|
||||
return yield* Effect.failCause(createExit.cause).pipe(
|
||||
Effect.mapError(mapError(input, "create-thread", threadId)),
|
||||
Effect.mapError(
|
||||
mapError(
|
||||
input,
|
||||
input.reuseExistingThread === true ? "update-thread" : "create-thread",
|
||||
threadId,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
@@ -365,9 +457,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (input.initialMessage !== undefined && !messageCommitted) {
|
||||
const messageId = yield* ids.allocate
|
||||
.message({ threadId, ordinal: 1 })
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
|
||||
const messageId =
|
||||
input.initialMessage.messageId ??
|
||||
(yield* ids.allocate
|
||||
.message({ threadId, ordinal: 1 })
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
|
||||
yield* threads
|
||||
.sendToThread({
|
||||
projectId: input.projectId,
|
||||
|
||||
@@ -32,7 +32,7 @@ import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlS
|
||||
import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts";
|
||||
import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
|
||||
import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.ts";
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layerFromProjectRepository as runtimePolicyLayerFromProjectRepository } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
@@ -40,6 +40,13 @@ import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.t
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
|
||||
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
const runtimePolicyProvided = runtimePolicyLayerFromProjectRepository.pipe(
|
||||
Layer.provide(ProjectionProjectRepositoryLive),
|
||||
);
|
||||
|
||||
const eventStoreProvided = eventStoreLayer.pipe(
|
||||
Layer.provide(OrchestrationEventInfrastructureLayerLive),
|
||||
);
|
||||
@@ -111,7 +118,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runExecutionServiceProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -130,7 +137,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -189,7 +196,7 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
providerAdapterRegistryProvided,
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
@@ -201,9 +208,6 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
);
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
);
|
||||
|
||||
+199
-28
@@ -1,8 +1,11 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -13,9 +16,11 @@ import {
|
||||
type AuthAccessStreamEvent,
|
||||
type AuthEnvironmentScope,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
type DiscoveredLocalServerList,
|
||||
type GitActionProgressEvent,
|
||||
type GitManagerServiceError,
|
||||
type MessageId,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
@@ -28,18 +33,21 @@ import {
|
||||
type ProjectEntriesFailure,
|
||||
type ProjectFileFailure,
|
||||
type ProjectFileOperation,
|
||||
type ProjectMutation,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchContentsError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
ProjectMutationError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
RpcClientId,
|
||||
ChatAttachmentId,
|
||||
PersistChatAttachmentsError,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
@@ -81,6 +89,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import { issueAssetUrl } from "./assets/AssetAccess.ts";
|
||||
import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -118,6 +128,73 @@ function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
}
|
||||
|
||||
const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageId: MessageId;
|
||||
readonly attachments: ReadonlyArray<{
|
||||
readonly type: "image";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly dataUrl: string;
|
||||
}>;
|
||||
}) {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return yield* Effect.forEach(
|
||||
input.attachments.map((attachment, index) => ({ attachment, index })),
|
||||
Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} has an invalid image payload.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* Effect.fromResult(Encoding.decodeBase64(parsed.base64)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} is not valid base64.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (bytes.byteLength !== attachment.sizeBytes) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} size does not match its payload.`,
|
||||
});
|
||||
}
|
||||
const rawId = createDeterministicAttachmentId(input.threadId, `${input.messageId}:${index}`);
|
||||
if (rawId === null) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: "Could not allocate an attachment identifier.",
|
||||
});
|
||||
}
|
||||
const persisted = {
|
||||
type: "image" as const,
|
||||
id: ChatAttachmentId.make(rawId),
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
yield* fileSystem
|
||||
.writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)), bytes)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Could not persist attachment ${attachment.name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return persisted;
|
||||
}),
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
});
|
||||
|
||||
function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {
|
||||
readonly failure: ProjectEntriesFailure;
|
||||
readonly normalizedCwd?: string;
|
||||
@@ -253,8 +330,11 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsMutate, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
|
||||
@@ -623,20 +703,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
},
|
||||
);
|
||||
|
||||
const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
schemaVersion: snapshot.schemaVersion,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
threads: snapshot.archivedThreads,
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const getOrchestrationV2ArchivedShellSnapshot = sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const threads = yield* threadManagement.getShellSnapshot();
|
||||
return {
|
||||
schemaVersion: threads.schemaVersion,
|
||||
snapshotSequence: yield* applicationEvents.latestApplicationSequence,
|
||||
projects: projects.projects,
|
||||
threads: threads.archivedThreads,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const subscribeOrchestrationV2ArchivedShell = Effect.fn(
|
||||
"ws.orchestrationV2.subscribeArchivedShell",
|
||||
@@ -671,6 +759,64 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live);
|
||||
});
|
||||
|
||||
const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) {
|
||||
switch (mutation.type) {
|
||||
case "project.create":
|
||||
return yield* projectService.create({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
title: mutation.title,
|
||||
workspaceRoot: mutation.workspaceRoot,
|
||||
...(mutation.createWorkspaceRootIfMissing === undefined
|
||||
? {}
|
||||
: { createWorkspaceRootIfMissing: mutation.createWorkspaceRootIfMissing }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.update":
|
||||
return yield* projectService.update({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
...(mutation.title === undefined ? {} : { title: mutation.title }),
|
||||
...(mutation.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: mutation.workspaceRoot }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.delete": {
|
||||
const snapshot = yield* threadManagement.getShellSnapshot();
|
||||
const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
|
||||
(thread) => thread.projectId === mutation.projectId,
|
||||
);
|
||||
if (projectThreads.length > 0 && mutation.force !== true) {
|
||||
return yield* new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: `Project ${mutation.projectId} is not empty.`,
|
||||
});
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
projectThreads,
|
||||
(thread) =>
|
||||
threadManagement.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.make(`${mutation.commandId}:delete-thread:${thread.id}`),
|
||||
threadId: thread.id,
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
return yield* projectService.delete({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handlers = ServerWsRpcGroup.of({
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
@@ -680,7 +826,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
threadManagement.dispatch(
|
||||
ThreadManagementService.withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: "creationSource" in command ? command.creationSource : "web",
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -771,26 +917,29 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
.enqueueCommand(
|
||||
threadLaunch.launch({
|
||||
commandId: input.commandId,
|
||||
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input.reuseExistingThread === undefined
|
||||
? {}
|
||||
: { reuseExistingThread: input.reuseExistingThread }),
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy:
|
||||
input.workspaceStrategy.type === "root"
|
||||
? { type: "root" }
|
||||
: {
|
||||
type: "worktree",
|
||||
baseRef: input.workspaceStrategy.baseRef,
|
||||
...(input.workspaceStrategy.branch === undefined
|
||||
? {}
|
||||
: { branch: input.workspaceStrategy.branch }),
|
||||
},
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
...(input.initialMessage === undefined
|
||||
? {}
|
||||
: { initialMessage: input.initialMessage }),
|
||||
: {
|
||||
initialMessage: {
|
||||
...(input.initialMessage.messageId === undefined
|
||||
? {}
|
||||
: { messageId: input.initialMessage.messageId }),
|
||||
text: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
},
|
||||
}),
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -1137,6 +1286,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsMutate]: (mutation) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsMutate,
|
||||
startup.enqueueCommand(mutateProject(mutation)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProjectMutationError"
|
||||
? cause
|
||||
: new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: "Failed to mutate project.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
@@ -1195,6 +1360,12 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsPersistChatAttachments]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsPersistChatAttachments,
|
||||
persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
|
||||
Reference in new issue
Block a user