buuuunch of cleanup

This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-02-26 13:20:36 -08:00
1 parent a973e43421
commit c2b9680a5e
69 files changed
+1384 -1099

No files matched your search

@@ -6,7 +6,6 @@ import { execFileSync } from "node:child_process";
import { NodeServices } from "@effect/platform-node";
import {
ApprovalRequestId,
CheckpointRef,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -63,11 +62,6 @@ function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["commit", "-m", "Initial"]);
}
export function checkpointRefForTurn(threadId: string, turnCount: number): CheckpointRef {
const encodedThreadId = Buffer.from(threadId, "utf8").toString("base64url");
return CheckpointRef.makeUnsafe(`refs/t3/checkpoints/${encodedThreadId}/turn/${turnCount}`);
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
@@ -17,17 +17,15 @@ import { Effect, Option } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import {
checkpointRefForTurn,
gitRefExists,
gitShowFileAtRef,
makeOrchestrationIntegrationHarness,
type OrchestrationIntegrationHarness,
} from "./OrchestrationEngineHarness.integration.ts";
import { checkpointRefForThreadTurn } from "../src/checkpointing/Refs.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId =>
ProviderSessionId.makeUnsafe(value);
@@ -37,7 +35,7 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = asThreadId("thread-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
@@ -95,7 +93,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
@@ -105,7 +103,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
@@ -124,7 +122,7 @@ const startTurn = (input: {
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
commandId: asCommandId(input.commandId),
commandId: CommandId.makeUnsafe(input.commandId),
threadId: THREAD_ID,
message: {
messageId: asMessageId(input.messageId),
@@ -195,8 +193,8 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-diff-completed");
const ref0 = checkpointRefForTurn(THREAD_ID, 0);
const ref1 = checkpointRefForTurn(THREAD_ID, 1);
const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);
const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);
assert.equal(gitRefExists(harness.workspaceDir, ref0), true);
assert.equal(gitRefExists(harness.workspaceDir, ref1), true);
assert.equal(gitShowFileAtRef(harness.workspaceDir, ref0, "README.md"), "v1\n");
@@ -335,26 +333,34 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
const incrementalDiff = yield* harness.checkpointStore.diffCheckpoints({
cwd: harness.workspaceDir,
fromCheckpointRef: checkpointRefForTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForTurn(THREAD_ID, 2),
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
});
assert.equal(incrementalDiff.includes("README.md"), true);
const fullDiff = yield* harness.checkpointStore.diffCheckpoints({
cwd: harness.workspaceDir,
fromCheckpointRef: checkpointRefForTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForTurn(THREAD_ID, 2),
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
});
assert.equal(fullDiff.includes("README.md"), true);
assert.equal(
gitShowFileAtRef(harness.workspaceDir, checkpointRefForTurn(THREAD_ID, 1), "README.md"),
gitShowFileAtRef(
harness.workspaceDir,
checkpointRefForThreadTurn(THREAD_ID, 1),
"README.md",
),
"v2\n",
);
assert.equal(
gitShowFileAtRef(harness.workspaceDir, checkpointRefForTurn(THREAD_ID, 2), "README.md"),
gitShowFileAtRef(
harness.workspaceDir,
checkpointRefForThreadTurn(THREAD_ID, 2),
"README.md",
),
"v3\n",
);
}),
@@ -416,7 +422,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: asCommandId("cmd-approval-respond"),
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
@@ -507,7 +513,10 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(gitRefExists(harness.workspaceDir, checkpointRefForTurn(THREAD_ID, 1)), true);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
);
@@ -644,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-checkpoint-revert"),
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
@@ -681,7 +690,10 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(gitRefExists(harness.workspaceDir, checkpointRefForTurn(THREAD_ID, 2)), false);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness.getRollbackCalls(sessionId), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
@@ -701,7 +713,7 @@ it.live(
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-checkpoint-revert-no-session"),
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
@@ -0,0 +1,190 @@
import {
CheckpointRef,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Refs.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
function makeSnapshot(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: input.worktreePath,
latestTurnId: asTurnId("turn-1"),
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
messages: [],
activities: [],
checkpoints: [
{
turnId: asTurnId("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
},
],
};
}
describe("CheckpointDiffQueryLive", () => {
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = asProjectId("project-1");
const threadId = ThreadId.makeUnsafe("thread-1");
const toCheckpointRef = asCheckpointRef("refs/t3/checkpoints/thread-1/turn/1");
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: ({ checkpointRef }) =>
Effect.sync(() => {
hasCheckpointRefCalls.push(checkpointRef);
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(snapshot),
}),
),
);
const result = await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
diff: "diff patch",
});
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.makeUnsafe("thread-missing");
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(""),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
}),
),
);
await expect(
Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
),
).rejects.toThrow("Thread 'thread-missing' not found.");
});
});
@@ -0,0 +1,193 @@
import {
OrchestrationGetTurnDiffResult,
type ProjectId,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn } from "../Refs.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery, type CheckpointDiffQueryShape } from "../Services/CheckpointDiffQuery.ts";
function trimToNonEmpty(value: string | null | undefined): string | undefined {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
}
function resolveThreadWorkspaceCwd(input: {
readonly thread: {
readonly projectId: ProjectId;
readonly worktreePath: string | null;
};
readonly projects: ReadonlyArray<{
readonly id: ProjectId;
readonly workspaceRoot: string;
}>;
}): string | undefined {
const worktreeCwd = trimToNonEmpty(input.thread.worktreePath);
if (worktreeCwd) {
return worktreeCwd;
}
const workspaceRoot = input.projects.find(
(project) => project.id === input.thread.projectId,
)?.workspaceRoot;
return trimToNonEmpty(workspaceRoot);
}
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff: "",
};
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
});
}
return emptyDiff;
}
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
if (input.toTurnCount > maxTurnCount) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
});
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
});
}
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
});
}
const toCheckpointRef = thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
});
}
const [fromExists, toExists] = yield* Effect.all(
[
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
if (!fromExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
});
}
if (!toExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
});
}
return turnDiff;
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
) =>
getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
getTurnDiff,
getFullThreadDiff,
} satisfies CheckpointDiffQueryShape;
});
export const CheckpointDiffQueryLive = Layer.effect(CheckpointDiffQuery, make);
+10
View File
@@ -0,0 +1,10 @@
import { Encoding } from "effect";
import { CheckpointRef, type ThreadId } from "@t3tools/contracts";
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
return CheckpointRef.makeUnsafe(
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
);
}
@@ -0,0 +1,24 @@
import type {
OrchestrationGetFullThreadDiffInput,
OrchestrationGetFullThreadDiffResult,
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { CheckpointServiceError } from "../Errors.ts";
export interface CheckpointDiffQueryShape {
readonly getTurnDiff: (
input: OrchestrationGetTurnDiffInput,
) => Effect.Effect<OrchestrationGetTurnDiffResult, CheckpointServiceError>;
readonly getFullThreadDiff: (
input: OrchestrationGetFullThreadDiffInput,
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
}
export class CheckpointDiffQuery extends ServiceMap.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("checkpointing/CheckpointDiffQuery") {}
+4 -4
View File
@@ -216,7 +216,7 @@ export class GitCoreService {
async status(input: GitStatusInput): Promise<GitStatusResult> {
const details = await this.statusDetails(input.cwd);
return GitStatusResult.makeUnsafe({
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
@@ -224,7 +224,7 @@ export class GitCoreService {
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
});
};
}
async statusDetails(cwd: string): Promise<GitStatusDetails> {
@@ -385,11 +385,11 @@ export class GitCoreService {
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return GitPullResult.makeUnsafe({
return {
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
upstreamBranch: refreshed.upstreamRef,
});
};
}
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
+1 -1
View File
@@ -40,7 +40,7 @@ const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRu
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(
rules.map((rule) => KeybindingRule.makeUnsafe(rule)),
rules,
);
yield* fileSystem.writeFileString(configPath, encoded);
});
+2 -2
View File
@@ -313,7 +313,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
title: "Invalid keybinding rule",
}),
),
Effect.map((resolved) => ResolvedKeybindingRule.makeUnsafe(resolved)),
Effect.map((resolved) => resolved),
),
encode: (resolved) =>
@@ -456,7 +456,7 @@ const makeKeybindings = Effect.gen(function* () {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigJson)(
rules.map((rule) => KeybindingRule.makeUnsafe(rule)),
rules,
).pipe(
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
+33 -35
View File
@@ -22,9 +22,7 @@ import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
@@ -58,7 +56,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-1-create"),
commandId: CommandId.makeUnsafe("cmd-project-1-create"),
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
@@ -69,8 +67,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-1-create"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
@@ -82,8 +80,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.turn.start",
commandId: asCommandId("cmd-turn-start-1"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("msg-1"),
role: "user",
@@ -108,7 +106,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-replay-create"),
commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
@@ -119,8 +117,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-replay-create"),
threadId: asThreadId("thread-replay"),
commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
model: "gpt-5-codex",
@@ -132,8 +130,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.delete",
commandId: asCommandId("cmd-thread-replay-delete"),
threadId: asThreadId("thread-replay"),
commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
threadId: ThreadId.makeUnsafe("thread-replay"),
}),
);
@@ -158,7 +156,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-stream-create"),
commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
@@ -179,8 +177,8 @@ describe("OrchestrationEngine", () => {
yield* Effect.sleep("10 millis");
yield* engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-stream-thread-create"),
threadId: asThreadId("thread-stream"),
commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
model: "gpt-5-codex",
@@ -190,8 +188,8 @@ describe("OrchestrationEngine", () => {
});
yield* engine.dispatch({
type: "thread.meta.update",
commandId: asCommandId("cmd-stream-thread-update"),
threadId: asThreadId("thread-stream"),
commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
threadId: ThreadId.makeUnsafe("thread-stream"),
title: "domain-stream-updated",
});
eventTypes.push((yield* Queue.take(eventQueue)).type);
@@ -211,7 +209,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-turn-diff-create"),
commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
@@ -222,8 +220,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-turn-diff-create"),
threadId: asThreadId("thread-turn-diff"),
commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
model: "gpt-5-codex",
@@ -235,8 +233,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.turn.diff.complete",
commandId: asCommandId("cmd-turn-diff-complete"),
threadId: asThreadId("thread-turn-diff"),
commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
turnId: asTurnId("turn-1"),
completedAt: createdAt,
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
@@ -275,7 +273,7 @@ describe("OrchestrationEngine", () => {
const flakyStore: OrchestrationEventStoreShape = {
append(event) {
if (shouldFailFirstAppend && event.commandId === asCommandId("cmd-flaky-1")) {
if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
shouldFailFirstAppend = false;
return Effect.fail(
new PersistenceSqlError({
@@ -314,7 +312,7 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-flaky-create"),
commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
@@ -327,8 +325,8 @@ describe("OrchestrationEngine", () => {
runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-flaky-1"),
threadId: asThreadId("thread-flaky-fail"),
commandId: CommandId.makeUnsafe("cmd-flaky-1"),
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
model: "gpt-5-codex",
@@ -342,8 +340,8 @@ describe("OrchestrationEngine", () => {
const result = await runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-flaky-2"),
threadId: asThreadId("thread-flaky-ok"),
commandId: CommandId.makeUnsafe("cmd-flaky-2"),
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
model: "gpt-5-codex",
@@ -366,8 +364,8 @@ describe("OrchestrationEngine", () => {
system.run(
engine.dispatch({
type: "thread.turn.start",
commandId: asCommandId("cmd-invariant-missing-thread"),
threadId: asThreadId("thread-missing"),
commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
threadId: ThreadId.makeUnsafe("thread-missing"),
message: {
messageId: asMessageId("msg-missing"),
role: "user",
@@ -390,7 +388,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-duplicate-create"),
commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
@@ -402,8 +400,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-duplicate-1"),
threadId: asThreadId("thread-duplicate"),
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
model: "gpt-5-codex",
@@ -417,8 +415,8 @@ describe("OrchestrationEngine", () => {
system.run(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-duplicate-2"),
threadId: asThreadId("thread-duplicate"),
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
model: "gpt-5-codex",
@@ -5,7 +5,6 @@ import { execFileSync } from "node:child_process";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CheckpointRef,
CommandId,
EventId,
MessageId,
@@ -36,19 +35,13 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Refs.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
function checkpointRefForTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
const encodedThreadId = Buffer.from(threadId, "utf8").toString("base64url");
return CheckpointRef.makeUnsafe(`refs/t3/checkpoints/${encodedThreadId}/turn/${turnCount}`);
}
function createProviderServiceHarness(cwd: string, hasSession = true) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -109,7 +102,7 @@ async function waitForThread(
activities: ReadonlyArray<{ kind: string }>;
}> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === asThreadId("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
if (thread && predicate(thread)) {
return thread;
}
@@ -250,7 +243,7 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
@@ -261,8 +254,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-create"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
@@ -276,21 +269,21 @@ describe("CheckpointReactor", () => {
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForTurn(asThreadId("thread-1"), 0),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
}),
);
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForTurn(asThreadId("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
}),
);
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForTurn(asThreadId("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
}),
);
}
@@ -309,10 +302,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set-capture"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -334,7 +327,7 @@ describe("CheckpointReactor", () => {
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-1"),
});
await waitForGitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 0));
await waitForGitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0));
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
@@ -354,13 +347,25 @@ describe("CheckpointReactor", () => {
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(gitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 0))).toBe(true);
expect(gitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 1))).toBe(true);
expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0))).toBe(
true,
);
expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1))).toBe(
true,
);
expect(
gitShowFileAtRef(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 0), "README.md"),
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
"README.md",
),
).toBe("v1\n");
expect(
gitShowFileAtRef(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 1), "README.md"),
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
"README.md",
),
).toBe("v2\n");
});
@@ -374,8 +379,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: asCommandId("cmd-turn-start-for-baseline"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: MessageId.makeUnsafe("message-user-1"),
role: "user",
@@ -386,9 +391,13 @@ describe("CheckpointReactor", () => {
}),
);
await waitForGitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 0));
await waitForGitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0));
expect(
gitShowFileAtRef(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 0), "README.md"),
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
"README.md",
),
).toBe("v1\n");
});
@@ -403,10 +412,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set-missing-provider-cwd"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-missing"),
@@ -432,9 +441,15 @@ describe("CheckpointReactor", () => {
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
expect(gitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 1))).toBe(true);
expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1))).toBe(
true,
);
expect(
gitShowFileAtRef(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 1), "README.md"),
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
"README.md",
),
).toBe("v2\n");
});
@@ -445,10 +460,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set-checkpoint-captured"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -488,10 +503,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -507,11 +522,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: asCommandId("cmd-diff-1"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForTurn(asThreadId("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
@@ -521,11 +536,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: asCommandId("cmd-diff-2"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForTurn(asThreadId("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
@@ -536,8 +551,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-revert-request"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-revert-request"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -555,7 +570,9 @@ describe("CheckpointReactor", () => {
numTurns: 1,
});
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
expect(gitRefExists(harness.cwd, checkpointRefForTurn(asThreadId("thread-1"), 2))).toBe(false);
expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2))).toBe(
false,
);
});
it("appends an error activity when revert is requested without an active session", async () => {
@@ -565,8 +582,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-revert-no-session"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -1,17 +1,18 @@
import {
CheckpointRef,
CommandId,
EventId,
MessageId,
ProviderSessionId,
ThreadId,
TurnId,
type ProjectId,
type OrchestrationEvent,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Queue, Stream } from "effect";
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Refs.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
@@ -19,8 +20,6 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
type ReactorInput =
| {
readonly source: "runtime";
@@ -31,11 +30,6 @@ type ReactorInput =
readonly event: OrchestrationEvent;
};
function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
const encodedThreadId = Buffer.from(threadId, "utf8").toString("base64url");
return CheckpointRef.makeUnsafe(`${CHECKPOINT_REFS_PREFIX}/${encodedThreadId}/turn/${turnCount}`);
}
function toTurnId(value: string | undefined): TurnId | null {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? TurnId.makeUnsafe(normalized) : null;
@@ -48,11 +42,11 @@ function trimToNonEmpty(value: string | null | undefined): string | undefined {
function resolveThreadWorkspaceCwd(input: {
readonly thread: {
readonly projectId: string;
readonly projectId: ProjectId;
readonly worktreePath: string | null;
};
readonly projects: ReadonlyArray<{
readonly id: string;
readonly id: ProjectId;
readonly workspaceRoot: string;
}>;
}): string | undefined {
@@ -5,13 +5,11 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Stream } from "effect";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
import {
toOrchestrationCommandDecodeError,
toOrchestrationJsonParseError,
OrchestrationCommandInvariantError,
OrchestrationCommandPreviouslyRejectedError,
type OrchestrationDispatchError,
@@ -29,8 +27,6 @@ interface CommandEnvelope {
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
}
const decodeUnknownCommand = Schema.decodeUnknownEffect(OrchestrationCommand);
function commandToAggregateRef(command: OrchestrationCommand): {
readonly aggregateKind: "project" | "thread";
readonly aggregateId: ProjectId | ThreadId;
@@ -175,30 +171,12 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return yield* Deferred.await(result);
});
const dispatchUnknownCommand: OrchestrationEngineShape["dispatchUnknownCommand"] = (command) =>
Effect.gen(function* () {
const payload =
typeof command === "string"
? yield* Effect.try({
try: () => JSON.parse(command) as unknown,
catch: toOrchestrationJsonParseError,
})
: command;
const decoded = yield* decodeUnknownCommand(payload).pipe(
Effect.mapError(toOrchestrationCommandDecodeError),
);
return yield* dispatch(decoded);
});
const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
Stream.fromPubSub(eventPubSub);
return {
getReadModel,
readEvents,
dispatchUnknownCommand,
dispatch,
streamDomainEvents,
} satisfies OrchestrationEngineShape;
@@ -18,7 +18,6 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQu
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -225,7 +224,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
assert.deepEqual(snapshot.threads, [
{
id: asThreadId("thread-1"),
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
model: "gpt-5-codex",
@@ -269,7 +268,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
},
],
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asProviderSessionId("provider-session-1"),
@@ -26,9 +26,7 @@ import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
@@ -126,7 +124,7 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
@@ -137,8 +135,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-create"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
@@ -165,8 +163,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: asCommandId("cmd-turn-start-1"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-1"),
role: "user",
@@ -185,7 +183,7 @@ describe("ProviderCommandReactor", () => {
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === asThreadId("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
});
@@ -196,10 +194,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -215,8 +213,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: asCommandId("cmd-turn-interrupt"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-interrupt"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: now,
}),
@@ -235,10 +233,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set-for-approval"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -254,8 +252,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: asCommandId("cmd-approval-respond"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("approval-request-1"),
decision: "accept",
createdAt: now,
@@ -277,10 +275,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-set-for-stop"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -296,15 +294,15 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.stop",
commandId: asCommandId("cmd-session-stop"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-stop"),
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === asThreadId("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.providerSessionId).toBeNull();
@@ -28,9 +28,7 @@ import {
} from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
@@ -78,7 +76,7 @@ async function waitForThread(
activities: ReadonlyArray<{ kind: string }>;
}> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === asThreadId("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
if (thread && predicate(thread)) {
return thread;
}
@@ -132,7 +130,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: asCommandId("cmd-provider-project-create"),
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
@@ -143,8 +141,8 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: asCommandId("cmd-thread-create"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
@@ -156,10 +154,10 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.session.set",
commandId: asCommandId("cmd-session-seed"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
@@ -18,7 +18,7 @@ import type {
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type { OrchestrationDispatchError, OrchestrationEngineError } from "../Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
export interface OrchestrationEngineShape {
@@ -39,18 +39,6 @@ export interface OrchestrationEngineShape {
fromSequenceExclusive: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
* Validate and dispatch an unknown command payload.
*
* Accepts either parsed values or raw JSON strings.
*
* @param command - Unknown command payload.
* @returns Effect containing the sequence of the persisted event.
*/
readonly dispatchUnknownCommand: (
command: unknown,
) => Effect.Effect<{ sequence: number }, OrchestrationEngineError, never>;
/**
* Dispatch a validated orchestration command.
*
@@ -5,10 +5,8 @@ import { Effect } from "effect";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
describe("decider project scripts", () => {
@@ -20,7 +18,7 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: asCommandId("cmd-project-create-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
@@ -46,9 +44,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-scripts"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create-scripts"),
correlationId: CommandId.makeUnsafe("cmd-project-create-scripts"),
metadata: {},
payload: {
projectId: asProjectId("project-scripts"),
@@ -76,7 +74,7 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: asCommandId("cmd-project-update-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-update-scripts"),
projectId: asProjectId("project-scripts"),
scripts: Array.from(scripts),
},
@@ -100,9 +98,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-1"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
correlationId: CommandId.makeUnsafe("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-1"),
@@ -120,15 +118,15 @@ describe("decider project scripts", () => {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-1"),
aggregateId: ThreadId.makeUnsafe("thread-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create"),
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
metadata: {},
payload: {
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
@@ -144,8 +142,8 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: asCommandId("cmd-turn-start"),
threadId: asThreadId("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("message-user-1"),
role: "user",
@@ -23,7 +23,6 @@ import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
@@ -36,7 +35,7 @@ class FakeCodexManager extends CodexAppServerManager {
sessionId: asSessionId("sess-1"),
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
threadId: ProviderThreadId.makeUnsafe("thread-1"),
cwd: input.cwd,
createdAt: now,
updatedAt: now,
@@ -46,7 +45,7 @@ class FakeCodexManager extends CodexAppServerManager {
public sendTurnImpl = vi.fn(
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
threadId: asThreadId("thread-1"),
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
}),
);
@@ -56,12 +55,12 @@ class FakeCodexManager extends CodexAppServerManager {
);
public readThreadImpl = vi.fn(async (_sessionId: ProviderSessionId) => ({
threadId: asThreadId("thread-1"),
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turns: [],
}));
public rollbackThreadImpl = vi.fn(async (_sessionId: ProviderSessionId, _numTurns: number) => ({
threadId: asThreadId("thread-1"),
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turns: [],
}));
@@ -194,7 +193,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
itemId: asItemId("msg_1"),
payload: {
@@ -21,7 +21,7 @@ import {
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Schema, Stream } from "effect";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -46,7 +46,6 @@ import {
} from "../../persistence/Layers/Sqlite.ts";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -568,7 +567,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
};
@@ -616,7 +615,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Command run",
@@ -628,7 +627,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
delta: "hello",
},
@@ -638,7 +637,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
},
+8
View File
@@ -4,8 +4,10 @@ import { NodeServices } from "@effect/platform-node";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
import { ServerConfig } from "./config";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { CheckpointStore } from "./checkpointing/Services/CheckpointStore";
import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts";
import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore";
@@ -55,6 +57,7 @@ export function makeServerRuntimeServicesLayer(): Layer.Layer<
| OrchestrationEngineService
| ProjectionSnapshotQuery
| CheckpointStore
| CheckpointDiffQuery
| OrchestrationReactor
| TerminalManager
| Keybindings,
@@ -67,11 +70,16 @@ export function makeServerRuntimeServicesLayer(): Layer.Layer<
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(checkpointStoreLayer),
);
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
checkpointStoreLayer,
checkpointDiffQueryLayer,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
+4 -3
View File
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapterShape, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
import { TerminalManagerRuntime } from "./terminalManager";
import { Encoding } from "effect";
class FakePtyProcess implements PtyProcess {
readonly writes: string[] = [];
@@ -107,15 +108,15 @@ function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInpu
}
function historyLogName(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
return `terminal_${Encoding.encodeBase64Url(threadId)}.log`;
}
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
return `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
+3 -3
View File
@@ -13,7 +13,7 @@ import {
type TerminalSessionSnapshot,
type TerminalSessionStatus,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, ServiceMap } from "effect";
import { Effect, Encoding, Layer, Schema, ServiceMap } from "effect";
import { createLogger } from "./logger";
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
@@ -269,11 +269,11 @@ function legacySafeThreadId(threadId: string): string {
}
function toSafeThreadId(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
return `terminal_${Encoding.encodeBase64Url(threadId)}`;
}
function toSafeTerminalId(terminalId: string): string {
return Buffer.from(terminalId, "utf8").toString("base64url");
return Encoding.encodeBase64Url(terminalId);
}
function toSessionKey(threadId: string, terminalId: string): string {
+21 -1
View File
@@ -175,7 +175,7 @@ class MockTerminalManager implements TerminalManagerShape {
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
for (const key of this.sessions.keys()) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
@@ -837,6 +837,26 @@ describe("WebSocket Server", () => {
expect(response.error?.message).toContain("Thread 'thread-missing' not found.");
});
it("returns error when requesting turn diff with an inverted range", async () => {
server = await createTestServer({ cwd: "/test" });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, {
threadId: "thread-any",
fromTurnCount: 2,
toTurnCount: 1,
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain(
"fromTurnCount must be less than or equal to toTurnCount",
);
});
it("returns error when requesting full thread diff for unknown thread", async () => {
server = await createTestServer({ cwd: "/test" });
const addr = server.address();
+29 -153
View File
@@ -4,19 +4,19 @@ import path from "node:path";
import type { Duplex } from "node:stream";
import {
CheckpointRef,
CommandId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProjectId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
WebSocketRequest,
WebSocketResponse,
WsPush,
WsResponse,
} from "@t3tools/contracts";
import { NodeHttpServer } from "@effect/platform-node";
import { Cause, Effect, Exit, Layer, Schema, Scope, ServiceMap, Stream } from "effect";
import { Cause, Effect, Exit, Layer, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
@@ -37,7 +37,7 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
import { CheckpointStore } from "./checkpointing/Services/CheckpointStore";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open } from "./open";
import { ServerConfig } from "./config";
@@ -133,22 +133,14 @@ function websocketRawToString(raw: unknown): string | null {
return null;
}
function stripRequestTag<T extends { _tag: string }>(body: T): Omit<T, "_tag"> {
const { _tag: _ignoredTag, ...rest } = body;
return rest;
}
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
function checkpointRefForThreadTurn(threadId: string, turnCount: number): CheckpointRef {
const encodedThreadId = Buffer.from(threadId, "utf8").toString("base64url");
return CheckpointRef.makeUnsafe(`${CHECKPOINT_REFS_PREFIX}/${encodedThreadId}/turn/${turnCount}`);
function stripRequestTag<T extends { _tag: string }>(body: T) {
return Struct.omit(body, ["_tag"]);
}
export type ServerCoreRuntimeServices =
| OrchestrationEngineService
| ProjectionSnapshotQuery
| CheckpointStore
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService;
@@ -301,7 +293,7 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const liveCheckpointStore = yield* CheckpointStore;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const liveProviderService = yield* ProviderService;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = yield* Open;
@@ -338,10 +330,10 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
if (!existing) {
const createdAt = new Date().toISOString();
const projectName = path.basename(cwd) || "project";
yield* orchestrationEngine.dispatchUnknownCommand({
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: crypto.randomUUID(),
projectId: crypto.randomUUID(),
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
@@ -351,110 +343,6 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
}
const routeRequest = Effect.fn(function* (request: WebSocketRequest) {
const computeTurnDiff = Effect.fn(function* (input: {
readonly threadId: string;
readonly fromTurnCount: number;
readonly toTurnCount: number;
}) {
if (input.fromTurnCount > input.toTurnCount) {
throw new Error(
`Invalid turn diff range for thread '${input.threadId}': from ${input.fromTurnCount} exceeds to ${input.toTurnCount}.`,
);
}
if (input.fromTurnCount === input.toTurnCount) {
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff: "",
};
}
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
throw new Error(`Thread '${input.threadId}' not found.`);
}
const maxTurnCount = thread.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
if (input.toTurnCount > maxTurnCount) {
throw new Error(
`Turn diff range exceeds current turn count for thread '${input.threadId}': requested ${input.toTurnCount}, current ${maxTurnCount}.`,
);
}
const workspaceCwd =
thread.worktreePath?.trim() ||
snapshot.projects.find((project) => project.id === thread.projectId)?.workspaceRoot?.trim();
if (!workspaceCwd) {
throw new Error(
`Invariant violation: workspace path missing for thread '${input.threadId}' when computing turn diff.`,
);
}
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
throw new Error(
`Checkpoint is unavailable for turn ${input.fromTurnCount} in thread ${input.threadId}.`,
);
}
const toCheckpointRef = thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
throw new Error(
`Checkpoint is unavailable for turn ${input.toTurnCount} in thread ${input.threadId}.`,
);
}
const [fromExists, toExists] = yield* Effect.all(
[
liveCheckpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
liveCheckpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
if (!fromExists) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.fromTurnCount} in thread ${input.threadId}.`,
);
}
if (!toExists) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.toTurnCount} in thread ${input.threadId}.`,
);
}
const diff = yield* liveCheckpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
});
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
});
switch (request.body._tag) {
case ORCHESTRATION_WS_METHODS.getSnapshot:
return yield* projectionReadModelQuery.getSnapshot();
@@ -466,16 +354,12 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
const body = stripRequestTag(request.body);
return yield* computeTurnDiff(body);
return yield* checkpointDiffQuery.getTurnDiff(body);
}
case ORCHESTRATION_WS_METHODS.getFullThreadDiff: {
const body = stripRequestTag(request.body);
return yield* computeTurnDiff({
threadId: body.threadId,
fromTurnCount: 0,
toTurnCount: body.toTurnCount,
});
return yield* checkpointDiffQuery.getFullThreadDiff(body);
}
case ORCHESTRATION_WS_METHODS.replayEvents: {
@@ -599,46 +483,38 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
const messageText = websocketRawToString(raw);
if (messageText === null) {
const errorResponse = yield* encodeResponse(
new WebSocketResponse({
id: "unknown",
error: { message: "Invalid request format: Failed to read message" },
}),
);
const errorResponse = yield* encodeResponse({
id: "unknown",
error: { message: "Invalid request format: Failed to read message" },
});
ws.send(errorResponse);
return;
}
const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText);
if (request._tag === "Failure") {
const errorResponse = yield* encodeResponse(
new WebSocketResponse({
id: "unknown",
error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
}),
);
const errorResponse = yield* encodeResponse({
id: "unknown",
error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
});
ws.send(errorResponse);
return;
}
const result = yield* Effect.exit(routeRequest(request.value));
if (result._tag === "Failure") {
const errorResponse = yield* encodeResponse(
new WebSocketResponse({
id: request.value.id,
error: { message: Cause.pretty(result.cause) },
}),
);
const errorResponse = yield* encodeResponse({
id: request.value.id,
error: { message: Cause.pretty(result.cause) },
});
ws.send(errorResponse);
return;
}
const response = yield* encodeResponse(
new WebSocketResponse({
id: request.value.id,
result: result.value,
}),
);
const response = yield* encodeResponse({
id: request.value.id,
result: result.value,
});
ws.send(response);
});
@@ -1,4 +1,4 @@
import type { GitBranch } from "@t3tools/contracts";
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
@@ -19,8 +19,9 @@ const branches: GitBranch[] = [
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
@@ -31,8 +32,9 @@ describe("deriveSyncedLocalBranch", () => {
});
it("does not sync when creating a new worktree", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
@@ -43,8 +45,9 @@ describe("deriveSyncedLocalBranch", () => {
});
it("does not sync when thread already targets a worktree path", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeThreadId: threadId,
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
@@ -1,7 +1,7 @@
import type { GitBranch } from "@t3tools/contracts";
import type { GitBranch, ThreadId } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: string | undefined;
activeThreadId: ThreadId | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
+14 -12
View File
@@ -1,14 +1,14 @@
import type { GitBranch } from "@t3tools/contracts";
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useNativeApi } from "../hooks/useNativeApi";
import { asThreadId, newCommandId } from "../lib/orchestrationIds";
import { newCommandId } from "../lib/orchestrationIds";
import {
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
@@ -24,7 +24,7 @@ import {
import { ChevronDownIcon } from "lucide-react";
interface BranchToolbarProps {
threadId: string;
threadId: ThreadId;
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
@@ -39,7 +39,6 @@ export default function BranchToolbar({
onComposerFocusRequest,
}: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
@@ -54,7 +53,7 @@ export default function BranchToolbar({
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(api, branchCwd));
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = branchesQuery.data?.branches ?? [];
const branchNames = branches.map((branch) => branch.name);
@@ -72,11 +71,11 @@ export default function BranchToolbar({
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation(
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
);
const createBranchMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
);
// ── Effects ───────────────────────────────────────────────────────────
@@ -92,12 +91,13 @@ export default function BranchToolbar({
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: asThreadId(activeThreadId),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
@@ -115,7 +115,6 @@ export default function BranchToolbar({
queryBranches,
envMode,
dispatch,
api,
]);
useEffect(() => {
@@ -132,6 +131,7 @@ export default function BranchToolbar({
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = activeThread?.session?.sessionId;
@@ -140,7 +140,7 @@ export default function BranchToolbar({
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: asThreadId(activeThreadId),
threadId: activeThreadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
@@ -149,7 +149,7 @@ export default function BranchToolbar({
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: asThreadId(activeThreadId),
threadId: activeThreadId,
branch,
worktreePath,
});
@@ -158,6 +158,7 @@ export default function BranchToolbar({
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
@@ -198,6 +199,7 @@ export default function BranchToolbar({
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
+9 -5
View File
@@ -3,7 +3,7 @@ import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
import { useNativeApi } from "../hooks/useNativeApi";
import { readNativeApi } from "../nativeApi";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { preferredTerminalEditor } from "../terminal-links";
@@ -13,12 +13,11 @@ interface ChatMarkdownProps {
}
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
const api = useNativeApi();
const markdownComponents = useMemo<Components>(
() => ({
a({ node: _node, href, ...props }) {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
if (!targetPath || !api) {
if (!targetPath) {
return <a {...props} href={href} target="_blank" rel="noreferrer" />;
}
@@ -29,13 +28,18 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void api.shell.openInEditor(targetPath, preferredTerminalEditor());
const api = readNativeApi();
if (api) {
void api.shell.openInEditor(targetPath, preferredTerminalEditor());
} else {
console.warn("Native API not found. Unable to open file in editor.");
}
}}
/>
);
},
}),
[api, cwd],
[cwd],
);
return (
+101 -98
View File
@@ -1,15 +1,25 @@
import {
type ApprovalRequestId,
DEFAULT_MODEL,
DEFAULT_REASONING,
EDITORS,
type EditorId,
type KeybindingCommand,
type NativeApi,
type MessageId,
MODEL_OPTIONS,
type ProjectId,
type ProjectEntry,
type ProjectScript,
ModelSlug,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
REASONING_OPTIONS,
type ReasoningEffort,
type ResolvedKeybindingsConfig,
type ProviderApprovalDecision,
type ThreadId,
type TurnId,
resolveModelSlug,
} from "@t3tools/contracts";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -27,14 +37,6 @@ import {
detectComposerTrigger,
replaceTextRange,
} from "../composer-logic";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
MODEL_OPTIONS,
REASONING_OPTIONS,
ReasoningEffort,
resolveModelSlug,
} from "../model-logic";
import {
derivePendingApprovals,
derivePhase,
@@ -66,7 +68,6 @@ import {
} from "../keybindings";
import ChatMarkdown from "./ChatMarkdown";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { useNativeApi } from "../hooks/useNativeApi";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import {
BotIcon,
@@ -101,13 +102,8 @@ import {
} from "~/projectScripts";
import { Toggle } from "./ui/toggle";
import { SidebarTrigger } from "./ui/sidebar";
import {
asApprovalRequestId,
asProjectId,
asThreadId,
newCommandId,
newMessageId,
} from "~/lib/orchestrationIds";
import { newCommandId, newMessageId } from "~/lib/orchestrationIds";
import { readNativeApi } from "~/nativeApi";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -326,7 +322,7 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
});
interface ChatViewProps {
threadId: string;
threadId: ThreadId;
}
export default function ChatView({ threadId }: ChatViewProps) {
@@ -336,12 +332,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
strict: false,
select: (params) => parseDiffRouteSearch(params),
});
const api = useNativeApi();
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(
gitCreateWorktreeMutationOptions({ api, queryClient }),
);
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const [prompt, setPrompt] = useState("");
const promptRef = useRef(prompt);
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
@@ -353,7 +346,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>([]);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
@@ -429,7 +422,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
const byMessageId = new Map<string, TurnDiffSummary>();
const byMessageId = new Map<MessageId, TurnDiffSummary>();
for (const summary of turnDiffSummaries) {
if (!summary.assistantMessageId) continue;
byMessageId.set(summary.assistantMessageId, summary);
@@ -437,7 +430,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
return byMessageId;
}, [turnDiffSummaries]);
const revertTurnCountByUserMessageId = useMemo(() => {
const byUserMessageId = new Map<string, number>();
const byUserMessageId = new Map<MessageId, number>();
for (let index = 0; index < timelineEntries.length; index += 1) {
const entry = timelineEntries[index];
if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
@@ -536,14 +529,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const keybindingsQuery = useQuery({
...serverConfigQueryOptions(api),
...serverConfigQueryOptions(),
select: (config) => config.keybindings,
});
const workspaceEntriesQuery = useQuery(
projectSearchEntriesQueryOptions({
api,
cwd: gitCwd,
query: effectivePathQuery,
enabled: isPathTrigger,
@@ -689,6 +681,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
if (!activeThreadId || !api) return;
const isFinalTerminal = (activeThread?.terminalIds.length ?? 0) <= 1;
const fallbackExitWrite = () =>
@@ -714,7 +707,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThread?.terminalIds.length, activeThreadId, api, dispatch],
[activeThread?.terminalIds.length, activeThreadId, dispatch],
);
const runProjectScript = useCallback(
async (
@@ -727,6 +720,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
rememberAsLastInvoked?: boolean;
},
) => {
const api = readNativeApi();
if (!api || !activeThreadId || !activeProject || !activeThread) return;
if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => {
@@ -799,23 +793,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
},
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
[activeProject, activeThread, activeThreadId, dispatch, gitCwd],
);
const persistProjectScripts = useCallback(
async (input: {
projectId: string;
projectId: ProjectId;
projectCwd: string;
previousScripts: ProjectScript[];
nextScripts: ProjectScript[];
keybinding?: string | null;
keybindingCommand: KeybindingCommand;
}) => {
const api = readNativeApi();
if (!api) return;
await api.orchestration.dispatchCommand({
type: "project.meta.update",
commandId: newCommandId(),
projectId: asProjectId(input.projectId),
projectId: input.projectId,
scripts: input.nextScripts,
});
@@ -836,7 +831,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
}
},
[api, queryClient],
[queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
@@ -911,6 +906,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
scheduleComposerFocus();
const api = readNativeApi();
if (!api) return;
const runningThreadIds = state.threads
@@ -927,7 +923,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: asThreadId(threadId),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined),
@@ -1182,7 +1178,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
]);
const setThreadError = useCallback(
(threadId: string | null, error: string | null) => {
(threadId: ThreadId | null, error: string | null) => {
if (!threadId) return;
dispatch({
type: "SET_ERROR",
@@ -1298,9 +1294,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onRevertToTurnCount = useCallback(
async (turnCount: number) => {
if (!api || !activeThread || isRevertingCheckpoint) {
return;
}
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSending || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
@@ -1322,7 +1318,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await api.orchestration.dispatchCommand({
type: "thread.checkpoint.revert",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
turnCount,
createdAt: new Date().toISOString(),
});
@@ -1335,11 +1331,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsRevertingCheckpoint(false);
}
},
[activeThread, api, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
);
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return;
@@ -1363,7 +1360,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
@@ -1397,7 +1394,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
title,
});
}
@@ -1434,7 +1431,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
message: {
messageId: newMessageId(),
role: "user",
@@ -1456,17 +1453,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
const onInterrupt = async () => {
const api = readNativeApi();
if (!api || !activeThread) return;
await api.orchestration.dispatchCommand({
type: "thread.turn.interrupt",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
createdAt: new Date().toISOString(),
});
};
const onRespondToApproval = useCallback(
async (requestId: string, decision: ProviderApprovalDecision) => {
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
const api = readNativeApi();
if (!api || !activeThreadId) return;
setRespondingRequestIds((existing) =>
@@ -1476,8 +1475,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
await api.orchestration.dispatchCommand({
type: "thread.approval.respond",
commandId: newCommandId(),
threadId: asThreadId(activeThreadId),
requestId: asApprovalRequestId(requestId),
threadId: activeThreadId,
requestId,
decision,
createdAt: new Date().toISOString(),
});
@@ -1491,23 +1490,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
},
[activeThreadId, api, dispatch],
[activeThreadId, dispatch],
);
const onModelSelect = useCallback(
(model: ModelSlug) => {
const api = readNativeApi();
if (!activeThread) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: asThreadId(activeThread.id),
threadId: activeThread.id,
model: resolveModelSlug(model),
});
}
scheduleComposerFocus();
},
[activeThread, api, scheduleComposerFocus],
[activeThread, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
@@ -1629,7 +1629,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}, [diffOpen, navigate, threadId]);
const onOpenTurnDiff = useCallback(
(turnId: string, filePath?: string) => {
(turnId: TurnId, filePath?: string) => {
void navigate({
to: "/$threadId",
params: { threadId },
@@ -1644,7 +1644,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
[navigate, threadId],
);
const onRevertUserMessage = useCallback(
(messageId: string) => {
(messageId: MessageId) => {
const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
if (typeof targetTurnCount !== "number") {
return;
@@ -1698,7 +1698,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={diffOpen}
onRunProjectScript={(script) => {
@@ -1971,35 +1970,39 @@ export default function ChatView({ threadId }: ChatViewProps) {
/>
)}
{activeThread.terminalOpen && api && activeProject && (
<ThreadTerminalDrawer
key={activeThread.id}
api={api}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
/>
)}
{(() => {
if (!activeThread.terminalOpen || !activeProject) {
return null;
}
return (
<ThreadTerminalDrawer
key={activeThread.id}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
/>
);
})()}
{expandedImage && (
<div
@@ -2040,13 +2043,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
interface ChatHeaderProps {
activeThreadId: string;
activeThreadId: ThreadId;
activeThreadTitle: string;
activeProjectName: string | undefined;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
api: NativeApi | undefined;
gitCwd: string | null;
diffOpen: boolean;
onRunProjectScript: (script: ProjectScript) => void;
@@ -2062,7 +2064,6 @@ const ChatHeader = memo(function ChatHeader({
activeProjectScripts,
preferredScriptId,
keybindings,
api,
gitCwd,
diffOpen,
onRunProjectScript,
@@ -2100,9 +2101,7 @@ const ChatHeader = memo(function ChatHeader({
{activeProjectName && (
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
)}
{activeProjectName && (
<GitActionsControl api={api} gitCwd={gitCwd} activeThreadId={activeThreadId} />
)}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
<Toggle
className="shrink-0"
pressed={diffOpen}
@@ -2134,8 +2133,11 @@ const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: st
interface PendingApprovalsPanelProps {
pendingApprovals: PendingApproval[];
respondingRequestIds: string[];
onRespondToApproval: (requestId: string, decision: ProviderApprovalDecision) => Promise<void>;
respondingRequestIds: ApprovalRequestId[];
onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
}
const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
@@ -2211,13 +2213,13 @@ interface MessagesTimelineProps {
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
turnDiffSummaryByAssistantMessageId: Map<string, TurnDiffSummary>;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
nowIso: string;
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
onOpenTurnDiff: (turnId: string, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<string, number>;
onRevertUserMessage: (messageId: string) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<MessageId, number>;
onRevertUserMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (image: ExpandedImagePreview) => void;
markdownCwd: string | undefined;
@@ -2667,7 +2669,7 @@ const OpenInPicker = memo(function OpenInPicker({
activeThreadId,
}: {
keybindings: ResolvedKeybindingsConfig;
activeThreadId: string | null;
activeThreadId: ThreadId | null;
}) {
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
@@ -2692,13 +2694,13 @@ const OpenInPicker = memo(function OpenInPicker({
] satisfies { label: string; Icon: Icon; value: EditorId }[];
const primaryOption = options.find(({ value }) => value === lastEditor);
const api = useNativeApi();
const { state } = useStore();
const activeThread = state.threads.find((t) => t.id === activeThreadId);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const openInEditor = useCallback(
(editorId: EditorId | null) => {
const api = readNativeApi();
if (!api || !activeProject) return;
const editor = editorId ?? lastEditor;
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
@@ -2706,7 +2708,7 @@ const OpenInPicker = memo(function OpenInPicker({
localStorage.setItem(LAST_EDITOR_KEY, editor);
setLastEditor(editor);
},
[api, activeProject, activeThread, lastEditor, setLastEditor],
[activeProject, activeThread, lastEditor, setLastEditor],
);
const openFavoriteEditorShortcutLabel = useMemo(
@@ -2716,6 +2718,7 @@ const OpenInPicker = memo(function OpenInPicker({
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
const api = readNativeApi();
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !activeProject) return;
@@ -2725,7 +2728,7 @@ const OpenInPicker = memo(function OpenInPicker({
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, activeThread, keybindings, lastEditor]);
}, [activeProject, activeThread, keybindings, lastEditor]);
return (
<Group aria-label="Subscription actions">
+8 -11
View File
@@ -2,13 +2,13 @@ import { parsePatchFiles } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -81,7 +81,6 @@ interface DiffPanelProps {
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const api = useNativeApi();
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { state } = useStore();
@@ -90,13 +89,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const turnStripRef = useRef<HTMLDivElement>(null);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const params = useParams({ strict: false });
const rawSearch = useSearch({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const activeThreadId = routeThreadId;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
@@ -169,7 +166,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
}, [orderedTurnDiffSummaries, selectedTurn]);
const activeCheckpointDiffQuery = useQuery(
checkpointDiffQueryOptions(api, {
checkpointDiffQueryOptions({
threadId: activeThreadId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
@@ -216,7 +213,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const selectTurn = (turnId: string) => {
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
+19 -17
View File
@@ -1,4 +1,4 @@
import { type GitStatusResult, type GitStackedAction, type NativeApi } from "@t3tools/contracts";
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
@@ -39,11 +39,11 @@ import {
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
activeThreadId: string | null;
activeThreadId: ThreadId | null;
}
function getMenuActionDisabledReason(
@@ -136,7 +136,7 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
return <InfoIcon className={iconClassName} />;
}
export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitActionsControlProps) {
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
@@ -145,11 +145,9 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(api, gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
@@ -163,12 +161,12 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const initMutation = useMutation(gitInitMutationOptions({ api, cwd: gitCwd, queryClient }));
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ api, cwd: gitCwd, queryClient }),
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ api, cwd: gitCwd, queryClient }));
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
const isDefaultBranch = useMemo(() => {
@@ -192,6 +190,7 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
const api = readNativeApi();
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
@@ -203,10 +202,11 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[api, gitStatusForActions?.branch, isDefaultBranch],
[gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
if (!api) {
toastManager.add({
type: "error",
@@ -232,8 +232,7 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
data: threadToastData,
});
});
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
}, [gitStatusForActions?.openPr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
@@ -329,8 +328,10 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
actionProps: {
children: "Open PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api?.shell.openExternal(prUrl);
void api.shell.openExternal(prUrl);
},
},
}
@@ -356,8 +357,8 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
});
}
},
[
api,
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.openPr?.url,
@@ -447,6 +448,7 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
const openChangedFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
if (!api || !gitCwd) {
toastManager.add({
type: "error",
@@ -465,7 +467,7 @@ export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitAc
});
});
},
[api, gitCwd, threadToastData],
[gitCwd, threadToastData],
);
if (!gitCwd) return null;
+34 -40
View File
@@ -1,25 +1,23 @@
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import {
DEFAULT_MODEL,
ProjectId,
ThreadId,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { DEFAULT_MODEL } from "../model-logic";
import {
asProjectId,
asThreadId,
newCommandId,
newProjectId,
newThreadId,
} from "../lib/orchestrationIds";
import { newCommandId, newProjectId, newThreadId } from "../lib/orchestrationIds";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import {
@@ -37,6 +35,7 @@ import {
SidebarTrigger,
} from "./ui/sidebar";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
@@ -143,33 +142,33 @@ function T3Wordmark() {
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const navigate = useNavigate();
const { settings: appSettings } = useAppSettings();
const params = useParams({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
...serverConfigQueryOptions(api),
...serverConfigQueryOptions(),
select: (config) => config.keybindings,
});
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(
gitRemoveWorktreeMutationOptions({ api, queryClient }),
);
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => new Map<string, boolean>(), []);
const pendingApprovalByThreadId = useMemo(() => new Map<ThreadId, boolean>(), []);
const handleNewThread = useCallback(
(
projectId: string,
projectId: ProjectId,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
): Promise<void> => {
const api = readNativeApi();
if (!api) return Promise.resolve();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
@@ -180,7 +179,7 @@ export default function Sidebar() {
type: "thread.create",
commandId: newCommandId(),
threadId,
projectId: asProjectId(projectId),
projectId,
title: "New thread",
model,
branch: options?.branch ?? null,
@@ -202,11 +201,11 @@ export default function Sidebar() {
});
})();
},
[api, dispatch, navigate, state.projects],
[dispatch, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: string) => {
(projectId: ProjectId) => {
const latestThread = state.threads
.filter((thread) => thread.projectId === projectId)
.toSorted((a, b) => {
@@ -228,6 +227,7 @@ export default function Sidebar() {
async (rawCwd: string) => {
const cwd = rawCwd.trim();
if (!cwd || isAddingProject) return;
const api = readNativeApi();
setIsAddingProject(true);
try {
@@ -240,7 +240,7 @@ export default function Sidebar() {
const projectId = newProjectId();
const createdAt = new Date().toISOString();
const title = cwd.split(/[/\\]/).filter(Boolean).at(-1) ?? cwd;
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
@@ -257,14 +257,7 @@ export default function Sidebar() {
setAddingProject(false);
}
},
[
api,
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
state.projects,
state.threads,
],
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
);
const handleAddProject = () => {
@@ -272,6 +265,7 @@ export default function Sidebar() {
};
const handlePickFolder = async () => {
const api = readNativeApi();
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
@@ -284,7 +278,8 @@ export default function Sidebar() {
};
const handleThreadContextMenu = useCallback(
async (threadId: string, position: { x: number; y: number }) => {
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
@@ -324,7 +319,7 @@ export default function Sidebar() {
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: asThreadId(threadId),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
@@ -344,7 +339,7 @@ export default function Sidebar() {
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: asThreadId(threadId),
threadId,
});
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
@@ -384,9 +379,7 @@ export default function Sidebar() {
}
},
[
api,
appSettings.confirmThreadDelete,
dispatch,
navigate,
removeWorktreeMutation,
routeThreadId,
@@ -396,7 +389,8 @@ export default function Sidebar() {
);
const handleProjectContextMenu = useCallback(
async (projectId: string, position: { x: number; y: number }) => {
async (projectId: ProjectId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
@@ -423,7 +417,7 @@ export default function Sidebar() {
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: newCommandId(),
projectId: asProjectId(projectId),
projectId,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error deleting project.";
@@ -435,7 +429,7 @@ export default function Sidebar() {
});
}
},
[api, state.projects, state.threads],
[state.projects, state.threads],
);
useEffect(() => {
@@ -687,7 +681,7 @@ export default function Sidebar() {
if (event.key === "Escape") setAddingProject(false);
}}
/>
{isElectron && api && (
{isElectron && (
<button
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
@@ -1,6 +1,6 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { type ThreadId } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
@@ -25,6 +25,7 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ThreadTerminalGroup,
} from "../types";
import { readNativeApi } from "~/nativeApi";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -107,8 +108,7 @@ function terminalThemeFromApp(): ITheme {
}
interface TerminalViewportProps {
api: NativeApi;
threadId: string;
threadId: ThreadId;
terminalId: string;
cwd: string;
runtimeEnv?: Record<string, string>;
@@ -119,7 +119,6 @@ interface TerminalViewportProps {
}
function TerminalViewport({
api,
threadId,
terminalId,
cwd,
@@ -155,6 +154,9 @@ function TerminalViewport({
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const api = readNativeApi();
if (!api) return;
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -210,14 +212,10 @@ function TerminalViewport({
end: { x: match.end, y: bufferLineNumber },
},
activate: (event: MouseEvent) => {
if (!isTerminalLinkActivation(event)) {
return;
}
if (!isTerminalLinkActivation(event)) return;
const latestTerminal = terminalRef.current;
if (!latestTerminal) {
return;
}
if (!latestTerminal) return;
if (match.kind === "url") {
void api.shell.openExternal(match.text).catch((error) => {
@@ -297,7 +295,7 @@ function TerminalViewport({
}
};
const unsubscribe = api.terminal.onEvent((event) => {
const unsubscribe = api?.terminal.onEvent((event) => {
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -372,7 +370,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, runtimeEnv, terminalId, threadId]);
}, [cwd, runtimeEnv, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
@@ -387,9 +385,10 @@ function TerminalViewport({
}, [autoFocus, focusRequestId]);
useEffect(() => {
const api = readNativeApi();
const terminal = terminalRef.current;
const fitAddon = fitAddonRef.current;
if (!terminal || !fitAddon) return;
if (!api || !terminal || !fitAddon) return;
const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
const frame = window.requestAnimationFrame(() => {
fitAddon.fit();
@@ -408,14 +407,12 @@ function TerminalViewport({
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
threadId: ThreadId;
cwd: string;
runtimeEnv?: Record<string, string>;
height: number;
@@ -464,7 +461,6 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
}
export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
runtimeEnv,
@@ -783,7 +779,6 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
api={api}
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
@@ -801,7 +796,6 @@ export default function ThreadTerminalDrawer({
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
api={api}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
+4 -1
View File
@@ -133,7 +133,10 @@ function CommandEmpty({ className, ...props }: React.ComponentProps<typeof Autoc
function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className="-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2"
className={cn(
"-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2",
className,
)}
{...props}
/>
);
+1
View File
@@ -49,6 +49,7 @@ function SheetViewport({
side === "left" && "flex justify-start",
side === "right" && "flex justify-end",
variant === "inset" && "sm:p-4",
className,
)}
data-slot="sheet-viewport"
{...props}
+6 -4
View File
@@ -3,6 +3,7 @@
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import { useParams } from "@tanstack/react-router";
import { ThreadId } from "@t3tools/contracts";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -16,7 +17,7 @@ import { buttonVariants } from "~/components/ui/button";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: string | null;
threadId?: ThreadId | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
};
@@ -48,17 +49,18 @@ interface ToastProviderProps extends Toast.Provider.Props {
function shouldRenderForActiveThread(
data: ThreadToastData | undefined,
activeThreadId: string | null,
activeThreadId: ThreadId | null,
): boolean {
const toastThreadId = data?.threadId;
if (!toastThreadId) return true;
return toastThreadId === activeThreadId;
}
function useActiveThreadIdFromRoute(): string | null {
function useActiveThreadIdFromRoute(): ThreadId | null {
return useParams({
strict: false,
select: (params) => params.threadId ?? null,
select: (params) =>
typeof params.threadId === "string" ? ThreadId.makeUnsafe(params.threadId) : null,
});
}
+5 -2
View File
@@ -1,6 +1,8 @@
import { TurnId } from "@t3tools/contracts";
export interface DiffRouteSearch {
diff?: "1";
diffTurnId?: string;
diffTurnId?: TurnId;
diffFilePath?: string;
}
@@ -25,7 +27,8 @@ export function stripDiffSearchParams<T extends Record<string, unknown>>(
export function parseDiffRouteSearch(search: Record<string, unknown>): DiffRouteSearch {
const diff = isDiffOpenValue(search.diff) ? "1" : undefined;
const diffTurnId = diff ? normalizeSearchString(search.diffTurnId) : undefined;
const diffTurnIdRaw = diff ? normalizeSearchString(search.diffTurnId) : undefined;
const diffTurnId = diffTurnIdRaw ? TurnId.makeUnsafe(diffTurnIdRaw) : undefined;
const diffFilePath = diff && diffTurnId ? normalizeSearchString(search.diffFilePath) : undefined;
return {
+10 -7
View File
@@ -1,20 +1,23 @@
import { MessageId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { buildBootstrapInput } from "./historyBootstrap";
const messageId = (value: string) => MessageId.makeUnsafe(value);
describe("buildBootstrapInput", () => {
it("includes full transcript when under budget", () => {
const result = buildBootstrapInput(
[
{
id: "u-1",
id: messageId("u-1"),
role: "user",
text: "hello",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: "a-1",
id: messageId("a-1"),
role: "assistant",
text: "world",
createdAt: "2026-02-09T00:00:01.000Z",
@@ -38,21 +41,21 @@ describe("buildBootstrapInput", () => {
const result = buildBootstrapInput(
[
{
id: "u-1",
id: messageId("u-1"),
role: "user",
text: "first question with details",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: "a-1",
id: messageId("a-1"),
role: "assistant",
text: "first answer with details",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
{
id: "u-2",
id: messageId("u-2"),
role: "user",
text: "second question with details",
createdAt: "2026-02-09T00:00:02.000Z",
@@ -75,7 +78,7 @@ describe("buildBootstrapInput", () => {
const result = buildBootstrapInput(
[
{
id: "u-1",
id: messageId("u-1"),
role: "user",
text: "old context",
createdAt: "2026-02-09T00:00:00.000Z",
@@ -96,7 +99,7 @@ describe("buildBootstrapInput", () => {
const result = buildBootstrapInput(
[
{
id: "u-image",
id: messageId("u-image"),
role: "user",
text: "",
attachments: [
-6
View File
@@ -1,6 +0,0 @@
import { useMemo } from "react";
import { readNativeApi } from "../nativeApi";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
}
+36 -53
View File
@@ -1,5 +1,6 @@
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
import type { GitStackedAction } from "@t3tools/contracts";
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
import { ensureNativeApi } from "~/nativeApi";
const GIT_STATUS_STALE_TIME_MS = 5_000;
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
@@ -16,16 +17,15 @@ export function invalidateGitQueries(queryClient: QueryClient) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string | null) {
export function gitStatusQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.status(cwd),
queryFn: async () => {
if (!api || !cwd) {
throw new Error("Git status is unavailable.");
}
const api = ensureNativeApi();
if (!cwd) throw new Error("Git status is unavailable.");
return api.git.status({ cwd });
},
enabled: !!api && !!cwd,
enabled: cwd !== null,
staleTime: GIT_STATUS_STALE_TIME_MS,
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
@@ -33,16 +33,15 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
});
}
export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string | null) {
export function gitBranchesQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.branches(cwd),
queryFn: async () => {
if (!api || !cwd) {
throw new Error("Git branches are unavailable.");
}
const api = ensureNativeApi();
if (!cwd) throw new Error("Git branches are unavailable.");
return api.git.listBranches({ cwd });
},
enabled: !!api && !!cwd,
enabled: cwd !== null,
staleTime: GIT_BRANCHES_STALE_TIME_MS,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
@@ -50,15 +49,12 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
});
}
export function gitInitMutationOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
queryClient: QueryClient;
}) {
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async () => {
if (!input.api || !input.cwd) throw new Error("Git init is unavailable.");
return input.api.git.init({ cwd: input.cwd });
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git init is unavailable.");
return api.git.init({ cwd: input.cwd });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
@@ -67,14 +63,14 @@ export function gitInitMutationOptions(input: {
}
export function gitCheckoutMutationOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async (branch: string) => {
if (!input.api || !input.cwd) throw new Error("Git checkout is unavailable.");
return input.api.git.checkout({ cwd: input.cwd, branch });
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git checkout is unavailable.");
return api.git.checkout({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
@@ -83,15 +79,15 @@ export function gitCheckoutMutationOptions(input: {
}
export function gitCreateBranchAndCheckoutMutationOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async (branch: string) => {
if (!input.api || !input.cwd) throw new Error("Git branch creation is unavailable.");
await input.api.git.createBranch({ cwd: input.cwd, branch });
return input.api.git.checkout({ cwd: input.cwd, branch });
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
await api.git.createBranch({ cwd: input.cwd, branch });
return api.git.checkout({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
@@ -100,7 +96,6 @@ export function gitCreateBranchAndCheckoutMutationOptions(input: {
}
export function gitRunStackedActionMutationOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
queryClient: QueryClient;
}) {
@@ -112,10 +107,9 @@ export function gitRunStackedActionMutationOptions(input: {
action: GitStackedAction;
commitMessage?: string;
}) => {
if (!input.api || !input.cwd) {
throw new Error("Git action is unavailable.");
}
return input.api.git.runStackedAction({
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git action is unavailable.");
return api.git.runStackedAction({
cwd: input.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
@@ -127,15 +121,12 @@ export function gitRunStackedActionMutationOptions(input: {
});
}
export function gitPullMutationOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
queryClient: QueryClient;
}) {
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async () => {
if (!input.api || !input.cwd) throw new Error("Git pull is unavailable.");
return input.api.git.pull({ cwd: input.cwd });
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git pull is unavailable.");
return api.git.pull({ cwd: input.cwd });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
@@ -143,10 +134,7 @@ export function gitPullMutationOptions(input: {
});
}
export function gitCreateWorktreeMutationOptions(input: {
api: NativeApi | undefined;
queryClient: QueryClient;
}) {
export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({
cwd,
@@ -159,10 +147,9 @@ export function gitCreateWorktreeMutationOptions(input: {
newBranch: string;
path?: string | null;
}) => {
if (!input.api) {
throw new Error("Git worktree creation is unavailable.");
}
return input.api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree creation is unavailable.");
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
@@ -170,16 +157,12 @@ export function gitCreateWorktreeMutationOptions(input: {
});
}
export function gitRemoveWorktreeMutationOptions(input: {
api: NativeApi | undefined;
queryClient: QueryClient;
}) {
export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
if (!input.api) {
throw new Error("Git worktree removal is unavailable.");
}
return input.api.git.removeWorktree({ cwd, path, force });
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree removal is unavailable.");
return api.git.removeWorktree({ cwd, path, force });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
-1
View File
@@ -8,7 +8,6 @@ export const newThreadId = (): ThreadId => ThreadId.makeUnsafe(crypto.randomUUID
export const newMessageId = (): MessageId => MessageId.makeUnsafe(crypto.randomUUID());
export const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
export const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
+6 -5
View File
@@ -1,5 +1,6 @@
import type { NativeApi, ProjectSearchEntriesResult } from "@t3tools/contracts";
import type { ProjectSearchEntriesResult } from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
import { ensureNativeApi } from "~/nativeApi";
export const projectQueryKeys = {
all: ["projects"] as const,
@@ -15,7 +16,6 @@ const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = {
};
export function projectSearchEntriesQueryOptions(input: {
api: NativeApi | undefined;
cwd: string | null;
query: string;
enabled?: boolean;
@@ -26,16 +26,17 @@ export function projectSearchEntriesQueryOptions(input: {
return queryOptions({
queryKey: projectQueryKeys.searchEntries(input.cwd, input.query, limit),
queryFn: async () => {
if (!input.api || !input.cwd) {
const api = ensureNativeApi();
if (!input.cwd) {
throw new Error("Workspace entry search is unavailable.");
}
return input.api.projects.searchEntries({
return api.projects.searchEntries({
cwd: input.cwd,
query: input.query,
limit,
});
},
enabled: (input.enabled ?? true) && Boolean(input.api && input.cwd),
enabled: (input.enabled ?? true) && input.cwd !== null,
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
});
+55 -25
View File
@@ -1,12 +1,31 @@
import type { NativeApi } from "@t3tools/contracts";
import { ThreadId, type NativeApi } from "@t3tools/contracts";
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
import * as nativeApi from "../nativeApi";
const threadId = ThreadId.makeUnsafe("thread-id");
function mockNativeApi(input: {
getTurnDiff: ReturnType<typeof vi.fn>;
getFullThreadDiff: ReturnType<typeof vi.fn>;
}) {
vi.spyOn(nativeApi, "ensureNativeApi").mockReturnValue({
orchestration: {
getTurnDiff: input.getTurnDiff,
getFullThreadDiff: input.getFullThreadDiff,
},
} as unknown as NativeApi);
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("providerQueryKeys.checkpointDiff", () => {
it("includes cacheScope so reused turn counts do not collide", () => {
const baseInput = {
threadId: "thread-id",
threadId,
fromTurnCount: 1,
toTurnCount: 2,
} as const;
@@ -29,15 +48,10 @@ describe("checkpointDiffQueryOptions", () => {
it("forwards checkpoint range to the provider API", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const api = {
orchestration: {
getTurnDiff,
getFullThreadDiff,
},
} as unknown as NativeApi;
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions(api, {
threadId: "thread-id",
const options = checkpointDiffQueryOptions({
threadId,
fromTurnCount: 3,
toTurnCount: 4,
cacheScope: "turn:abc",
@@ -47,7 +61,7 @@ describe("checkpointDiffQueryOptions", () => {
await queryClient.fetchQuery(options);
expect(getTurnDiff).toHaveBeenCalledWith({
threadId: "thread-id",
threadId,
fromTurnCount: 3,
toTurnCount: 4,
});
@@ -57,15 +71,10 @@ describe("checkpointDiffQueryOptions", () => {
it("uses explicit full thread diff API when range starts from zero", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const api = {
orchestration: {
getTurnDiff,
getFullThreadDiff,
},
} as unknown as NativeApi;
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions(api, {
threadId: "thread-id",
const options = checkpointDiffQueryOptions({
threadId,
fromTurnCount: 0,
toTurnCount: 2,
cacheScope: "thread:all",
@@ -75,15 +84,36 @@ describe("checkpointDiffQueryOptions", () => {
await queryClient.fetchQuery(options);
expect(getFullThreadDiff).toHaveBeenCalledWith({
threadId: "thread-id",
threadId,
toTurnCount: 2,
});
expect(getTurnDiff).not.toHaveBeenCalled();
});
it("fails fast on invalid range and does not call provider RPC", async () => {
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
mockNativeApi({ getTurnDiff, getFullThreadDiff });
const options = checkpointDiffQueryOptions({
threadId,
fromTurnCount: 4,
toTurnCount: 3,
cacheScope: "turn:invalid",
});
const queryClient = new QueryClient();
await expect(queryClient.fetchQuery(options)).rejects.toThrow(
"Checkpoint diff is unavailable.",
);
expect(getTurnDiff).not.toHaveBeenCalled();
expect(getFullThreadDiff).not.toHaveBeenCalled();
});
it("retries checkpoint-not-ready errors longer than generic failures", () => {
const options = checkpointDiffQueryOptions(undefined, {
threadId: "thread-id",
const options = checkpointDiffQueryOptions({
threadId,
fromTurnCount: 1,
toTurnCount: 2,
cacheScope: "turn:abc",
@@ -106,8 +136,8 @@ describe("checkpointDiffQueryOptions", () => {
});
it("backs off longer for checkpoint-not-ready errors", () => {
const options = checkpointDiffQueryOptions(undefined, {
threadId: "thread-id",
const options = checkpointDiffQueryOptions({
threadId,
fromTurnCount: 1,
toTurnCount: 2,
cacheScope: "turn:abc",
+32 -32
View File
@@ -1,9 +1,14 @@
import type { NativeApi } from "@t3tools/contracts";
import {
OrchestrationGetFullThreadDiffInput,
OrchestrationGetTurnDiffInput,
ThreadId,
} from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
import { asThreadId } from "./orchestrationIds";
import { Option, Schema } from "effect";
import { ensureNativeApi } from "../nativeApi";
export interface CheckpointDiffQueryInput {
threadId: string | null;
interface CheckpointDiffQueryInput {
threadId: ThreadId | null;
fromTurnCount: number | null;
toTurnCount: number | null;
cacheScope?: string | null;
@@ -22,6 +27,21 @@ export const providerQueryKeys = {
] as const,
};
function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
if (input.fromTurnCount === 0) {
return Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput)({
threadId: input.threadId,
toTurnCount: input.toTurnCount,
}).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
}
return Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput)({
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
}).pipe(Option.map((fields) => ({ kind: "turnDiff" as const, input: fields })));
}
function asCheckpointErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
@@ -41,42 +61,22 @@ function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
);
}
export function checkpointDiffQueryOptions(
api: NativeApi | undefined,
input: CheckpointDiffQueryInput,
) {
const hasValidRange =
typeof input.fromTurnCount === "number" &&
typeof input.toTurnCount === "number" &&
Number.isInteger(input.fromTurnCount) &&
Number.isInteger(input.toTurnCount) &&
input.fromTurnCount >= 0 &&
input.toTurnCount >= 0 &&
input.fromTurnCount <= input.toTurnCount;
export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
const decodedRequest = decodeCheckpointDiffRequest(input);
return queryOptions({
queryKey: providerQueryKeys.checkpointDiff(input),
queryFn: async () => {
if (!api || !input.threadId || !hasValidRange) {
const api = ensureNativeApi();
if (!input.threadId || decodedRequest._tag === "None") {
throw new Error("Checkpoint diff is unavailable.");
}
const { fromTurnCount, toTurnCount } = input;
if (typeof fromTurnCount !== "number" || typeof toTurnCount !== "number") {
throw new Error("Checkpoint diff range is invalid.");
if (decodedRequest.value.kind === "fullThreadDiff") {
return api.orchestration.getFullThreadDiff(decodedRequest.value.input);
}
if (fromTurnCount === 0) {
return api.orchestration.getFullThreadDiff({
threadId: asThreadId(input.threadId),
toTurnCount,
});
}
return api.orchestration.getTurnDiff({
threadId: asThreadId(input.threadId),
fromTurnCount,
toTurnCount,
});
return api.orchestration.getTurnDiff(decodedRequest.value.input);
},
enabled: !!api && !!input.threadId && hasValidRange,
enabled: !!input.threadId && decodedRequest._tag === "Some",
staleTime: Infinity,
retry: (failureCount, error) => {
if (isCheckpointTemporarilyUnavailable(error)) {
+3 -6
View File
@@ -1,21 +1,18 @@
import type { NativeApi } from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
import { ensureNativeApi } from "~/nativeApi";
export const serverQueryKeys = {
all: ["server"] as const,
config: () => ["server", "config"] as const,
};
export function serverConfigQueryOptions(api: NativeApi | undefined) {
export function serverConfigQueryOptions() {
return queryOptions({
queryKey: serverQueryKeys.config(),
queryFn: async () => {
if (!api || !api.server || typeof api.server.getConfig !== "function") {
throw new Error("Server config is unavailable.");
}
const api = ensureNativeApi();
return api.server.getConfig();
},
enabled: !!api && !!api.server && typeof api.server.getConfig === "function",
staleTime: Infinity,
});
}
-33
View File
@@ -1,33 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL, normalizeModelSlug, resolveModelSlug } from "./model-logic";
describe("normalizeModelSlug", () => {
it("maps 5.3 aliases to canonical codex slug", () => {
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("preserves non-aliased slugs", () => {
expect(normalizeModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
});
it("returns null for empty input", () => {
expect(normalizeModelSlug("")).toBeNull();
expect(normalizeModelSlug(" ")).toBeNull();
expect(normalizeModelSlug(null)).toBeNull();
expect(normalizeModelSlug(undefined)).toBeNull();
});
});
describe("resolveModelSlug", () => {
it("falls back to default for unknown models", () => {
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
});
it("resolves supported hard-coded models", () => {
expect(resolveModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(resolveModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(resolveModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
-10
View File
@@ -1,10 +0,0 @@
export {
DEFAULT_MODEL,
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export type ReasoningEffort = (typeof REASONING_OPTIONS)[number];
export const DEFAULT_REASONING: ReasoningEffort = "high";
+8
View File
@@ -16,3 +16,11 @@ export function readNativeApi(): NativeApi | undefined {
cachedApi = createWsNativeApi();
return cachedApi;
}
export function ensureNativeApi(): NativeApi {
const api = readNativeApi();
if (!api) {
throw new Error("Native API not found");
}
return api;
}
+4 -6
View File
@@ -9,7 +9,7 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { useNativeApi } from "../hooks/useNativeApi";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
import { providerQueryKeys } from "../lib/providerReactQuery";
@@ -22,9 +22,7 @@ export const Route = createRootRouteWithContext<{
});
function RootRouteView() {
const api = useNativeApi();
if (!api) {
if (!readNativeApi()) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
@@ -119,11 +117,11 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
useEffect(() => {
const api = readNativeApi();
if (!api) return;
let disposed = false;
let latestSequence = 0;
@@ -177,7 +175,7 @@ function EventRouter() {
unsubDomainEvent();
unsubWelcome();
};
}, [api, dispatch, queryClient]);
}, [dispatch, queryClient]);
return null;
}
+6 -8
View File
@@ -1,3 +1,4 @@
import { ThreadId } from "@t3tools/contracts";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
@@ -133,9 +134,11 @@ const DiffPanelInlineSidebar = (props: {
function ChatThreadRouteView() {
const { state } = useStore();
const navigate = useNavigate();
const { threadId } = Route.useParams();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
});
const search = Route.useSearch();
const threadExists = threadId ? state.threads.some((thread) => thread.id === threadId) : false;
const threadExists = state.threads.some((thread) => thread.id === threadId);
const diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => {
@@ -159,11 +162,6 @@ function ChatThreadRouteView() {
}, [navigate, threadId]);
useEffect(() => {
if (!threadId) {
void navigate({ to: "/", replace: true });
return;
}
if (!state.threadsHydrated) {
return;
}
@@ -174,7 +172,7 @@ function ChatThreadRouteView() {
}
}, [navigate, state.threadsHydrated, threadExists, threadId]);
if (!threadId || !state.threadsHydrated || !threadExists) {
if (!state.threadsHydrated || !threadExists) {
return null;
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { useEffect } from "react";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import ThreadSidebar from "../components/Sidebar";
import { SidebarInset, Sidebar, SidebarProvider } from "~/components/ui/sidebar";
import { Sidebar, SidebarProvider } from "~/components/ui/sidebar";
function ChatRouteLayout() {
const navigate = useNavigate();
+2 -34
View File
@@ -1,11 +1,7 @@
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
derivePendingApprovals,
deriveTurnDiffFilesFromUnifiedDiff,
deriveWorkLogEntries,
} from "./session-logic";
import { derivePendingApprovals, deriveWorkLogEntries } from "./session-logic";
function makeActivity(overrides: {
id?: string;
@@ -105,7 +101,7 @@ describe("deriveWorkLogEntries", () => {
makeActivity({ id: "no-turn", summary: "Checkpoint captured", tone: "info" }),
];
const entries = deriveWorkLogEntries(activities, "turn-2");
const entries = deriveWorkLogEntries(activities, TurnId.makeUnsafe("turn-2"));
expect(entries.map((entry) => entry.id)).toEqual(["turn-2"]);
});
@@ -130,31 +126,3 @@ describe("deriveWorkLogEntries", () => {
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
});
});
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
it("extracts per-file +/- counts from unified diff", () => {
const diff = [
"diff --git a/a.txt b/a.txt",
"index 111..222 100644",
"--- a/a.txt",
"+++ b/a.txt",
"@@ -1 +1,2 @@",
"-old",
"+new",
"+extra",
"diff --git a/b.txt b/b.txt",
"index 333..444 100644",
"--- a/b.txt",
"+++ b/b.txt",
"@@ -2,2 +2 @@",
"-x",
"-y",
"+z",
].join("\n");
expect(deriveTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
{ path: "a.txt", additions: 2, deletions: 1 },
{ path: "b.txt", additions: 1, deletions: 2 },
]);
});
});
+16 -64
View File
@@ -1,12 +1,11 @@
import type { OrchestrationThreadActivity, ProviderKind } from "@t3tools/contracts";
import {
ApprovalRequestId,
type OrchestrationThreadActivity,
type ProviderKind,
type TurnId,
} from "@t3tools/contracts";
import type {
ChatMessage,
SessionPhase,
ThreadSession,
TurnDiffFileChange,
TurnDiffSummary,
} from "./types";
import type { ChatMessage, SessionPhase, ThreadSession, TurnDiffSummary } from "./types";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -26,7 +25,7 @@ export interface WorkLogEntry {
}
export interface PendingApproval {
requestId: string;
requestId: ApprovalRequestId;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
@@ -79,7 +78,7 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
const openByRequestId = new Map<string, PendingApproval>();
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
const ordered = [...activities].toSorted((left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
@@ -89,7 +88,10 @@ export function derivePendingApprovals(
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const requestId = payload && typeof payload.requestId === "string" ? payload.requestId : null;
const requestId =
payload && typeof payload.requestId === "string"
? ApprovalRequestId.makeUnsafe(payload.requestId)
: null;
const requestKind =
payload && (payload.requestKind === "command" || payload.requestKind === "file-change")
? payload.requestKind
@@ -118,7 +120,7 @@ export function derivePendingApprovals(
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
latestTurnId: string | undefined,
latestTurnId: TurnId | undefined,
): WorkLogEntry[] {
const ordered = [...activities].toSorted((left, right) =>
left.createdAt.localeCompare(right.createdAt),
@@ -163,55 +165,11 @@ export function deriveTimelineEntries(
return [...messageRows, ...workRows].toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
}
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const normalized = diff.replace(/\r\n/g, "\n");
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
if (headerMatches.length === 0) {
return [];
}
const files: TurnDiffFileChange[] = [];
for (let index = 0; index < headerMatches.length; index += 1) {
const header = headerMatches[index];
if (!header) continue;
const start = header.index ?? 0;
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
const segment = normalized.slice(start, nextStart);
const headerLine = header[0];
if (!headerLine) continue;
const match = headerLine.match(/^diff --git a\/(.+?) b\/(.+)$/);
const filePath = match?.[2] ?? match?.[1];
if (!filePath) continue;
let additions = 0;
let deletions = 0;
for (const line of segment.split("\n")) {
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
if (line.startsWith("+")) {
additions += 1;
continue;
}
if (line.startsWith("-")) {
deletions += 1;
}
}
files.push({
path: filePath,
additions,
deletions,
});
}
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
): Record<TurnId, number> {
const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt));
const result: Record<string, number> = {};
const result: Record<TurnId, number> = {};
for (let index = 0; index < sorted.length; index += 1) {
const summary = sorted[index];
if (!summary) continue;
@@ -220,12 +178,6 @@ export function inferCheckpointTurnCountByTurnId(
return result;
}
export function deriveTurnDiffSummaries(
_events: ReadonlyArray<OrchestrationThreadActivity>,
): TurnDiffSummary[] {
return [];
}
export function derivePhase(session: ThreadSession | null): SessionPhase {
if (!session || session.status === "closed") return "disconnected";
if (session.status === "connecting") return "connecting";
+23 -16
View File
@@ -8,15 +8,20 @@ import {
useReducer,
} from "react";
import { type OrchestrationReadModel, type OrchestrationSessionStatus } from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_MODEL,
ProviderSessionId,
ThreadId,
type OrchestrationReadModel,
type OrchestrationSessionStatus,
resolveModelSlug,
} from "@t3tools/contracts";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type ProjectScript,
type Project,
type RuntimeMode,
type Thread,
@@ -27,19 +32,19 @@ import {
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { type: "MARK_THREAD_VISITED"; threadId: string; visitedAt?: string }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
| {
type: "SET_THREAD_BRANCH";
threadId: string;
threadId: ThreadId;
branch: string | null;
worktreePath: string | null;
}
@@ -127,7 +132,7 @@ function persistState(state: AppState): void {
function updateThread(
threads: Thread[],
threadId: string,
threadId: ThreadId,
updater: (t: Thread) => Thread,
): Thread[] {
return threads.map((t) => (t.id === threadId ? updater(t) : t));
@@ -415,7 +420,9 @@ export function reducer(state: AppState, action: Action): AppState {
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: thread.session
? {
sessionId: thread.session.providerSessionId ?? `thread:${thread.id}`,
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
-42
View File
@@ -1,42 +0,0 @@
import { DEFAULT_MODEL } from "./model-logic";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
interface CreateThreadOptions {
branch?: string | null;
createdAt?: string;
model?: string;
title?: string;
worktreePath?: string | null;
}
export function createThread(projectId: string, options: CreateThreadOptions = {}): Thread {
const createdAt = options.createdAt ?? new Date().toISOString();
return {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: options.title ?? "New thread",
model: options.model ?? DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],
activities: [],
error: null,
createdAt,
branch: options.branch ?? null,
worktreePath: options.worktreePath ?? null,
};
}
+21 -13
View File
@@ -2,6 +2,14 @@ import type {
OrchestrationSessionStatus,
OrchestrationThreadActivity,
ProjectScript as ContractProjectScript,
ThreadId,
ProjectId,
TurnId,
MessageId,
CheckpointRef,
ProviderThreadId,
ProviderSessionId,
ProviderKind,
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
@@ -29,7 +37,7 @@ export interface ChatImageAttachment {
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage {
id: string;
id: MessageId;
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
@@ -46,17 +54,17 @@ export interface TurnDiffFileChange {
}
export interface TurnDiffSummary {
turnId: string;
turnId: TurnId;
completedAt: string;
status?: string | undefined;
files: TurnDiffFileChange[];
checkpointRef?: string | undefined;
assistantMessageId?: string | undefined;
checkpointRef?: CheckpointRef | undefined;
assistantMessageId?: MessageId | undefined;
checkpointTurnCount?: number | undefined;
}
export interface Project {
id: string;
id: ProjectId;
name: string;
cwd: string;
model: string;
@@ -65,9 +73,9 @@ export interface Project {
}
export interface Thread {
id: string;
codexThreadId: string | null;
projectId: string;
id: ThreadId;
codexThreadId: ProviderThreadId | null;
projectId: ProjectId;
title: string;
model: string;
terminalOpen: boolean;
@@ -81,7 +89,7 @@ export interface Thread {
messages: ChatMessage[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
latestTurnId?: TurnId | undefined;
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
@@ -93,11 +101,11 @@ export interface Thread {
}
export interface ThreadSession {
sessionId: string;
provider: "codex" | "claudeCode";
sessionId: ProviderSessionId;
provider: ProviderKind;
status: SessionPhase | "error" | "closed";
threadId: string | null;
activeTurnId?: string | undefined;
threadId: ProviderThreadId | null;
activeTurnId?: TurnId | undefined;
createdAt: string;
updatedAt: string;
lastError?: string;
+24 -11
View File
@@ -1,3 +1,4 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
@@ -5,9 +6,9 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-1",
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: "project-1",
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
@@ -36,37 +37,49 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
describe("getOrphanedWorktreePathForThread", () => {
it("returns null when the target thread does not exist", () => {
const result = getOrphanedWorktreePathForThread([], "missing-thread");
const result = getOrphanedWorktreePathForThread([], ThreadId.makeUnsafe("missing-thread"));
expect(result).toBeNull();
});
it("returns null when the target thread has no worktree", () => {
const threads = [makeThread()];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
const result = getOrphanedWorktreePathForThread(threads, ThreadId.makeUnsafe("thread-1"));
expect(result).toBeNull();
});
it("returns the path when no other thread links to that worktree", () => {
const threads = [makeThread({ worktreePath: "/tmp/repo/worktrees/feature-a" })];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
const result = getOrphanedWorktreePathForThread(threads, ThreadId.makeUnsafe("thread-1"));
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
it("returns null when another thread links to the same worktree", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
worktreePath: "/tmp/repo/worktrees/feature-a",
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
worktreePath: "/tmp/repo/worktrees/feature-a",
}),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
const result = getOrphanedWorktreePathForThread(threads, ThreadId.makeUnsafe("thread-1"));
expect(result).toBeNull();
});
it("ignores threads linked to different worktrees", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-b" }),
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
worktreePath: "/tmp/repo/worktrees/feature-a",
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
worktreePath: "/tmp/repo/worktrees/feature-b",
}),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
const result = getOrphanedWorktreePathForThread(threads, ThreadId.makeUnsafe("thread-1"));
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
});
+1 -1
View File
@@ -10,7 +10,7 @@ function normalizeWorktreePath(path: string | null): string | null {
export function getOrphanedWorktreePathForThread(
threads: readonly Thread[],
threadId: string,
threadId: Thread["id"],
): string | null {
const targetThread = threads.find((thread) => thread.id === threadId);
if (!targetThread) {
+1 -6
View File
@@ -13,12 +13,7 @@ const REQUEST_TIMEOUT_MS = 60_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
const decodeWsResponseFromJson = Schema.decodeUnknownExit(Schema.fromJsonString(WsResponse));
const isWsPushEnvelope = Schema.is(WsPush);
function isWebSocketResponseEnvelope(
message: typeof WsResponse.Type,
): message is WebSocketResponse {
return message instanceof WebSocketResponse;
}
const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
interface WsRequestEnvelope {
id: string;
+3 -2
View File
@@ -8,7 +8,8 @@ export const EDITORS = [
export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
export type EditorId = typeof EditorId.Type;
export class OpenInEditorInput extends Schema.Class<OpenInEditorInput>("OpenInEditorInput")({
export const OpenInEditorInput = Schema.Struct({
cwd: Schema.String,
editor: EditorId,
}) {}
});
export type OpenInEditorInput = typeof OpenInEditorInput.Type;
+48 -48
View File
@@ -18,78 +18,79 @@ export const GitPrStepStatus = Schema.Literals([
"skipped_not_requested",
]);
export class GitBranch extends Schema.Class<GitBranch>("GitBranch")({
export const GitBranch = Schema.Struct({
name: TrimmedNonEmptyString,
current: Schema.Boolean,
isDefault: Schema.Boolean,
worktreePath: TrimmedNonEmptyString.pipe(Schema.NullOr),
}) {}
});
export type GitBranch = typeof GitBranch.Type;
export class GitWorktree extends Schema.Class<GitWorktree>("GitWorktree")({
export const GitWorktree = Schema.Struct({
path: TrimmedNonEmptyString,
branch: TrimmedNonEmptyString,
}) {}
});
export type GitWorktree = typeof GitWorktree.Type;
// RPC Inputs
export class GitStatusInput extends Schema.Class<GitStatusInput>("GitStatusInput")({
export const GitStatusInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
}) {}
});
export type GitStatusInput = typeof GitStatusInput.Type;
export class GitPullInput extends Schema.Class<GitPullInput>("GitPullInput")({
export const GitPullInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
}) {}
});
export type GitPullInput = typeof GitPullInput.Type;
export class GitRunStackedActionInput extends Schema.Class<GitRunStackedActionInput>(
"GitRunStackedActionInput",
)({
export const GitRunStackedActionInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
action: GitStackedAction,
commitMessage: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(10_000))),
}) {}
});
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
export class GitListBranchesInput extends Schema.Class<GitListBranchesInput>(
"GitListBranchesInput",
)({
export const GitListBranchesInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
}) {}
});
export type GitListBranchesInput = typeof GitListBranchesInput.Type;
export class GitCreateWorktreeInput extends Schema.Class<GitCreateWorktreeInput>(
"GitCreateWorktreeInput",
)({
export const GitCreateWorktreeInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
branch: TrimmedNonEmptyString,
newBranch: TrimmedNonEmptyString,
path: TrimmedNonEmptyString.pipe(Schema.NullOr),
}) {}
});
export type GitCreateWorktreeInput = typeof GitCreateWorktreeInput.Type;
export class GitRemoveWorktreeInput extends Schema.Class<GitRemoveWorktreeInput>(
"GitRemoveWorktreeInput",
)({
export const GitRemoveWorktreeInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
path: TrimmedNonEmptyString,
force: Schema.optional(Schema.Boolean),
}) {}
});
export type GitRemoveWorktreeInput = typeof GitRemoveWorktreeInput.Type;
export class GitCreateBranchInput extends Schema.Class<GitCreateBranchInput>(
"GitCreateBranchInput",
)({
export const GitCreateBranchInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
branch: TrimmedNonEmptyString,
}) {}
});
export type GitCreateBranchInput = typeof GitCreateBranchInput.Type;
export class GitCheckoutInput extends Schema.Class<GitCheckoutInput>("GitCheckoutInput")({
export const GitCheckoutInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
branch: TrimmedNonEmptyString,
}) {}
});
export type GitCheckoutInput = typeof GitCheckoutInput.Type;
export class GitInitInput extends Schema.Class<GitInitInput>("GitInitInput")({
export const GitInitInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
}) {}
});
export type GitInitInput = typeof GitInitInput.Type;
// RPC Results
export class GitStatusResult extends Schema.Class<GitStatusResult>("GitStatusResult")({
export const GitStatusResult = Schema.Struct({
branch: TrimmedNonEmptyString.pipe(Schema.NullOr),
hasWorkingTreeChanges: Schema.Boolean,
workingTree: Schema.Struct({
@@ -113,24 +114,21 @@ export class GitStatusResult extends Schema.Class<GitStatusResult>("GitStatusRes
baseBranch: TrimmedNonEmptyString,
headBranch: TrimmedNonEmptyString,
}).pipe(Schema.NullOr),
}) {}
});
export type GitStatusResult = typeof GitStatusResult.Type;
export class GitListBranchesResult extends Schema.Class<GitListBranchesResult>(
"GitListBranchesResult",
)({
export const GitListBranchesResult = Schema.Struct({
branches: Schema.Array(GitBranch),
isRepo: Schema.Boolean,
}) {}
});
export type GitListBranchesResult = typeof GitListBranchesResult.Type;
export class GitCreateWorktreeResult extends Schema.Class<GitCreateWorktreeResult>(
"GitCreateWorktreeResult",
)({
export const GitCreateWorktreeResult = Schema.Struct({
worktree: GitWorktree,
}) {}
});
export type GitCreateWorktreeResult = typeof GitCreateWorktreeResult.Type;
export class GitRunStackedActionResult extends Schema.Class<GitRunStackedActionResult>(
"GitRunStackedActionResult",
)({
export const GitRunStackedActionResult = Schema.Struct({
action: GitStackedAction,
commit: Schema.Struct({
status: GitCommitStepStatus,
@@ -151,10 +149,12 @@ export class GitRunStackedActionResult extends Schema.Class<GitRunStackedActionR
headBranch: Schema.optional(TrimmedNonEmptyString),
title: Schema.optional(TrimmedNonEmptyString),
}),
}) {}
});
export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;
export class GitPullResult extends Schema.Class<GitPullResult>("GitPullResult")({
export const GitPullResult = Schema.Struct({
status: Schema.Literals(["pulled", "skipped_up_to_date"]),
branch: TrimmedNonEmptyString,
upstreamBranch: TrimmedNonEmptyString.pipe(Schema.NullOr),
}) {}
});
export type GitPullResult = typeof GitPullResult.Type;
+12 -14
View File
@@ -44,25 +44,27 @@ export const KeybindingWhen = Schema.Trim.check(
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
export type KeybindingWhen = typeof KeybindingWhen.Type;
export class KeybindingRule extends Schema.Class<KeybindingRule>("KeybindingRule")({
export const KeybindingRule = Schema.Struct({
key: KeybindingValue,
command: KeybindingCommand,
when: Schema.optional(KeybindingWhen),
}) {}
});
export type KeybindingRule = typeof KeybindingRule.Type;
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
export class KeybindingShortcut extends Schema.Class<KeybindingShortcut>("KeybindingShortcut")({
export const KeybindingShortcut = Schema.Struct({
key: KeybindingValue,
metaKey: Schema.Boolean,
ctrlKey: Schema.Boolean,
shiftKey: Schema.Boolean,
altKey: Schema.Boolean,
modKey: Schema.Boolean,
}) {}
});
export type KeybindingShortcut = typeof KeybindingShortcut.Type;
export const KeybindingWhenNode: Schema.Schema<KeybindingWhenNode> = Schema.Union([
Schema.Struct({
@@ -90,16 +92,12 @@ export type KeybindingWhenNode =
| { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }
| { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };
export class ResolvedKeybindingRule extends Schema.Class<ResolvedKeybindingRule>(
"ResolvedKeybindingRule",
)(
{
command: KeybindingCommand,
shortcut: KeybindingShortcut,
whenAst: Schema.optional(KeybindingWhenNode),
},
{ parseOptions: { onExcessProperty: "ignore" } },
) {}
export const ResolvedKeybindingRule = Schema.Struct({
command: KeybindingCommand,
shortcut: KeybindingShortcut,
whenAst: Schema.optional(KeybindingWhenNode),
}).annotate({ parseOptions: { onExcessProperty: "ignore" } });
export type ResolvedKeybindingRule = typeof ResolvedKeybindingRule.Type;
export const ResolvedKeybindingsConfig = Schema.Array(ResolvedKeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
+4
View File
@@ -37,3 +37,7 @@ export function resolveModelSlug(model: string | null | undefined): ModelSlug {
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
}
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export type ReasoningEffort = (typeof REASONING_OPTIONS)[number];
export const DEFAULT_REASONING: ReasoningEffort = "high";
@@ -0,0 +1,46 @@
import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { OrchestrationGetTurnDiffInput, ThreadTurnDiff } from "./orchestration";
const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);
const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);
it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
Effect.gen(function* () {
const parsed = yield* decodeTurnDiffInput({
threadId: "thread-1",
fromTurnCount: 1,
toTurnCount: 2,
});
assert.strictEqual(parsed.fromTurnCount, 1);
assert.strictEqual(parsed.toTurnCount, 2);
}),
);
it.effect("rejects turn diff input when fromTurnCount > toTurnCount", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeTurnDiffInput({
threadId: "thread-1",
fromTurnCount: 3,
toTurnCount: 2,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
it.effect("rejects thread turn diff when fromTurnCount > toTurnCount", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeThreadTurnDiff({
threadId: "thread-1",
fromTurnCount: 3,
toTurnCount: 2,
diff: "patch",
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+22 -11
View File
@@ -1,4 +1,4 @@
import { Schema } from "effect";
import { Option, Schema, SchemaIssue, Struct } from "effect";
export const ORCHESTRATION_WS_METHODS = {
getSnapshot: "orchestration.getSnapshot",
@@ -777,13 +777,24 @@ export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandRecei
export const TurnCountRange = Schema.Struct({
fromTurnCount: NonNegativeInt,
toTurnCount: NonNegativeInt,
});
}).check(
Schema.makeFilter(
(input) =>
input.fromTurnCount <= input.toTurnCount ||
new SchemaIssue.InvalidValue(Option.some(input.fromTurnCount), {
message: "fromTurnCount must be less than or equal to toTurnCount",
}),
{ identifier: "OrchestrationTurnDiffRange" },
),
);
export const ThreadTurnDiff = Schema.Struct({
threadId: ThreadId,
...TurnCountRange.fields,
diff: Schema.String,
});
export const ThreadTurnDiff = TurnCountRange.mapFields(
Struct.assign({
threadId: ThreadId,
diff: Schema.String,
}),
{ unsafePreserveChecks: true },
);
export const ProviderSessionRuntimeStatus = Schema.Literals([
"starting",
@@ -829,10 +840,10 @@ export type OrchestrationGetSnapshotInput = typeof OrchestrationGetSnapshotInput
export const OrchestrationGetSnapshotResult = OrchestrationReadModel;
export type OrchestrationGetSnapshotResult = typeof OrchestrationGetSnapshotResult.Type;
export const OrchestrationGetTurnDiffInput = Schema.Struct({
threadId: ThreadId,
...TurnCountRange.fields,
});
export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
Struct.assign({ threadId: ThreadId }),
{ unsafePreserveChecks: true },
);
export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;
export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
+9 -10
View File
@@ -3,28 +3,27 @@ import { Schema } from "effect";
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
const TrimmedNonEmptyString = Schema.Trimmed.check(Schema.isNonEmpty());
export class ProjectSearchEntriesInput extends Schema.Class<ProjectSearchEntriesInput>(
"ProjectSearchEntriesInput",
)({
export const ProjectSearchEntriesInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
query: Schema.NonEmptyString.check(Schema.isMaxLength(256)),
limit: Schema.Int.check(
Schema.isGreaterThanOrEqualTo(1),
Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT),
),
}) {}
});
export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;
export const ProjectEntryKind = Schema.Literals(["file", "directory"]);
export class ProjectEntry extends Schema.Class<ProjectEntry>("ProjectEntry")({
export const ProjectEntry = Schema.Struct({
path: TrimmedNonEmptyString,
kind: ProjectEntryKind,
parentPath: Schema.optional(TrimmedNonEmptyString),
}) {}
});
export type ProjectEntry = typeof ProjectEntry.Type;
export class ProjectSearchEntriesResult extends Schema.Class<ProjectSearchEntriesResult>(
"ProjectSearchEntriesResult",
)({
export const ProjectSearchEntriesResult = Schema.Struct({
entries: Schema.Array(ProjectEntry),
truncated: Schema.Boolean,
}) {}
});
export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;
+39
View File
@@ -0,0 +1,39 @@
import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { ORCHESTRATION_WS_METHODS } from "./orchestration";
import { WebSocketRequest } from "./ws";
const decodeWebSocketRequest = Schema.decodeUnknownEffect(WebSocketRequest);
it.effect("accepts getTurnDiff requests when fromTurnCount <= toTurnCount", () =>
Effect.gen(function* () {
const parsed = yield* decodeWebSocketRequest({
id: "req-1",
body: {
_tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
threadId: "thread-1",
fromTurnCount: 1,
toTurnCount: 2,
},
});
assert.strictEqual(parsed.body._tag, ORCHESTRATION_WS_METHODS.getTurnDiff);
}),
);
it.effect("rejects getTurnDiff requests when fromTurnCount > toTurnCount", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeWebSocketRequest({
id: "req-1",
body: {
_tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
threadId: "thread-1",
fromTurnCount: 3,
toTurnCount: 2,
},
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+49 -33
View File
@@ -1,4 +1,4 @@
import { Schema } from "effect";
import { Schema, Struct } from "effect";
import {
ClientOrchestrationCommand,
@@ -76,43 +76,56 @@ export const WS_CHANNELS = {
// -- Tagged Union of all request body schemas ─────────────────────────
export const WebSocketRequestBody = Schema.TaggedUnion({
const tagRequestBody = <const Tag extends string, const Fields extends Schema.Struct.Fields>(
tag: Tag,
schema: Schema.Struct<Fields>,
) =>
schema.mapFields(
Struct.assign({ _tag: Schema.tag(tag) }),
// PreserveChecks is safe here. No existing schema should have checks depending on the tag
{ unsafePreserveChecks: true },
);
export const WebSocketRequestBody = Schema.Union([
// Orchestration methods
[ORCHESTRATION_WS_METHODS.dispatchCommand]: { command: ClientOrchestrationCommand },
[ORCHESTRATION_WS_METHODS.getSnapshot]: OrchestrationGetSnapshotInput.fields,
[ORCHESTRATION_WS_METHODS.getTurnDiff]: OrchestrationGetTurnDiffInput.fields,
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: OrchestrationGetFullThreadDiffInput.fields,
[ORCHESTRATION_WS_METHODS.replayEvents]: OrchestrationReplayEventsInput.fields,
tagRequestBody(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Schema.Struct({ command: ClientOrchestrationCommand }),
),
tagRequestBody(ORCHESTRATION_WS_METHODS.getSnapshot, OrchestrationGetSnapshotInput),
tagRequestBody(ORCHESTRATION_WS_METHODS.getTurnDiff, OrchestrationGetTurnDiffInput),
tagRequestBody(ORCHESTRATION_WS_METHODS.getFullThreadDiff, OrchestrationGetFullThreadDiffInput),
tagRequestBody(ORCHESTRATION_WS_METHODS.replayEvents, OrchestrationReplayEventsInput),
// Project Search
[WS_METHODS.projectsSearchEntries]: ProjectSearchEntriesInput.fields,
tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput),
// Shell methods
[WS_METHODS.shellOpenInEditor]: OpenInEditorInput.fields,
tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput),
// Git methods
[WS_METHODS.gitPull]: GitPullInput.fields,
[WS_METHODS.gitStatus]: GitStatusInput.fields,
[WS_METHODS.gitRunStackedAction]: GitRunStackedActionInput.fields,
[WS_METHODS.gitListBranches]: GitListBranchesInput.fields,
[WS_METHODS.gitCreateWorktree]: GitCreateWorktreeInput.fields,
[WS_METHODS.gitRemoveWorktree]: GitRemoveWorktreeInput.fields,
[WS_METHODS.gitCreateBranch]: GitCreateBranchInput.fields,
[WS_METHODS.gitCheckout]: GitCheckoutInput.fields,
[WS_METHODS.gitInit]: GitInitInput.fields,
tagRequestBody(WS_METHODS.gitPull, GitPullInput),
tagRequestBody(WS_METHODS.gitStatus, GitStatusInput),
tagRequestBody(WS_METHODS.gitRunStackedAction, GitRunStackedActionInput),
tagRequestBody(WS_METHODS.gitListBranches, GitListBranchesInput),
tagRequestBody(WS_METHODS.gitCreateWorktree, GitCreateWorktreeInput),
tagRequestBody(WS_METHODS.gitRemoveWorktree, GitRemoveWorktreeInput),
tagRequestBody(WS_METHODS.gitCreateBranch, GitCreateBranchInput),
tagRequestBody(WS_METHODS.gitCheckout, GitCheckoutInput),
tagRequestBody(WS_METHODS.gitInit, GitInitInput),
// Terminal methods
[WS_METHODS.terminalOpen]: TerminalOpenInput.fields,
[WS_METHODS.terminalWrite]: TerminalWriteInput.fields,
[WS_METHODS.terminalResize]: TerminalResizeInput.fields,
[WS_METHODS.terminalClear]: TerminalClearInput.fields,
[WS_METHODS.terminalRestart]: TerminalRestartInput.fields,
[WS_METHODS.terminalClose]: TerminalCloseInput.fields,
tagRequestBody(WS_METHODS.terminalOpen, TerminalOpenInput),
tagRequestBody(WS_METHODS.terminalWrite, TerminalWriteInput),
tagRequestBody(WS_METHODS.terminalResize, TerminalResizeInput),
tagRequestBody(WS_METHODS.terminalClear, TerminalClearInput),
tagRequestBody(WS_METHODS.terminalRestart, TerminalRestartInput),
tagRequestBody(WS_METHODS.terminalClose, TerminalCloseInput),
// Server meta
[WS_METHODS.serverGetConfig]: {},
[WS_METHODS.serverUpsertKeybinding]: KeybindingRule.fields,
});
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
]);
export const WebSocketRequest = Schema.Struct({
id: Schema.String,
@@ -120,7 +133,7 @@ export const WebSocketRequest = Schema.Struct({
});
export type WebSocketRequest = typeof WebSocketRequest.Type;
export class WebSocketResponse extends Schema.Class<WebSocketResponse>("WebSocketResponse")({
export const WebSocketResponse = Schema.Struct({
id: Schema.String,
result: Schema.optional(Schema.Unknown),
error: Schema.optional(
@@ -128,13 +141,15 @@ export class WebSocketResponse extends Schema.Class<WebSocketResponse>("WebSocke
message: Schema.String,
}),
),
}) {}
});
export type WebSocketResponse = typeof WebSocketResponse.Type;
export class WsPush extends Schema.Class<WsPush>("WsPushEvent")({
export const WsPush = Schema.Struct({
type: Schema.Literal("push"),
channel: Schema.String,
data: Schema.Unknown,
}) {}
});
export type WsPush = typeof WsPush.Type;
// ── Union of all server → client messages ─────────────────────────────
@@ -143,7 +158,8 @@ export type WsResponse = typeof WsResponse.Type;
// ── Server welcome payload ───────────────────────────────────────────
export class WsWelcomePayload extends Schema.Class<WsWelcomePayload>("WsWelcomePayload")({
export const WsWelcomePayload = Schema.Struct({
cwd: Schema.String,
projectName: Schema.String,
}) {}
});
export type WsWelcomePayload = typeof WsWelcomePayload.Type;