Compare commits
106
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a30a50807 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
d48b42c017 | ||
|
|
fb45896588 | ||
|
|
b52518f85f | ||
|
|
3e99019af8 | ||
|
|
7d4b02689e | ||
|
|
9962f57ad0 | ||
|
|
8b538e2802 | ||
|
|
a6c57e169a | ||
|
|
6f92f0a668 | ||
|
|
35817601ff | ||
|
|
2b154db938 | ||
|
|
b9ff7aa5cd | ||
|
|
b5188e8cea | ||
|
|
992db16586 | ||
|
|
2aad749e24 | ||
|
|
aa267ebb05 | ||
|
|
1a33f25970 | ||
|
|
e8dfc42f44 | ||
|
|
21c823ecdc | ||
|
|
80498f1709 | ||
|
|
e6c5a4a4bb | ||
|
|
732b3abf99 | ||
|
|
ffbf541ff8 | ||
|
|
709f961e1c | ||
|
|
1653383573 | ||
|
|
c7ae6b9471 | ||
|
|
bbcf9ba9db | ||
|
|
3f81f9dcb4 | ||
|
|
b073fea5fb | ||
|
|
834236931e | ||
|
|
872b907372 | ||
|
|
0b8e098c10 | ||
|
|
7c6a0f869d | ||
|
|
3a43047102 | ||
|
|
041acf158a | ||
|
|
f9752d7c08 | ||
|
|
766592b83b | ||
|
|
1c3c412ce4 | ||
|
|
f9e6d1290d | ||
|
|
8ef653fcc0 | ||
|
|
fb8d66b8d3 | ||
|
|
e70b34de62 | ||
|
|
b1584fab8f | ||
|
|
718084065e | ||
|
|
57dd091e05 | ||
|
|
a1f208f1e6 | ||
|
|
581aa7279f | ||
|
|
0b29924648 | ||
|
|
49472da669 | ||
|
|
69a2eac2ff | ||
|
|
5fd632c357 | ||
|
|
bb2164c945 | ||
|
|
8c91aa5570 | ||
|
|
6db8257b1e | ||
|
|
f6e7166e79 | ||
|
|
2da8290040 | ||
|
|
4d6e8e1ca5 | ||
|
|
7e4da5b157 | ||
|
|
9acce6ddaa | ||
|
|
8054a32417 | ||
|
|
ed3958daa8 | ||
|
|
9d5c515680 | ||
|
|
0e9677965c | ||
|
|
cc29ceea80 | ||
|
|
32a17b9109 | ||
|
|
e119e18ed3 | ||
|
|
001902c881 | ||
|
|
c7a029a2bd | ||
|
|
4fac2d203b | ||
|
|
58692df0d2 | ||
|
|
68585d4638 | ||
|
|
23d2a8affc | ||
|
|
501335bc31 | ||
|
|
0cfaf7325e | ||
|
|
9c4095aaaa | ||
|
|
961df8597c | ||
|
|
139ad675b3 | ||
|
|
375afb7c33 | ||
|
|
a2330938d6 | ||
|
|
5aa517863a | ||
|
|
00cdf41899 | ||
|
|
1b98213d6d | ||
|
|
0d67424f69 | ||
|
|
1245ce984b | ||
|
|
1de1b0d6be | ||
|
|
a830cd5b1a | ||
|
|
d47059a9db | ||
|
|
37e17e9207 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -11,3 +11,4 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
@@ -0,0 +1,64 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg", "favicon.ico", "favicon.png",
|
||||
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
||||
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
||||
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
||||
];
|
||||
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html", "public/index.html",
|
||||
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
||||
"app/root.tsx", "src/root.tsx", "src/index.html",
|
||||
];
|
||||
|
||||
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
||||
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
||||
|
||||
function test(projectCwd) {
|
||||
console.log("--- Testing:", projectCwd, "---");
|
||||
|
||||
for (const c of FAVICON_CANDIDATES) {
|
||||
const full = path.join(projectCwd, c);
|
||||
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
||||
console.log(" Phase 1 FOUND:", c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 1: no match");
|
||||
|
||||
for (const sf of ICON_SOURCE_FILES) {
|
||||
const full = path.join(projectCwd, sf);
|
||||
if (!fs.existsSync(full)) continue;
|
||||
const content = fs.readFileSync(full, "utf8");
|
||||
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
||||
if (href) {
|
||||
const clean = href.replace(/^\//, "");
|
||||
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
for (const p of tryPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2 href found but file missing:", href);
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2: no match");
|
||||
}
|
||||
|
||||
function getTestPaths() {
|
||||
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
||||
if (cliPaths.length > 0) return cliPaths;
|
||||
|
||||
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
||||
if (envPaths?.length) return envPaths;
|
||||
|
||||
return [process.cwd()];
|
||||
}
|
||||
|
||||
for (const p of getTestPaths()) {
|
||||
test(path.resolve(p));
|
||||
}
|
||||
@@ -91,7 +91,7 @@ npx t3
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5173`
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [ ] External runners (i.e. running the cli on a mac mini)
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -5,7 +5,7 @@ import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
|
||||
await waitOn({
|
||||
|
||||
@@ -9,7 +9,17 @@ import {
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Schedule,
|
||||
Schema,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
@@ -75,20 +85,27 @@ export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): st
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
function waitFor<A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
|
||||
"WaitForTimeoutError",
|
||||
{
|
||||
description: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A, never>;
|
||||
function waitFor<A, B extends A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
function waitFor<A, B extends A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B, never>;
|
||||
function waitFor<A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
@@ -106,12 +123,26 @@ function waitFor<A>(
|
||||
while: (error) => error === RETRY_SIGNAL,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
|
||||
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
|
||||
),
|
||||
Effect.orDie,
|
||||
);
|
||||
}
|
||||
|
||||
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
|
||||
"OrchestrationHarnessRuntimeError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
|
||||
Effect.tryPromise({
|
||||
try: run,
|
||||
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
|
||||
});
|
||||
|
||||
export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
@@ -152,8 +183,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
@@ -185,14 +215,13 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -215,30 +244,34 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* Effect.promise(() =>
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
);
|
||||
const reactor = yield* Effect.promise(() =>
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
);
|
||||
const snapshotQuery = yield* Effect.promise(() =>
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
);
|
||||
const providerService = yield* Effect.promise(() =>
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
);
|
||||
const checkpointStore = yield* Effect.promise(() =>
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
);
|
||||
const checkpointRepository = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
);
|
||||
const pendingApprovalRepository = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
);
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
|
||||
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Exit, Option } from "effect";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
|
||||
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
|
||||
import {
|
||||
@@ -45,8 +45,14 @@ function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
|
||||
"IntegrationWaitTimeoutError",
|
||||
{
|
||||
description: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
|
||||
function waitForSync<A>(
|
||||
read: () => A,
|
||||
@@ -63,7 +69,7 @@ function waitForSync<A>(
|
||||
return value;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
|
||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||
}
|
||||
yield* sleep(10);
|
||||
}
|
||||
@@ -130,27 +136,11 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
it.live("always removes integration temp dirs when shutdown fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeOrchestrationIntegrationHarness;
|
||||
const rootDir = harness.rootDir;
|
||||
const originalStopAll = harness.providerService.stopAll.bind(harness.providerService);
|
||||
|
||||
(
|
||||
harness.providerService as unknown as {
|
||||
stopAll: typeof harness.providerService.stopAll;
|
||||
}
|
||||
).stopAll = () => originalStopAll().pipe(Effect.andThen(Effect.fail(new Error("boom"))));
|
||||
|
||||
const disposeExit = yield* Effect.exit(harness.dispose);
|
||||
assert.equal(Exit.isFailure(disposeExit), true);
|
||||
assert.equal(fs.existsSync(rootDir), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -329,7 +319,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
const secondTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurnId === "turn-2" &&
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
||||
);
|
||||
@@ -663,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurnId === "turn-2" &&
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
||||
8000,
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
|
||||
@@ -45,7 +45,14 @@ function makeSnapshot(input: {
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -40,7 +40,7 @@ function normalizeCodexError(
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (error instanceof TextGenerationError) {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const readStreamAsString = (
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, unknown>,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
|
||||
@@ -393,7 +393,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
})),
|
||||
);
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
type GitHubCliShape,
|
||||
@@ -23,7 +23,7 @@ interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
createdPrUrl?: string;
|
||||
defaultBranch?: string;
|
||||
failWith?: Error;
|
||||
failWith?: GitHubCliError;
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Effect.Effect<{ title: string; body: string }, unknown>;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
}
|
||||
|
||||
function makeTempDir(
|
||||
@@ -58,7 +58,7 @@ function runGit(
|
||||
allowNonZeroExit = false,
|
||||
): Effect.Effect<
|
||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||
unknown,
|
||||
GitCommandError,
|
||||
GitService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
@@ -74,7 +74,7 @@ function runGit(
|
||||
|
||||
function initRepo(
|
||||
cwd: string,
|
||||
): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> {
|
||||
): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
@@ -88,7 +88,7 @@ function initRepo(
|
||||
|
||||
function createBareRemote(): Effect.Effect<
|
||||
string,
|
||||
unknown,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
@@ -139,34 +139,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
};
|
||||
}
|
||||
|
||||
const normalizeGhError = (error: Error): GitHubCliError => {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
};
|
||||
|
||||
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
service: GitHubCliShape;
|
||||
ghCalls: string[];
|
||||
@@ -179,7 +151,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
if (scenario.failWith) {
|
||||
return Effect.fail(normalizeGhError(scenario.failWith));
|
||||
return Effect.fail(scenario.failWith);
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "list") {
|
||||
@@ -325,7 +297,7 @@ function makeManager(input?: {
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -352,17 +324,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
expect(status.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-merged-pr",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-30T10:00:00Z",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 45,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-31T10:00:00Z",
|
||||
updatedAt: "2026-02-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -373,13 +431,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("Command not found: gh"),
|
||||
failWith: new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -600,7 +661,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
expect(errorMessage).toContain("detached HEAD");
|
||||
}),
|
||||
@@ -617,7 +678,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("Command not found: gh"),
|
||||
failWith: new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -626,7 +690,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
|
||||
}),
|
||||
@@ -643,7 +707,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("authentication failed"),
|
||||
failWith: new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -652,7 +719,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
expect(errorMessage).toContain("gh auth login");
|
||||
}),
|
||||
|
||||
@@ -16,6 +16,62 @@ interface OpenPrInfo {
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
@@ -79,12 +135,13 @@ function extractBranchFromRef(ref: string): string {
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
function toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
@@ -92,6 +149,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,10 +181,56 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
url: first.url,
|
||||
baseRefName: first.baseRefName,
|
||||
headRefName: first.headRefName,
|
||||
} satisfies OpenPrInfo;
|
||||
state: "open",
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const findLatestPr = (cwd: string, branch: string) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
return latestOpenPr;
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
@@ -258,10 +362,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||
const details = yield* gitCore.statusDetails(input.cwd);
|
||||
|
||||
const openPr =
|
||||
details.branch && details.hasUpstream
|
||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null;
|
||||
@@ -273,7 +377,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
pr,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
@@ -50,7 +50,7 @@ layer("GitServiceLive", (it) => {
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag === "Failure") {
|
||||
assert.ok(result.failure instanceof GitCommandError);
|
||||
assert.ok(Schema.is(GitCommandError)(result.failure));
|
||||
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
|
||||
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -28,7 +28,7 @@ function toGitCommandError(
|
||||
detail: string,
|
||||
) {
|
||||
return (cause: unknown) =>
|
||||
cause instanceof GitCommandError
|
||||
Schema.is(GitCommandError)(cause)
|
||||
? cause
|
||||
: new GitCommandError({
|
||||
operation: input.operation,
|
||||
@@ -39,9 +39,9 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn(function* (
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, unknown>,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -211,13 +211,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
|
||||
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isFalse(
|
||||
configState.keybindings.some(
|
||||
(entry) =>
|
||||
// @ts-expect-error - invalid command
|
||||
entry.command === "invalid.command",
|
||||
),
|
||||
);
|
||||
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
|
||||
@@ -65,6 +65,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
|
||||
@@ -117,7 +117,10 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.promise(() => import("open"));
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -40,6 +41,7 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||
@@ -91,7 +93,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
|
||||
async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: {
|
||||
latestTurnId: string | null;
|
||||
latestTurn: { turnId: string } | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
@@ -99,7 +101,7 @@ async function waitForThread(
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
latestTurnId: string | null;
|
||||
latestTurn: { turnId: string } | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
@@ -231,11 +233,12 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
@@ -317,6 +320,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -332,7 +337,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -347,14 +352,14 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
@@ -379,6 +384,83 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-main"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -394,6 +476,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -409,7 +493,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
turnId: asProviderTurnId("turn-missing-baseline"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
@@ -445,6 +529,8 @@ describe("CheckpointReactor", () => {
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
@@ -481,6 +567,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-missing"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -497,7 +585,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
turnId: asProviderTurnId("turn-missing-cwd"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
@@ -529,6 +617,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -544,7 +634,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
});
|
||||
@@ -580,6 +670,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -595,7 +687,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
turnId: asProviderTurnId("turn-runtime-failure"),
|
||||
turnCount: 1,
|
||||
status: "completed",
|
||||
});
|
||||
@@ -607,7 +699,7 @@ describe("CheckpointReactor", () => {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
@@ -634,6 +726,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -684,7 +778,7 @@ describe("CheckpointReactor", () => {
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||
|
||||
expect(thread.latestTurnId).toBe("turn-1");
|
||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread.checkpoints).toHaveLength(1);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
@@ -713,6 +807,8 @@ describe("CheckpointReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
@@ -36,6 +37,17 @@ function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
if (left === null || left === undefined || right === null || right === undefined) {
|
||||
return false;
|
||||
}
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
||||
switch (status) {
|
||||
case "failed":
|
||||
@@ -173,6 +185,21 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||
if (
|
||||
projectedProviderThreadId !== null &&
|
||||
eventProviderThreadId !== null &&
|
||||
!sameId(projectedProviderThreadId, eventProviderThreadId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -92,6 +92,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -428,6 +430,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request" as const,
|
||||
sandboxMode: "workspace-write" as const,
|
||||
createdAt,
|
||||
};
|
||||
|
||||
@@ -586,6 +590,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now(),
|
||||
}),
|
||||
),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,11 @@
|
||||
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
@@ -27,10 +33,16 @@ import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OrchestrationProjectionPipeline,
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
IMAGE_EXTENSION_BY_MIME_TYPE,
|
||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||
} from "../../projectFaviconRoute.ts";
|
||||
|
||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
@@ -48,9 +60,122 @@ type ProjectorName =
|
||||
|
||||
interface ProjectorDefinition {
|
||||
readonly name: ProjectorName;
|
||||
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly apply: (
|
||||
event: OrchestrationEvent,
|
||||
attachmentSideEffects: AttachmentSideEffects,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
interface PendingAttachmentWrite {
|
||||
readonly absolutePath: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
|
||||
interface AttachmentSideEffects {
|
||||
readonly writes: Array<PendingAttachmentWrite>;
|
||||
readonly deletedThreadIds: Set<string>;
|
||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||
}
|
||||
|
||||
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = encodeURIComponent(threadId);
|
||||
if (
|
||||
segment.length === 0 ||
|
||||
segment === "." ||
|
||||
segment === ".." ||
|
||||
segment.includes("/") ||
|
||||
segment.includes("\\") ||
|
||||
segment.includes("\0")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const mimeType = match[1]?.trim().toLowerCase();
|
||||
const base64 = match[2]?.replace(/\s+/g, "");
|
||||
if (!mimeType || !base64) return null;
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
function inferImageExtension(attachment: Extract<ChatAttachment, { type: "image" }>): string {
|
||||
const normalizedMimeType = attachment.mimeType.toLowerCase();
|
||||
if (normalizedMimeType.startsWith("image/")) {
|
||||
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[normalizedMimeType];
|
||||
if (fromMime) return fromMime;
|
||||
}
|
||||
const ext = Mime.getExtension(attachment.mimeType);
|
||||
if (ext && SAFE_IMAGE_FILE_EXTENSIONS.has(ext)) return ext;
|
||||
return ".bin";
|
||||
}
|
||||
|
||||
const materializeAttachmentsForProjection = Effect.fn(function* (input: {
|
||||
readonly threadId: string;
|
||||
readonly messageId: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
readonly stageFileWrite: (pendingWrite: PendingAttachmentWrite) => void;
|
||||
}) {
|
||||
if (input.attachments.length === 0) return [];
|
||||
|
||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(serverConfig)) return input.attachments;
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const attachmentsRootDir = path.join(serverConfig.value.stateDir, "attachments");
|
||||
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment materialization for unsafe thread id", {
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
});
|
||||
return input.attachments;
|
||||
}
|
||||
const messageSegment = encodeURIComponent(input.messageId);
|
||||
|
||||
return yield* Effect.forEach(
|
||||
input.attachments,
|
||||
(attachment, index) =>
|
||||
Effect.sync(() => {
|
||||
if (attachment.type !== "image" || !attachment.dataUrl.startsWith("data:")) {
|
||||
return attachment;
|
||||
}
|
||||
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed) {
|
||||
return attachment;
|
||||
}
|
||||
if (!parsed.mimeType.startsWith("image/")) {
|
||||
return attachment;
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0) return attachment;
|
||||
|
||||
const fileName = `${index}${inferImageExtension({
|
||||
...attachment,
|
||||
mimeType: parsed.mimeType,
|
||||
})}`;
|
||||
const uniqueFileName = `${messageSegment}-${fileName}`;
|
||||
const relativePath = `${threadSegment}/${uniqueFileName}`;
|
||||
const absolutePath = path.join(attachmentsRootDir, threadSegment, uniqueFileName);
|
||||
input.stageFileWrite({ absolutePath, bytes });
|
||||
|
||||
return {
|
||||
...attachment,
|
||||
dataUrl: `${ATTACHMENTS_ROUTE_PREFIX}/${relativePath}`,
|
||||
} satisfies ChatAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return null;
|
||||
@@ -163,6 +288,138 @@ function retainProjectionActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function toAttachmentRelativePath(dataUrl: string): string | null {
|
||||
const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
|
||||
if (!dataUrl.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const relativePath = dataUrl.slice(prefix.length).replace(/^[/\\]+/, "");
|
||||
if (relativePath.length === 0 || relativePath.startsWith("..")) {
|
||||
return null;
|
||||
}
|
||||
return relativePath.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
): Set<string> {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
return new Set();
|
||||
}
|
||||
const threadPrefix = `${threadSegment}/`;
|
||||
const relativePaths = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
||||
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
||||
continue;
|
||||
}
|
||||
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
continue;
|
||||
}
|
||||
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
||||
}
|
||||
}
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||
readonly sideEffects: AttachmentSideEffects;
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(serverConfig)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.deletedThreadIds,
|
||||
(threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.prunedThreadRelativePaths.entries(),
|
||||
([threadId, keptThreadRelativePaths]) => {
|
||||
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
const entries = yield* input.fileSystem
|
||||
.readDirectory(threadDir, { recursive: true })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
||||
const fileInfo = yield* input.fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
||||
yield* input.fileSystem.remove(absolutePath, { force: true });
|
||||
}
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
const writesByPath = new Map<string, Uint8Array>();
|
||||
for (const pendingWrite of input.sideEffects.writes) {
|
||||
// Last write wins for a path so updated attachment contents replace stale bytes.
|
||||
writesByPath.set(pendingWrite.absolutePath, pendingWrite.bytes);
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
writesByPath.entries(),
|
||||
([absolutePath, bytes]) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.fileSystem.makeDirectory(input.path.dirname(absolutePath), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* input.fileSystem.writeFile(absolutePath, bytes);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
@@ -175,7 +432,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
@@ -233,7 +493,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
@@ -272,6 +532,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -351,7 +612,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
@@ -367,12 +631,24 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
: existingMessage && event.payload.text.length === 0
|
||||
? existingMessage.text
|
||||
: event.payload.text;
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
attachments: event.payload.attachments,
|
||||
stageFileWrite: (pendingWrite) => {
|
||||
attachmentSideEffects.writes.push(pendingWrite);
|
||||
},
|
||||
}).pipe(Effect.provideService(Path.Path, path))
|
||||
: existingMessage?.attachments;
|
||||
yield* projectionThreadMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: nextText,
|
||||
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||
isStreaming: event.payload.streaming,
|
||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -406,6 +682,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||
event.payload.threadId,
|
||||
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -414,7 +694,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended":
|
||||
@@ -462,7 +745,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.type !== "thread.session-set") {
|
||||
return;
|
||||
@@ -473,13 +759,18 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
providerName: event.payload.session.providerName,
|
||||
providerSessionId: event.payload.session.providerSessionId,
|
||||
providerThreadId: event.payload.session.providerThreadId,
|
||||
approvalPolicy: event.payload.session.approvalPolicy,
|
||||
sandboxMode: event.payload.session.sandboxMode,
|
||||
activeTurnId: event.payload.session.activeTurnId,
|
||||
lastError: event.payload.session.lastError,
|
||||
updatedAt: event.payload.session.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested": {
|
||||
@@ -712,7 +1003,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended": {
|
||||
@@ -835,17 +1129,40 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
];
|
||||
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
sql.withTransaction(
|
||||
projector.apply(event).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
Effect.gen(function* () {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
writes: [],
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
};
|
||||
|
||||
yield* sql.withTransaction(
|
||||
projector.apply(event, attachmentSideEffects).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* runAttachmentSideEffects({
|
||||
sideEffects: attachmentSideEffects,
|
||||
fileSystem,
|
||||
path,
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
sequence: event.sequence,
|
||||
eventType: event.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
projectionStateRepository
|
||||
@@ -899,6 +1216,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline,
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
|
||||
@@ -143,6 +143,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -153,6 +155,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'codex',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
'on-request',
|
||||
'workspace-write',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'2026-02-24T00:00:07.000Z'
|
||||
@@ -239,7 +243,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: asTurnId("turn-1"),
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
deletedAt: null,
|
||||
@@ -282,6 +293,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
@@ -38,12 +43,13 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -55,6 +61,15 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
||||
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
||||
}),
|
||||
);
|
||||
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||
threadId: ProjectionThread.fields.threadId,
|
||||
turnId: TurnId,
|
||||
state: Schema.String,
|
||||
requestedAt: IsoDateTime,
|
||||
startedAt: Schema.NullOr(IsoDateTime),
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
assistantMessageId: Schema.NullOr(MessageId),
|
||||
});
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
@@ -158,6 +173,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -196,6 +212,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -224,6 +242,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listLatestTurnRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionStateRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionStateDbRowSchema,
|
||||
@@ -248,6 +285,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
activityRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
latestTurnRows,
|
||||
stateRows,
|
||||
] = yield* Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
@@ -298,6 +336,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -312,6 +358,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||
|
||||
let updatedAt: string | null = null;
|
||||
|
||||
@@ -332,6 +379,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
@@ -370,6 +418,34 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
||||
}
|
||||
|
||||
for (const row of latestTurnRows) {
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
if (latestTurnByThread.has(row.threadId)) {
|
||||
continue;
|
||||
}
|
||||
latestTurnByThread.set(row.threadId, {
|
||||
turnId: row.turnId,
|
||||
state:
|
||||
row.state === "error"
|
||||
? "error"
|
||||
: row.state === "interrupted"
|
||||
? "interrupted"
|
||||
: row.state === "completed"
|
||||
? "completed"
|
||||
: "running",
|
||||
requestedAt: row.requestedAt,
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
});
|
||||
}
|
||||
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
sessionsByThread.set(row.threadId, {
|
||||
@@ -378,6 +454,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
providerName: row.providerName,
|
||||
providerSessionId: row.providerSessionId,
|
||||
providerThreadId: row.providerThreadId,
|
||||
approvalPolicy: row.approvalPolicy,
|
||||
sandboxMode: row.sandboxMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -402,7 +480,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
model: row.model,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurnId: row.latestTurnId,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
|
||||
@@ -71,16 +71,18 @@ describe("ProviderCommandReactor", () => {
|
||||
async function createHarness() {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const startSession = vi.fn((_: unknown, __: unknown) =>
|
||||
Effect.succeed({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
let nextSessionIndex = 1;
|
||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
return Effect.succeed({
|
||||
sessionId: asSessionId(`sess-${sessionIndex}`),
|
||||
provider: "codex" as const,
|
||||
status: "ready" as const,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
@@ -171,6 +173,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello reactor",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -181,11 +185,181 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unchanged-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unchanged-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("restarts the provider session when runtime mode changes", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-runtime-mode-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-runtime-mode-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
sessionId: asSessionId("sess-2"),
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-2");
|
||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
|
||||
Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||
expect(thread?.session?.approvalPolicy).toBe("never");
|
||||
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
|
||||
});
|
||||
|
||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||
@@ -203,6 +377,8 @@ describe("ProviderCommandReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
@@ -242,6 +418,8 @@ describe("ProviderCommandReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
@@ -284,6 +462,8 @@ describe("ProviderCommandReactor", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
|
||||
@@ -3,9 +3,13 @@ import {
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderApprovalPolicy,
|
||||
type ProviderKind,
|
||||
type ProviderSandboxMode,
|
||||
type OrchestrationSession,
|
||||
type ThreadId,
|
||||
type ProviderSession,
|
||||
type ProviderThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
@@ -60,6 +64,8 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -128,6 +134,10 @@ const make = Effect.gen(function* () {
|
||||
const ensureSessionForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly approvalPolicy?: ProviderApprovalPolicy;
|
||||
readonly sandboxMode?: ProviderSandboxMode;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
@@ -135,11 +145,10 @@ const make = Effect.gen(function* () {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
return existingSessionId;
|
||||
}
|
||||
|
||||
const desiredApprovalPolicy =
|
||||
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
|
||||
const desiredSandboxMode =
|
||||
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
|
||||
const preferredProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||
? thread.session.providerName
|
||||
@@ -149,28 +158,62 @@ const make = Effect.gen(function* () {
|
||||
projects: readModel.projects,
|
||||
});
|
||||
|
||||
const startedSession = yield* providerService.startSession(threadId, {
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(thread.model ? { model: thread.model } : {}),
|
||||
});
|
||||
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
|
||||
providerService.startSession(threadId, {
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(thread.model ? { model: thread.model } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
});
|
||||
|
||||
yield* setThreadSession({
|
||||
threadId,
|
||||
session: {
|
||||
const bindSessionToThread = (session: ProviderSession) =>
|
||||
setThreadSession({
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
|
||||
providerName: startedSession.provider,
|
||||
providerSessionId: startedSession.sessionId,
|
||||
providerThreadId: startedSession.threadId ?? null,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
lastError: startedSession.lastError ?? null,
|
||||
updatedAt: startedSession.updatedAt,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
session: {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
providerName: session.provider,
|
||||
providerSessionId: session.sessionId,
|
||||
providerThreadId: session.threadId ?? null,
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
lastError: session.lastError ?? null,
|
||||
updatedAt: session.updatedAt,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
const approvalPolicyChanged =
|
||||
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||
const sandboxModeChanged =
|
||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||
|
||||
if (!approvalPolicyChanged && !sandboxModeChanged) {
|
||||
return existingSessionId;
|
||||
}
|
||||
|
||||
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
|
||||
yield* bindSessionToThread(restartedSession);
|
||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
|
||||
threadId,
|
||||
sessionId: existingSessionId,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return restartedSession.sessionId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession();
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.sessionId;
|
||||
});
|
||||
|
||||
@@ -180,13 +223,18 @@ const make = Effect.gen(function* () {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly model?: string;
|
||||
readonly effort?: string;
|
||||
readonly approvalPolicy: ProviderApprovalPolicy;
|
||||
readonly sandboxMode: ProviderSandboxMode;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
|
||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandboxMode: input.sandboxMode,
|
||||
});
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
|
||||
@@ -231,6 +279,8 @@ const make = Effect.gen(function* () {
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||
approvalPolicy: event.payload.approvalPolicy,
|
||||
sandboxMode: event.payload.sandboxMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
@@ -307,6 +357,8 @@ const make = Effect.gen(function* () {
|
||||
providerName: thread.session?.providerName ?? null,
|
||||
providerSessionId: null,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
activeTurnId: null,
|
||||
lastError: thread.session?.lastError ?? null,
|
||||
updatedAt: now,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
ProviderSessionId,
|
||||
@@ -30,9 +31,12 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId =>
|
||||
ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness() {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
@@ -162,6 +166,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
@@ -216,6 +222,112 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(thread.session?.lastError).toBe("turn failed");
|
||||
});
|
||||
|
||||
it("ignores auxiliary turn completions from a different provider thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-primary"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-primary"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-primary"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-primary"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores non-active turn completion when runtime omits thread id", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-guarded"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-guarded-main"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-guarded-main",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-guarded-other"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-guarded-other"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-guarded-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-guarded-main"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
|
||||
it("maps message delta/completed into finalized assistant messages", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -258,6 +370,203 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("buffers assistant deltas by default until completion", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
itemId: asItemId("item-buffered"),
|
||||
delta: "buffer me",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
eventId: asEventId("evt-message-completed-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
itemId: asItemId("item-buffered"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
|
||||
);
|
||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
||||
expect(message?.text).toBe("buffer me");
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("message-streaming-mode"),
|
||||
role: "user",
|
||||
text: "stream please",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-mode",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
itemId: asItemId("item-streaming-mode"),
|
||||
delta: "hello live",
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
message.streaming &&
|
||||
message.text === "hello live",
|
||||
),
|
||||
);
|
||||
const liveMessage = liveThread.messages.find(
|
||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||
);
|
||||
expect(liveMessage?.streaming).toBe(true);
|
||||
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
eventId: asEventId("evt-message-completed-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
itemId: asItemId("item-streaming-mode"),
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const finalMessage = finalThread.messages.find(
|
||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||
);
|
||||
expect(finalMessage?.text).toBe("hello live");
|
||||
expect(finalMessage?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("spills oversized buffered deltas and still finalizes full assistant text", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const oversizedText = "x".repeat(40_000);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffer-spill",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
itemId: asItemId("item-buffer-spill"),
|
||||
delta: oversizedText,
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
eventId: asEventId("evt-message-completed-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
itemId: asItemId("item-buffer-spill"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
||||
expect(message?.text.length).toBe(oversizedText.length);
|
||||
expect(message?.text).toBe(oversizedText);
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import {
|
||||
type AssistantDeliveryMode,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderApprovalPolicy,
|
||||
type ProviderSandboxMode,
|
||||
ProviderThreadId,
|
||||
type ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -19,13 +24,47 @@ import {
|
||||
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "on-request";
|
||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
|
||||
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
|
||||
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
|
||||
|
||||
type TurnStartRequestedDomainEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
{ type: "thread.turn-start-requested" }
|
||||
>;
|
||||
|
||||
type RuntimeIngestionInput =
|
||||
| {
|
||||
source: "runtime";
|
||||
event: ProviderRuntimeEvent;
|
||||
}
|
||||
| {
|
||||
source: "domain";
|
||||
event: TurnStartRequestedDomainEvent;
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
if (left === null || left === undefined || right === null || right === undefined) {
|
||||
return false;
|
||||
}
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function truncateDetail(value: string, limit = 180): string {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
@@ -88,6 +127,7 @@ function runtimeEventToActivities(
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.completed": {
|
||||
return [
|
||||
{
|
||||
@@ -104,6 +144,7 @@ function runtimeEventToActivities(
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.started": {
|
||||
return [
|
||||
{
|
||||
@@ -130,12 +171,22 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
|
||||
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
|
||||
DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
);
|
||||
|
||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
||||
lookup: () => Effect.succeed(new Set<MessageId>()),
|
||||
});
|
||||
|
||||
const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
|
||||
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
|
||||
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
|
||||
lookup: () => Effect.succeed(""),
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
sessionId: ProviderSessionId,
|
||||
turnId: TurnId,
|
||||
@@ -189,6 +240,76 @@ const make = Effect.gen(function* () {
|
||||
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
|
||||
|
||||
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
|
||||
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
|
||||
Effect.flatMap((existingText) =>
|
||||
Effect.gen(function* () {
|
||||
const nextText = Option.match(existingText, {
|
||||
onNone: () => delta,
|
||||
onSome: (text) => `${text}${delta}`,
|
||||
});
|
||||
if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
|
||||
yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
|
||||
return "";
|
||||
}
|
||||
|
||||
// Safety valve: flush full buffered text as an assistant delta to cap memory.
|
||||
yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
|
||||
return nextText;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const takeBufferedAssistantText = (messageId: MessageId) =>
|
||||
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
|
||||
Effect.flatMap((existingText) =>
|
||||
Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(
|
||||
Effect.as(Option.getOrElse(existingText, () => "")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const clearBufferedAssistantText = (messageId: MessageId) =>
|
||||
Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
|
||||
|
||||
const clearAssistantMessageState = (messageId: MessageId) =>
|
||||
clearBufferedAssistantText(messageId);
|
||||
|
||||
const finalizeAssistantMessage = (input: {
|
||||
event: ProviderRuntimeEvent;
|
||||
threadId: ThreadId;
|
||||
messageId: MessageId;
|
||||
turnId?: TurnId;
|
||||
createdAt: string;
|
||||
commandTag: string;
|
||||
finalDeltaCommandTag: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const text = yield* takeBufferedAssistantText(input.messageId);
|
||||
|
||||
if (text.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: text,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
yield* clearAssistantMessageState(input.messageId);
|
||||
});
|
||||
|
||||
const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = `${sessionId}:`;
|
||||
@@ -196,12 +317,25 @@ const make = Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
turnKeys,
|
||||
(key) =>
|
||||
key.startsWith(prefix) ? Cache.invalidate(turnMessageIdsByTurnKey, key) : Effect.void,
|
||||
Effect.gen(function* () {
|
||||
if (!key.startsWith(prefix)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
|
||||
if (Option.isSome(messageIds)) {
|
||||
yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
}
|
||||
|
||||
yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const processEvent = (event: ProviderRuntimeEvent) =>
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
@@ -210,6 +344,62 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) return;
|
||||
|
||||
const now = event.createdAt;
|
||||
const sessionProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
|
||||
const matchesThreadScope =
|
||||
eventProviderThreadId === null ||
|
||||
sessionProviderThreadId === null ||
|
||||
sameId(eventProviderThreadId, sessionProviderThreadId);
|
||||
const conflictsWithActiveTurn =
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
||||
|
||||
const shouldApplyThreadLifecycle = (() => {
|
||||
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
|
||||
return true;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "session.exited":
|
||||
return true;
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
if (!matchesThreadScope) {
|
||||
return false;
|
||||
}
|
||||
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
|
||||
if (
|
||||
eventProviderThreadId !== null &&
|
||||
sessionProviderThreadId !== null &&
|
||||
!sameId(eventProviderThreadId, sessionProviderThreadId)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
case "turn.started":
|
||||
if (!matchesThreadScope) {
|
||||
return false;
|
||||
}
|
||||
return !conflictsWithActiveTurn;
|
||||
case "turn.completed":
|
||||
if (!matchesThreadScope) {
|
||||
return false;
|
||||
}
|
||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||
return false;
|
||||
}
|
||||
// Only the active turn may close the lifecycle state.
|
||||
if (activeTurnId !== null && eventTurnId !== undefined) {
|
||||
return sameId(activeTurnId, eventTurnId);
|
||||
}
|
||||
// Without an active turn, only accept completion when no thread mismatch signal exists.
|
||||
return eventProviderThreadId === null || sessionProviderThreadId === null;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
})();
|
||||
|
||||
if (
|
||||
event.type === "session.started" ||
|
||||
@@ -218,8 +408,7 @@ const make = Effect.gen(function* () {
|
||||
event.type === "turn.started" ||
|
||||
event.type === "turn.completed"
|
||||
) {
|
||||
const activeTurnId =
|
||||
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
|
||||
const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) : null;
|
||||
const providerThreadIdFromEvent =
|
||||
event.type === "thread.started"
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
@@ -227,7 +416,7 @@ const make = Effect.gen(function* () {
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
const providerThreadId =
|
||||
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
|
||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
@@ -243,22 +432,26 @@ const make = Effect.gen(function* () {
|
||||
? null
|
||||
: (thread.session?.lastError ?? null);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
if (shouldApplyThreadLifecycle) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
threadId: thread.id,
|
||||
status,
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
activeTurnId,
|
||||
lastError,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status,
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
activeTurnId: nextActiveTurnId,
|
||||
lastError,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "message.delta" && event.delta.length > 0) {
|
||||
@@ -270,15 +463,31 @@ const make = Effect.gen(function* () {
|
||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: event.delta,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
|
||||
if (assistantDeliveryMode === "buffered") {
|
||||
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, event.delta);
|
||||
if (spillChunk.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: spillChunk,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: event.delta,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
@@ -288,13 +497,14 @@ const make = Effect.gen(function* () {
|
||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(event, "assistant-complete"),
|
||||
yield* finalizeAssistantMessage({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize",
|
||||
});
|
||||
|
||||
if (turnId) {
|
||||
@@ -306,15 +516,19 @@ const make = Effect.gen(function* () {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||
yield* Effect.forEach(assistantMessageIds, (assistantMessageId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(event, "assistant-complete-finalize"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
}),
|
||||
yield* Effect.forEach(
|
||||
assistantMessageIds,
|
||||
(assistantMessageId) =>
|
||||
finalizeAssistantMessage({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||
}
|
||||
@@ -325,27 +539,38 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "runtime.error") {
|
||||
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
|
||||
? true
|
||||
: matchesThreadScope &&
|
||||
(activeTurnId === null ||
|
||||
eventTurnId === undefined ||
|
||||
sameId(activeTurnId, eventTurnId));
|
||||
|
||||
const providerThreadId =
|
||||
event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: (thread.session?.providerThreadId ?? null);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
if (shouldApplyRuntimeError) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||
threadId: thread.id,
|
||||
status: "error",
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
activeTurnId: toTurnId(event.turnId) ?? null,
|
||||
lastError: event.message,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "error",
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
activeTurnId: eventTurnId ?? null,
|
||||
lastError: event.message,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const activities = runtimeEventToActivities(event);
|
||||
@@ -360,33 +585,50 @@ const make = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const processEventSafely = (event: ProviderRuntimeEvent) =>
|
||||
processEvent(event).pipe(
|
||||
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
|
||||
Ref.set(
|
||||
assistantDeliveryModeRef,
|
||||
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
);
|
||||
|
||||
const processInput = (input: RuntimeIngestionInput) =>
|
||||
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: RuntimeIngestionInput) =>
|
||||
processInput(input).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("provider runtime ingestion failed to process event", {
|
||||
eventId: event.eventId,
|
||||
eventType: event.type,
|
||||
source: input.source,
|
||||
eventId: input.event.eventId,
|
||||
eventType: input.event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
|
||||
const providerEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.addFinalizer(() => Queue.shutdown(providerEventQueue).pipe(Effect.asVoid));
|
||||
const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>();
|
||||
yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.forever(Queue.take(providerEventQueue).pipe(Effect.flatMap(processEventSafely))),
|
||||
Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))),
|
||||
);
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) =>
|
||||
Queue.offer(providerEventQueue, event).pipe(Effect.asVoid),
|
||||
Queue.offer(inputQueue, { source: "runtime", event }).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (event.type !== "thread.turn-start-requested") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(inputQueue, { source: "domain", event }).pipe(Effect.asVoid);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -54,7 +54,7 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
latestTurnId: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
@@ -70,7 +70,7 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
latestTurnId: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
@@ -90,6 +90,8 @@ const messageSendCommand: OrchestrationCommand = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
|
||||
@@ -152,6 +152,8 @@ describe("decider project scripts", () => {
|
||||
},
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
@@ -162,7 +164,20 @@ describe("decider project scripts", () => {
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events).toHaveLength(2);
|
||||
expect(events[0]?.type).toBe("thread.message-sent");
|
||||
expect(events[1]?.type).toBe("thread.turn-start-requested");
|
||||
expect(events[1]?.causationEventId).toBe(events[0]?.eventId ?? null);
|
||||
const turnStartEvent = events[1];
|
||||
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
|
||||
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
|
||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
||||
return;
|
||||
}
|
||||
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "./commandInvariants.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
|
||||
|
||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||
@@ -252,6 +253,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
messageId: command.message.messageId,
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
approvalPolicy: command.approvalPolicy,
|
||||
sandboxMode: command.sandboxMode,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -75,7 +75,7 @@ describe("orchestration projector", () => {
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
@@ -135,6 +135,8 @@ describe("orchestration projector", () => {
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
@@ -193,6 +195,8 @@ describe("orchestration projector", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
@@ -203,7 +207,7 @@ describe("orchestration projector", () => {
|
||||
);
|
||||
|
||||
const thread = afterRunning.threads[0];
|
||||
expect(thread?.latestTurnId).toBe("turn-1");
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
});
|
||||
|
||||
@@ -500,7 +504,7 @@ describe("orchestration projector", () => {
|
||||
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
||||
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
||||
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
||||
expect(thread?.latestTurnId).toBe("turn-1");
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
});
|
||||
|
||||
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
||||
|
||||
@@ -26,6 +26,12 @@ type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
||||
const MAX_THREAD_MESSAGES = 2_000;
|
||||
const MAX_THREAD_CHECKPOINTS = 500;
|
||||
|
||||
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
|
||||
if (status === "error") return "error" as const;
|
||||
if (status === "missing") return "interrupted" as const;
|
||||
return "completed" as const;
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
threads: ReadonlyArray<OrchestrationThread>,
|
||||
threadId: ThreadId,
|
||||
@@ -40,9 +46,10 @@ function decodeForEvent<A>(
|
||||
eventType: OrchestrationEvent["type"],
|
||||
field: string,
|
||||
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
|
||||
return Schema.decodeUnknownEffect(schema)(value).pipe(
|
||||
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
|
||||
) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
|
||||
return Effect.try({
|
||||
try: () => Schema.decodeUnknownSync(schema as any)(value),
|
||||
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
|
||||
});
|
||||
}
|
||||
|
||||
function retainThreadMessagesAfterRevert(
|
||||
@@ -219,7 +226,7 @@ export function projectEvent(
|
||||
model: payload.model,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
latestTurnId: null,
|
||||
latestTurn: null,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
deletedAt: null,
|
||||
@@ -350,7 +357,26 @@ export function projectEvent(
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
session,
|
||||
latestTurnId: session.activeTurnId,
|
||||
latestTurn:
|
||||
session.status === "running" && session.activeTurnId !== null
|
||||
? {
|
||||
turnId: session.activeTurnId,
|
||||
state: "running",
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === session.activeTurnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: session.updatedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === session.activeTurnId
|
||||
? (thread.latestTurn.startedAt ?? session.updatedAt)
|
||||
: session.updatedAt,
|
||||
completedAt: null,
|
||||
assistantMessageId:
|
||||
thread.latestTurn?.turnId === session.activeTurnId
|
||||
? thread.latestTurn.assistantMessageId
|
||||
: null,
|
||||
}
|
||||
: thread.latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
@@ -395,7 +421,20 @@ export function projectEvent(
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
checkpoints,
|
||||
latestTurnId: payload.turnId,
|
||||
latestTurn: {
|
||||
turnId: payload.turnId,
|
||||
state: checkpointStatusToLatestTurnState(payload.status),
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: payload.completedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||
: payload.completedAt,
|
||||
completedAt: payload.completedAt,
|
||||
assistantMessageId: payload.assistantMessageId,
|
||||
},
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
@@ -421,8 +460,18 @@ export function projectEvent(
|
||||
).slice(-MAX_THREAD_MESSAGES);
|
||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||
|
||||
const latestTurnId =
|
||||
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
|
||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||
const latestTurn =
|
||||
latestCheckpoint === null
|
||||
? null
|
||||
: {
|
||||
turnId: latestCheckpoint.turnId,
|
||||
state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
|
||||
requestedAt: latestCheckpoint.completedAt,
|
||||
startedAt: latestCheckpoint.completedAt,
|
||||
completedAt: latestCheckpoint.completedAt,
|
||||
assistantMessageId: latestCheckpoint.assistantMessageId,
|
||||
};
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
@@ -430,7 +479,7 @@ export function projectEvent(
|
||||
checkpoints,
|
||||
messages,
|
||||
activities,
|
||||
latestTurnId,
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
|
||||
const layer = it.layer(
|
||||
ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
);
|
||||
|
||||
layer("ProjectionThreadMessageRepository", (it) => {
|
||||
it.effect("preserves existing attachments when upsert omits attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
|
||||
const createdAt = "2026-02-28T19:00:00.000Z";
|
||||
const updatedAt = "2026-02-28T19:00:01.000Z";
|
||||
const persistedAttachments = [
|
||||
{
|
||||
type: "image" as const,
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
||||
},
|
||||
];
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "user",
|
||||
text: "initial",
|
||||
attachments: persistedAttachments,
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "user",
|
||||
text: "updated",
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:00:02.000Z",
|
||||
});
|
||||
|
||||
const rows = yield* repository.listByThreadId({ threadId });
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]?.text, "updated");
|
||||
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-clear-attachments");
|
||||
const createdAt = "2026-02-28T19:10:00.000Z";
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "with attachment",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
||||
},
|
||||
],
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:10:01.000Z",
|
||||
});
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "cleared",
|
||||
attachments: [],
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:10:02.000Z",
|
||||
});
|
||||
|
||||
const rows = yield* repository.listByThreadId({ threadId });
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]?.text, "cleared");
|
||||
assert.deepEqual(rows[0]?.attachments, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -22,14 +24,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
|
||||
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
||||
Request: ProjectionThreadMessage,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
execute: (row) => {
|
||||
const nextAttachmentsJson =
|
||||
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||
return sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
@@ -40,6 +45,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
${row.turnId},
|
||||
${row.role},
|
||||
${row.text},
|
||||
COALESCE(
|
||||
${nextAttachmentsJson},
|
||||
(
|
||||
SELECT attachments_json
|
||||
FROM projection_thread_messages
|
||||
WHERE message_id = ${row.messageId}
|
||||
)
|
||||
),
|
||||
${row.isStreaming ? 1 : 0},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
@@ -50,10 +63,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
turn_id = excluded.turn_id,
|
||||
role = excluded.role,
|
||||
text = excluded.text,
|
||||
attachments_json = COALESCE(
|
||||
excluded.attachments_json,
|
||||
projection_thread_messages.attachments_json
|
||||
),
|
||||
is_streaming = excluded.is_streaming,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
`;
|
||||
},
|
||||
});
|
||||
|
||||
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
||||
@@ -67,6 +85,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -97,8 +116,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
...row,
|
||||
messageId: row.messageId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
isStreaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -25,6 +25,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -35,6 +37,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
${row.providerName},
|
||||
${row.providerSessionId},
|
||||
${row.providerThreadId},
|
||||
${row.approvalPolicy},
|
||||
${row.sandboxMode},
|
||||
${row.activeTurnId},
|
||||
${row.lastError},
|
||||
${row.updatedAt}
|
||||
@@ -45,6 +49,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
provider_name = excluded.provider_name,
|
||||
provider_session_id = excluded.provider_session_id,
|
||||
provider_thread_id = excluded.provider_thread_id,
|
||||
approval_policy = excluded.approval_policy,
|
||||
sandbox_mode = excluded.sandbox_mode,
|
||||
active_turn_id = excluded.active_turn_id,
|
||||
last_error = excluded.last_error,
|
||||
updated_at = excluded.updated_at
|
||||
@@ -62,6 +68,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
|
||||
@@ -17,6 +17,8 @@ import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
|
||||
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
||||
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -34,6 +36,8 @@ const loader = Migrator.fromRecord({
|
||||
"3_CheckpointDiffBlobs": Migration0003,
|
||||
"4_ProviderSessionRuntime": Migration0004,
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
const DEFAULT_APPROVAL_POLICY = "never";
|
||||
const DEFAULT_SANDBOX_MODE = "workspace-write";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
|
||||
WHERE approval_policy IS NULL
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
|
||||
WHERE sandbox_mode IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_messages
|
||||
ADD COLUMN attachments_json TEXT
|
||||
`;
|
||||
});
|
||||
@@ -4,23 +4,27 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as SqliteClient from "./NodeSqliteClient.ts";
|
||||
|
||||
it.effect("runs prepared queries and returns positional values", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const layer = it.layer(SqliteClient.layerMemory());
|
||||
|
||||
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
||||
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
||||
layer("NodeSqliteClient", (it) => {
|
||||
it.effect("runs prepared queries and returns positional values", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
||||
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
||||
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
||||
|
||||
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
||||
SELECT id, name FROM entries ORDER BY id
|
||||
`;
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0]?.name, "alpha");
|
||||
assert.equal(rows[1]?.name, "beta");
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0]?.name, "alpha");
|
||||
assert.equal(rows[1]?.name, "beta");
|
||||
|
||||
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
||||
assert.equal(values.length, 2);
|
||||
assert.equal(values[0]?.[1], "alpha");
|
||||
assert.equal(values[1]?.[1], "beta");
|
||||
}).pipe(Effect.provide(SqliteClient.layerMemory())),
|
||||
);
|
||||
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
||||
assert.equal(values.length, 2);
|
||||
assert.equal(values[0]?.[1], "alpha");
|
||||
assert.equal(values[1]?.[1], "beta");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module ProjectionThreadMessageRepository
|
||||
*/
|
||||
import {
|
||||
ChatAttachment,
|
||||
OrchestrationMessageRole,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
@@ -24,6 +25,7 @@ export const ProjectionThreadMessage = Schema.Struct({
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
role: OrchestrationMessageRole,
|
||||
text: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||
isStreaming: Schema.Boolean,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
OrchestrationSessionStatus,
|
||||
ProviderApprovalPolicy,
|
||||
ProviderSandboxMode,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
@@ -25,6 +27,8 @@ export const ProjectionThreadSession = Schema.Struct({
|
||||
providerName: Schema.NullOr(Schema.String),
|
||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
approvalPolicy: ProviderApprovalPolicy,
|
||||
sandboxMode: ProviderSandboxMode,
|
||||
activeTurnId: Schema.NullOr(TurnId),
|
||||
lastError: Schema.NullOr(Schema.String),
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
interface HttpResponse {
|
||||
statusCode: number;
|
||||
contentType: string | null;
|
||||
body: string;
|
||||
}
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function withRouteServer(
|
||||
run: (baseUrl: string) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const address = server.address();
|
||||
if (typeof address !== "object" || address === null) {
|
||||
throw new Error("Expected server address to be an object");
|
||||
}
|
||||
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
try {
|
||||
await run(baseUrl);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
|
||||
const response = await fetch(`${baseUrl}${pathname}`);
|
||||
return {
|
||||
statusCode: response.status,
|
||||
contentType: response.headers.get("content-type"),
|
||||
body: await response.text(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("tryHandleProjectFaviconRequest", () => {
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns 400 when cwd is missing", async () => {
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const response = await request(baseUrl, "/api/project-favicon");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toBe("Missing cwd parameter");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a well-known favicon file from the project root", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-root-");
|
||||
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>favicon</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon href from source files when no well-known favicon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-source-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
|
||||
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon link when href appears before rel in HTML", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
|
||||
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-html-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves object-style icon metadata when href appears before rel", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "src", "root.tsx"),
|
||||
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
|
||||
"utf8",
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
"image/svg+xml": ".svg",
|
||||
"image/bmp": ".bmp",
|
||||
"image/tiff": ".tiff",
|
||||
"image/heic": ".heic",
|
||||
};
|
||||
|
||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".webp",
|
||||
".bmp",
|
||||
".tiff",
|
||||
".svg",
|
||||
".ico",
|
||||
]);
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
};
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
];
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
];
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconHref(projectCwd: string, href: string): string[] {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
}
|
||||
|
||||
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Read error");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("Missing cwd parameter");
|
||||
return true;
|
||||
}
|
||||
|
||||
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
||||
if (index >= paths.length) {
|
||||
onExhausted();
|
||||
return;
|
||||
}
|
||||
const candidate = paths[index]!;
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("No favicon found");
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
fs.readFile(sourceFile, "utf8", (err, content) => {
|
||||
if (err) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const href = extractIconHref(content);
|
||||
if (!href) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const candidates = resolveIconHref(projectCwd, href);
|
||||
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
||||
});
|
||||
};
|
||||
|
||||
const tryCandidates = (index: number): void => {
|
||||
if (index >= FAVICON_CANDIDATES.length) {
|
||||
trySourceFiles(0);
|
||||
return;
|
||||
}
|
||||
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
tryCandidates(0);
|
||||
return true;
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
@@ -377,6 +378,7 @@ it.effect(
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: startedSession.threadId,
|
||||
},
|
||||
],
|
||||
@@ -464,6 +466,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
@@ -474,6 +477,38 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
sessionId: initial.sessionId,
|
||||
input: "resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops all sessions and clears adapter runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -564,7 +599,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
};
|
||||
@@ -612,7 +647,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
@@ -624,7 +659,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
delta: "hello",
|
||||
},
|
||||
@@ -634,7 +669,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
},
|
||||
|
||||
@@ -93,6 +93,18 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderSessionBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
|
||||
if (typeof rawCwd !== "string") return undefined;
|
||||
const trimmed = rawCwd.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const canonicalEventLogger =
|
||||
@@ -266,8 +278,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
return Layer.mergeAll(
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -223,5 +224,5 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)));
|
||||
}));
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
|
||||
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
@@ -35,7 +36,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
unknown,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
@@ -60,16 +61,16 @@ export function makeServerRuntimeServicesLayer() {
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
checkpointStoreLayer,
|
||||
CheckpointStoreLive,
|
||||
checkpointDiffQueryLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
|
||||
@@ -394,6 +394,21 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("ignores trailing writes after terminal exit", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitExit({ exitCode: 0, signal: 0 });
|
||||
|
||||
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
|
||||
expect(process.writes).toEqual([]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits subprocess activity events when child-process state changes", async () => {
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager } = makeManager(5, {
|
||||
|
||||
@@ -438,6 +438,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
const input = decodeTerminalWriteInput(raw);
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
if (!session.process || session.status !== "running") {
|
||||
if (session.status === "exited") {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||
);
|
||||
|
||||
@@ -3,7 +3,8 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -38,14 +39,15 @@ import type {
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||
import { SqlClient } from "effect/unstable/sql";
|
||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -295,6 +297,36 @@ async function waitForPush(
|
||||
return take(maxMessages);
|
||||
}
|
||||
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
||||
for (const binding of bindings) {
|
||||
@@ -323,14 +355,18 @@ describe("WebSocket Server", () => {
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>;
|
||||
persistenceLayer?: Layer.Layer<
|
||||
SqlClient.SqlClient,
|
||||
SqlError.SqlError | MigrationError | PlatformError.PlatformError
|
||||
>;
|
||||
cwd?: string;
|
||||
autoBootstrapProjectFromCwd?: boolean;
|
||||
logWebSocketEvents?: boolean;
|
||||
devUrl?: string;
|
||||
authToken?: string;
|
||||
stateDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, unknown>;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
||||
@@ -353,7 +389,7 @@ describe("WebSocket Server", () => {
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
stateDir,
|
||||
staticDir: undefined,
|
||||
staticDir: options.staticDir,
|
||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||
noBrowser: true,
|
||||
authToken: options.authToken,
|
||||
@@ -437,6 +473,80 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("serves persisted attachments from stateDir", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-");
|
||||
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("image/png");
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
expect(bytes).toEqual(Buffer.from("hello-attachment"));
|
||||
});
|
||||
|
||||
it("serves persisted attachments for URL-encoded paths", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||
const attachmentPath = path.join(
|
||||
stateDir,
|
||||
"attachments",
|
||||
"thread%20folder",
|
||||
"message%20folder",
|
||||
"file%20name.png",
|
||||
);
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`,
|
||||
);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("image/png");
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
expect(bytes).toEqual(Buffer.from("hello-encoded-attachment"));
|
||||
});
|
||||
|
||||
it("serves static index for root path", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-root-");
|
||||
const staticDir = makeTempDir("t3code-static-root-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toContain("static-root");
|
||||
});
|
||||
|
||||
it("rejects static path traversal attempts", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-traversal-");
|
||||
const staticDir = makeTempDir("t3code-static-traversal-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const response = await requestPath(port, "/..%2f..%2fetc/passwd");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toBe("Invalid static file path");
|
||||
});
|
||||
|
||||
it("bootstraps the cwd project on startup when enabled", async () => {
|
||||
server = await createTestServer({
|
||||
cwd: "/test/bootstrap-workspace",
|
||||
@@ -448,23 +558,117 @@ describe("WebSocket Server", () => {
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws); // welcome
|
||||
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
|
||||
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
expect(welcome.data).toEqual(
|
||||
expect.objectContaining({
|
||||
cwd: "/test/bootstrap-workspace",
|
||||
projectName: "bootstrap-workspace",
|
||||
bootstrapProjectId: expect.any(String),
|
||||
bootstrapThreadId: expect.any(String),
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
||||
expect(snapshotResponse.error).toBeUndefined();
|
||||
const snapshot = snapshotResponse.result as {
|
||||
projects: Array<{ workspaceRoot: string; title: string; defaultModel: string | null }>;
|
||||
projects: Array<{
|
||||
id: string;
|
||||
workspaceRoot: string;
|
||||
title: string;
|
||||
defaultModel: string | null;
|
||||
}>;
|
||||
threads: Array<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}>;
|
||||
};
|
||||
const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId;
|
||||
const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId;
|
||||
expect(bootstrapProjectId).toBeDefined();
|
||||
expect(bootstrapThreadId).toBeDefined();
|
||||
|
||||
expect(snapshot.projects).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: bootstrapProjectId,
|
||||
workspaceRoot: "/test/bootstrap-workspace",
|
||||
title: "bootstrap-workspace",
|
||||
defaultModel: "gpt-5-codex",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(snapshot.threads).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: bootstrapThreadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const cwd = "/test/bootstrap-existing";
|
||||
|
||||
server = await createTestServer({
|
||||
cwd,
|
||||
stateDir,
|
||||
persistenceLayer,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
});
|
||||
let addr = server.address();
|
||||
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const firstWs = await connectWs(port);
|
||||
connections.push(firstWs);
|
||||
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
|
||||
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
|
||||
.bootstrapProjectId;
|
||||
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
|
||||
.bootstrapThreadId;
|
||||
expect(firstBootstrapProjectId).toBeDefined();
|
||||
expect(firstBootstrapThreadId).toBeDefined();
|
||||
|
||||
firstWs.close();
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
|
||||
server = await createTestServer({
|
||||
cwd,
|
||||
stateDir,
|
||||
persistenceLayer,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
});
|
||||
addr = server.address();
|
||||
port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const secondWs = await connectWs(port);
|
||||
connections.push(secondWs);
|
||||
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
|
||||
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
expect(secondWelcome.data).toEqual(
|
||||
expect.objectContaining({
|
||||
cwd,
|
||||
projectName: "bootstrap-existing",
|
||||
bootstrapProjectId: firstBootstrapProjectId,
|
||||
bootstrapThreadId: firstBootstrapThreadId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs outbound websocket push events in dev mode", async () => {
|
||||
@@ -959,6 +1163,9 @@ describe("WebSocket Server", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt,
|
||||
});
|
||||
expect(startTurnResponse.error).toBeUndefined();
|
||||
@@ -1314,7 +1521,7 @@ describe("WebSocket Server", () => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||
|
||||
+246
-89
@@ -6,16 +6,16 @@
|
||||
*
|
||||
* @module Server
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
CommandId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TerminalEvent,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
@@ -24,7 +24,20 @@ import {
|
||||
WsResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
|
||||
import {
|
||||
Cause,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
Struct,
|
||||
} from "effect";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
@@ -41,21 +54,7 @@ import { clamp } from "effect/Number";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
".woff": "font/woff",
|
||||
".woff2": "font/woff2",
|
||||
".ttf": "font/ttf",
|
||||
".map": "application/json",
|
||||
};
|
||||
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -66,14 +65,14 @@ export interface ServerShape {
|
||||
*/
|
||||
readonly start: Effect.Effect<
|
||||
http.Server,
|
||||
unknown,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>;
|
||||
|
||||
/**
|
||||
* Wait for process shutdown signals.
|
||||
*/
|
||||
readonly stopSignal: Effect.Effect<unknown, never>;
|
||||
readonly stopSignal: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,8 +164,8 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
|
||||
|
||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
http.Server,
|
||||
unknown, // TODO: This should not be unknown
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||
ServerLifecycleError,
|
||||
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const {
|
||||
@@ -185,6 +184,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -231,57 +232,157 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
res.writeHead(302, { Location: devUrl.href });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
res.writeHead(503, { "Content-Type": "text/plain" });
|
||||
res.end("No static directory configured and no dev URL set.");
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
let filePath = path.join(staticDir, url.pathname);
|
||||
|
||||
// SPA fallback: if no file extension and not found, serve index.html
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.join(filePath, "index.html");
|
||||
}
|
||||
|
||||
fs.stat(filePath, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
// SPA fallback
|
||||
const indexPath = path.join(staticDir, "index.html");
|
||||
fs.readFile(indexPath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(data);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const fileExt = path.extname(filePath);
|
||||
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
|
||||
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
void Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": contentType });
|
||||
res.end(data);
|
||||
});
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const attachmentsRoot = path.resolve(path.join(serverConfig.stateDir, "attachments"));
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
|
||||
if (
|
||||
normalizedRelativePath.length === 0 ||
|
||||
normalizedRelativePath.startsWith("..") ||
|
||||
normalizedRelativePath.includes("\0")
|
||||
) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
});
|
||||
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (!res.destroyed) {
|
||||
res.write(chunk);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.exit);
|
||||
if (streamExit._tag === "Failure") {
|
||||
if (!res.destroyed) {
|
||||
res.destroy();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
respond(302, { Location: devUrl.href });
|
||||
return;
|
||||
}
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
respond(
|
||||
503,
|
||||
{ "Content-Type": "text/plain" },
|
||||
"No static directory configured and no dev URL set.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const staticRoot = path.resolve(staticDir);
|
||||
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||
if (
|
||||
staticRelativePath.length === 0 ||
|
||||
hasRawLeadingParentSegment ||
|
||||
hasPathTraversalSegment ||
|
||||
staticRelativePath.includes("\0")
|
||||
) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const isWithinStaticRoot = (candidate: string) =>
|
||||
candidate === staticRoot ||
|
||||
candidate.startsWith(
|
||||
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
|
||||
);
|
||||
|
||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.resolve(filePath, "index.html");
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!indexData) {
|
||||
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
return;
|
||||
}
|
||||
respond(200, { "Content-Type": contentType }, data);
|
||||
}),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -337,22 +438,65 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
||||
|
||||
let welcomeBootstrapProjectId: ProjectId | undefined;
|
||||
let welcomeBootstrapThreadId: ThreadId | undefined;
|
||||
|
||||
if (autoBootstrapProjectFromCwd) {
|
||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
|
||||
if (!existing) {
|
||||
const createdAt = new Date().toISOString();
|
||||
const projectName = path.basename(cwd) || "project";
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
|
||||
title: projectName,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
yield* Effect.gen(function* () {
|
||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
||||
);
|
||||
let bootstrapProjectId: ProjectId;
|
||||
let bootstrapProjectDefaultModel: string;
|
||||
|
||||
if (!existingProject) {
|
||||
const createdAt = new Date().toISOString();
|
||||
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
||||
bootstrapProjectDefaultModel = "gpt-5-codex";
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: bootstrapProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: bootstrapProjectDefaultModel,
|
||||
createdAt,
|
||||
});
|
||||
} else {
|
||||
bootstrapProjectId = existingProject.id;
|
||||
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
|
||||
}
|
||||
|
||||
const existingThread = snapshot.threads.find(
|
||||
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
|
||||
);
|
||||
if (!existingThread) {
|
||||
const createdAt = new Date().toISOString();
|
||||
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
threadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: bootstrapProjectDefaultModel,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||
welcomeBootstrapThreadId = threadId;
|
||||
} else {
|
||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||
welcomeBootstrapThreadId = existingThread.id;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
||||
@@ -389,7 +533,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.projectsSearchEntries: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.promise(() => searchWorkspaceEntries(body));
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => searchWorkspaceEntries(body),
|
||||
catch: (cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
@@ -569,7 +719,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const welcome: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: { cwd, projectName },
|
||||
data: {
|
||||
cwd,
|
||||
projectName,
|
||||
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
|
||||
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
|
||||
},
|
||||
};
|
||||
logOutgoingPush(welcome, 1);
|
||||
ws.send(JSON.stringify(welcome));
|
||||
@@ -612,7 +767,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions);
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.all([
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
"importFromBarrel": "error",
|
||||
"anyUnknownInErrorContext": "warning",
|
||||
"instanceOfSchema": "warning",
|
||||
"deterministicKeys": "warning"
|
||||
"deterministicKeys": "warning",
|
||||
"preferSchemaOverJson": "off",
|
||||
"globalErrorInEffectFailure": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -22,12 +22,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
@@ -11,8 +15,19 @@ const AppSettingsSchema = Schema.Struct({
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
|
||||
@@ -20,6 +35,76 @@ let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
): AppSettings["customCodexModels"] {
|
||||
const normalizedModels: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const candidate of models) {
|
||||
const normalized = normalizeModelSlug(candidate);
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||
seen.has(normalized)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(normalized);
|
||||
normalizedModels.push(normalized);
|
||||
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(slug);
|
||||
options.push({
|
||||
slug,
|
||||
name: slug,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
@@ -32,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
||||
}
|
||||
|
||||
try {
|
||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
@@ -93,10 +178,12 @@ export function useAppSettings() {
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -1,18 +1,207 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||
const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
return match?.[1] ?? "text";
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.map((child) => nodeToPlainText(child)).join("");
|
||||
}
|
||||
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||
return nodeToPlainText(node.props.children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractCodeBlock(
|
||||
children: ReactNode,
|
||||
): { className: string | undefined; code: string } | null {
|
||||
const childNodes = Children.toArray(children);
|
||||
if (childNodes.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
code: nodeToPlainText(onlyChild.props.children),
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(code)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [code]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd],
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,16 +7,75 @@ import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "luci
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark" | "system";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
|
||||
const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-diffs-header],
|
||||
[data-diff],
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
var(--background) 80%,
|
||||
var(--destructive)
|
||||
);
|
||||
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
[data-title] {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 120ms ease,
|
||||
text-decoration-color 120ms ease;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
[data-title]:hover {
|
||||
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
@@ -102,6 +161,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -222,6 +283,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const openDiffFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
@@ -421,7 +494,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
@@ -445,7 +518,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={patchViewportRef}
|
||||
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||
>
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
@@ -463,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto p-2 "
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -472,14 +548,31 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
{renderableFiles.map((fileDiff) => {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
return node.hasAttribute("data-title");
|
||||
});
|
||||
if (!clickedHeader) return;
|
||||
openDiffFileInEditor(filePath);
|
||||
}}
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -487,7 +580,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
|
||||
@@ -1,8 +1,36 @@
|
||||
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
if (!workerPool) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = workerPool.getDiffRenderOptions();
|
||||
if (current.theme === themeName) {
|
||||
return;
|
||||
}
|
||||
|
||||
void workerPool
|
||||
.setRenderOptions({
|
||||
...current,
|
||||
theme: themeName,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [themeName, workerPool]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores =
|
||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
@@ -17,9 +45,11 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
theme: diffThemeName,
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
}}
|
||||
>
|
||||
<DiffWorkerThemeSync themeName={diffThemeName} />
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
|
||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -29,12 +29,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -45,12 +46,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -147,12 +149,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
aheadCount: 3,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -164,12 +167,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
aheadCount: 2,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -204,7 +208,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -246,14 +250,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -290,7 +294,7 @@ describe("when: branch is behind upstream", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR", () => {
|
||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -346,12 +350,13 @@ describe("when: working tree has local changes", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasWorkingTreeChanges: true,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -411,7 +416,7 @@ describe("when: on default branch without open PR", () => {
|
||||
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -511,7 +516,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -526,12 +531,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -548,12 +554,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -568,7 +575,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
|
||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
|
||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
@@ -33,6 +33,7 @@ import { toastManager } from "~/components/ui/toast";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitInitMutationOptions,
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
gitStatusQueryOptions,
|
||||
@@ -57,7 +58,7 @@ function getMenuActionDisabledReason(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
|
||||
@@ -168,7 +169,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
const branchName = gitStatusForActions?.branch;
|
||||
if (!branchName) return false;
|
||||
@@ -215,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
return;
|
||||
}
|
||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
||||
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -232,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
@@ -291,7 +295,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
||||
const existingOpenPrUrl =
|
||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||
@@ -361,7 +367,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.openPr?.url,
|
||||
gitStatusForActions?.pr,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
@@ -15,7 +16,8 @@ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { toastManager } from "./ui/toast";
|
||||
@@ -50,7 +52,7 @@ function formatRelativeTime(iso: string): string {
|
||||
}
|
||||
|
||||
interface ThreadStatusPill {
|
||||
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
|
||||
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
|
||||
colorClass: string;
|
||||
dotClass: string;
|
||||
pulse: boolean;
|
||||
@@ -62,9 +64,16 @@ interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
}
|
||||
|
||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurnCompletedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(completedAt)) return false;
|
||||
if (!thread.lastVisitedAt) return true;
|
||||
|
||||
@@ -76,7 +85,7 @@ function hasUnseenCompletion(thread: Thread): boolean {
|
||||
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
||||
if (hasPendingApprovals) {
|
||||
return {
|
||||
label: "Awaiting response",
|
||||
label: "Pending Approval",
|
||||
colorClass: "text-amber-600 dark:text-amber-300/90",
|
||||
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
||||
pulse: false,
|
||||
@@ -124,6 +133,28 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
||||
if (prState === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
};
|
||||
}
|
||||
if (prState === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
};
|
||||
}
|
||||
if (prState === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
@@ -140,6 +171,50 @@ function T3Wordmark() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the server's HTTP origin (scheme + host + port) from the same
|
||||
* sources WsTransport uses, converting ws(s) to http(s).
|
||||
*/
|
||||
function getServerHttpOrigin(): string {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsUrl =
|
||||
bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
return new URL(httpUrl).origin;
|
||||
} catch {
|
||||
return httpUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const serverHttpOrigin = getServerHttpOrigin();
|
||||
|
||||
function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
|
||||
|
||||
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
||||
|
||||
if (status === "error") {
|
||||
return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
|
||||
onLoad={() => setStatus("loaded")}
|
||||
onError={() => setStatus("error")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const navigate = useNavigate();
|
||||
@@ -158,7 +233,65 @@ export default function Sidebar() {
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
const pendingApprovalByThreadId = useMemo(() => new Map<ThreadId, boolean>(), []);
|
||||
const pendingApprovalByThreadId = useMemo(() => {
|
||||
const map = new Map<ThreadId, boolean>();
|
||||
for (const thread of state.threads) {
|
||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
state.threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
queries: threadGitStatusCwds.map((cwd) => ({
|
||||
...gitStatusQueryOptions(cwd),
|
||||
staleTime: 30_000,
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prStateByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
if (!cwd) continue;
|
||||
const status = threadGitStatusQueries[index]?.data;
|
||||
if (status) {
|
||||
statusByCwd.set(cwd, status);
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPrState>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
@@ -281,7 +414,17 @@ export default function Sidebar() {
|
||||
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);
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "delete", label: "Delete" },
|
||||
],
|
||||
position,
|
||||
);
|
||||
if (clicked === "mark-unread") {
|
||||
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
|
||||
const thread = state.threads.find((t) => t.id === threadId);
|
||||
@@ -380,6 +523,7 @@ export default function Sidebar() {
|
||||
},
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
@@ -555,6 +699,7 @@ export default function Sidebar() {
|
||||
project.expanded ? "rotate-90" : ""
|
||||
}`}
|
||||
/>
|
||||
<ProjectFavicon cwd={project.cwd} />
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
@@ -569,6 +714,7 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
|
||||
return (
|
||||
@@ -614,6 +760,16 @@ export default function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{prStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={prStatus.label}
|
||||
title={prStatus.label}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
|
||||
@@ -112,6 +112,7 @@ interface TerminalViewportProps {
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
onSessionExited: () => void;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -123,6 +124,7 @@ function TerminalViewport({
|
||||
terminalId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -131,6 +133,12 @@ function TerminalViewport({
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const onSessionExitedRef = useRef(onSessionExited);
|
||||
const hasHandledExitRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
onSessionExitedRef.current = onSessionExited;
|
||||
}, [onSessionExited]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
@@ -306,6 +314,7 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
hasHandledExitRef.current = false;
|
||||
activeTerminal.write("\u001bc");
|
||||
if (event.snapshot.history.length > 0) {
|
||||
activeTerminal.write(event.snapshot.history);
|
||||
@@ -335,6 +344,16 @@ function TerminalViewport({
|
||||
activeTerminal,
|
||||
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
||||
);
|
||||
if (hasHandledExitRef.current) {
|
||||
return;
|
||||
}
|
||||
hasHandledExitRef.current = true;
|
||||
window.setTimeout(() => {
|
||||
if (!hasHandledExitRef.current) {
|
||||
return;
|
||||
}
|
||||
onSessionExitedRef.current();
|
||||
}, 0);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -783,6 +802,7 @@ export default function ThreadTerminalDrawer({
|
||||
terminalId={terminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -800,6 +820,7 @@ export default function ThreadTerminalDrawer({
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
|
||||
@@ -24,7 +24,6 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
|
||||
|
||||
type SidebarContextProps = {
|
||||
@@ -129,19 +128,6 @@ function SidebarProvider({
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||
}, [isMobile, setOpen]);
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
toggleSidebar();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [toggleSidebar]);
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
@@ -41,8 +41,10 @@ export function showContextMenuFallback<T extends string>(
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.textContent = item.label;
|
||||
btn.className =
|
||||
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default";
|
||||
const isDeleteAction = item.id === "delete";
|
||||
btn.className = isDeleteAction
|
||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
||||
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
||||
btn.addEventListener("click", () => cleanup(item.id));
|
||||
menu.appendChild(btn);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
systemDark: boolean;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
@@ -39,8 +44,16 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
// Apply immediately on module load to prevent flash
|
||||
applyTheme(getStored());
|
||||
|
||||
function getSnapshot(): Theme {
|
||||
return getStored();
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
const theme = getStored();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
lastSnapshot = { theme, systemDark };
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
@@ -71,10 +84,11 @@ function subscribe(listener: () => void): () => void {
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const theme = useSyncExternalStore(subscribe, getSnapshot);
|
||||
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
||||
const theme = snapshot.theme;
|
||||
|
||||
const resolvedTheme: "light" | "dark" =
|
||||
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
|
||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
}
|
||||
|
||||
.diff-render-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.5rem;
|
||||
overflow: clip;
|
||||
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
formatShortcutLabel,
|
||||
isChatNewShortcut,
|
||||
isChatNewLocalShortcut,
|
||||
isDiffToggleShortcut,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalClearShortcut,
|
||||
isTerminalCloseShortcut,
|
||||
@@ -91,6 +92,11 @@ const DEFAULT_BINDINGS = compile([
|
||||
command: "terminal.close",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("d"),
|
||||
command: "diff.toggle",
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
@@ -230,6 +236,7 @@ describe("shortcutLabelForCommand", () => {
|
||||
|
||||
it("returns labels for non-terminal commands", () => {
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
||||
"Ctrl+O",
|
||||
@@ -276,6 +283,21 @@ describe("chat/editor shortcuts", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches diff.toggle shortcut outside terminal focus", () => {
|
||||
assert.isTrue(
|
||||
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-command precedence", () => {
|
||||
|
||||
@@ -198,6 +198,14 @@ export function isTerminalCloseShortcut(
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
|
||||
}
|
||||
|
||||
export function isDiffToggleShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
|
||||
}
|
||||
|
||||
export function isChatNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
} as const;
|
||||
|
||||
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||
|
||||
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||
}
|
||||
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
export function fnv1a32(
|
||||
input: string,
|
||||
seed = FNV_OFFSET_BASIS_32,
|
||||
multiplier = FNV_PRIME_32,
|
||||
): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
} from "./gitReactQuery";
|
||||
|
||||
describe("gitMutationKeys", () => {
|
||||
it("scopes stacked action keys by cwd", () => {
|
||||
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
|
||||
gitMutationKeys.runStackedAction("/repo/b"),
|
||||
);
|
||||
});
|
||||
|
||||
it("scopes pull keys by cwd", () => {
|
||||
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("git mutation options", () => {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
it("attaches cwd-scoped mutation key for runStackedAction", () => {
|
||||
const options = gitRunStackedActionMutationOptions({ cwd: "/repo/a", queryClient });
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
||||
});
|
||||
|
||||
it("attaches cwd-scoped mutation key for pull", () => {
|
||||
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { GitStackedAction } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "~/nativeApi";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
@@ -13,6 +13,15 @@ export const gitQueryKeys = {
|
||||
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
||||
};
|
||||
|
||||
export const gitMutationKeys = {
|
||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
||||
createBranchAndCheckout: (cwd: string | null) =>
|
||||
["git", "mutation", "create-branch-and-checkout", cwd] as const,
|
||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
||||
};
|
||||
|
||||
export function invalidateGitQueries(queryClient: QueryClient) {
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
||||
}
|
||||
@@ -51,6 +60,7 @@ export function gitBranchesQueryOptions(cwd: string | null) {
|
||||
|
||||
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.init(input.cwd),
|
||||
mutationFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git init is unavailable.");
|
||||
@@ -67,6 +77,7 @@ export function gitCheckoutMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.checkout(input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git checkout is unavailable.");
|
||||
@@ -83,6 +94,7 @@ export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
||||
@@ -100,6 +112,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
mutationFn: async ({
|
||||
action,
|
||||
commitMessage,
|
||||
@@ -123,6 +136,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
|
||||
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.pull(input.cwd),
|
||||
mutationFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git pull is unavailable.");
|
||||
@@ -151,6 +165,7 @@ export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClie
|
||||
if (!cwd) throw new Error("Git worktree creation is unavailable.");
|
||||
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
|
||||
},
|
||||
mutationKey: ["git", "mutation", "create-worktree"] as const,
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
@@ -164,6 +179,7 @@ export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClie
|
||||
if (!cwd) throw new Error("Git worktree removal is unavailable.");
|
||||
return api.git.removeWorktree({ cwd, path, force });
|
||||
},
|
||||
mutationKey: ["git", "mutation", "remove-worktree"] as const,
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LRUCache } from "./lruCache";
|
||||
|
||||
describe("LRUCache", () => {
|
||||
it("returns null for missing keys", () => {
|
||||
const cache = new LRUCache<string>(2, 100);
|
||||
expect(cache.get("missing")).toBeNull();
|
||||
});
|
||||
|
||||
it("evicts oldest by max entries", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("promotes on get and evicts least recently used", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
|
||||
cache.set("c", "C", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("b")).toBeNull();
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("evicts by memory budget", () => {
|
||||
const cache = new LRUCache<string>(10, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface CacheEntry<T> {
|
||||
value: T;
|
||||
approximateSize: number;
|
||||
}
|
||||
|
||||
export class LRUCache<T> {
|
||||
private cache = new Map<string, CacheEntry<T>>();
|
||||
private totalSize = 0;
|
||||
|
||||
constructor(
|
||||
private readonly maxEntries: number,
|
||||
private readonly maxMemoryBytes: number,
|
||||
) {}
|
||||
|
||||
get(key: string): T | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.promote(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T, approximateSize: number): void {
|
||||
const existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
this.totalSize -= existing.approximateSize;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
|
||||
private promote(key: string, entry: CacheEntry<T>): void {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
private evictIfNeeded(incomingSize: number): void {
|
||||
while (
|
||||
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const oldestEntry = this.cache.get(oldestKey);
|
||||
if (oldestEntry) {
|
||||
this.totalSize -= oldestEntry.approximateSize;
|
||||
}
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
type ErrorComponentProps,
|
||||
useNavigate,
|
||||
useRouterState,
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -13,6 +16,7 @@ import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQue
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
|
||||
@@ -121,7 +125,12 @@ function errorDetails(error: unknown): string {
|
||||
function EventRouter() {
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
||||
const pathnameRef = useRef(pathname);
|
||||
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
pathnameRef.current = pathname;
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
@@ -170,8 +179,47 @@ function EventRouter() {
|
||||
}
|
||||
void syncSnapshot();
|
||||
});
|
||||
const unsubWelcome = onServerWelcome(() => {
|
||||
void syncSnapshot();
|
||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
await syncSnapshot();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_PROJECT_EXPANDED",
|
||||
projectId: payload.bootstrapProjectId,
|
||||
expanded: true,
|
||||
});
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
}
|
||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: payload.bootstrapThreadId },
|
||||
replace: true,
|
||||
});
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
})().catch(() => undefined);
|
||||
});
|
||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||
const signature = JSON.stringify(payload.issues);
|
||||
@@ -218,10 +266,11 @@ function EventRouter() {
|
||||
return () => {
|
||||
disposed = true;
|
||||
unsubDomainEvent();
|
||||
unsubTerminalEvent();
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [dispatch, queryClient]);
|
||||
}, [dispatch, navigate, queryClient]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ function ChatThreadRouteView() {
|
||||
if (!shouldUseDiffSheet) {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||
@@ -189,7 +189,7 @@ function ChatThreadRouteView() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -52,9 +53,12 @@ function SettingsRouteView() {
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [customModelInput, setCustomModelInput] = useState("");
|
||||
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const customCodexModels = settings.customCodexModels;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
@@ -74,6 +78,42 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [keybindingsConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(() => {
|
||||
const normalized = normalizeModelSlug(customModelInput);
|
||||
if (!normalized) {
|
||||
setCustomModelError("Enter a model slug.");
|
||||
return;
|
||||
}
|
||||
if (MODEL_OPTIONS.some((option) => option.slug === normalized)) {
|
||||
setCustomModelError("That model is already built in.");
|
||||
return;
|
||||
}
|
||||
if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
|
||||
setCustomModelError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
|
||||
return;
|
||||
}
|
||||
if (customCodexModels.includes(normalized)) {
|
||||
setCustomModelError("That custom model is already saved.");
|
||||
return;
|
||||
}
|
||||
|
||||
updateSettings({
|
||||
customCodexModels: [...customCodexModels, normalized],
|
||||
});
|
||||
setCustomModelInput("");
|
||||
setCustomModelError(null);
|
||||
}, [customCodexModels, customModelInput, updateSettings]);
|
||||
|
||||
const removeCustomModel = useCallback(
|
||||
(slug: string) => {
|
||||
updateSettings({
|
||||
customCodexModels: customCodexModels.filter((model) => model !== slug),
|
||||
});
|
||||
setCustomModelError(null);
|
||||
},
|
||||
[customCodexModels, updateSettings],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
@@ -193,6 +233,96 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Models</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Save additional Codex model slugs so they appear in the chat model picker.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
if (customModelError) {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Example: <code>gpt-6.7-codex-ultra-preview</code>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<p>Saved custom models: {customCodexModels.length}</p>
|
||||
{customCodexModels.length > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
customCodexModels: defaults.customCodexModels,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reset custom models
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{customCodexModels.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{customCodexModels.map((slug) => (
|
||||
<div
|
||||
key={slug}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
|
||||
>
|
||||
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
|
||||
{slug}
|
||||
</code>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => removeCustomModel(slug)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border bg-background px-3 py-4 text-xs text-muted-foreground">
|
||||
No custom models saved yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||
@@ -237,6 +367,49 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Responses</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Control how assistant output is rendered during a turn.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">Stream assistant messages</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Show token-by-token output while a response is in progress.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.enableAssistantStreaming}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
enableAssistantStreaming: Boolean(checked),
|
||||
})
|
||||
}
|
||||
aria-label="Stream assistant messages"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{settings.enableAssistantStreaming !== defaults.enableAssistantStreaming ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
enableAssistantStreaming: defaults.enableAssistantStreaming,
|
||||
})
|
||||
}
|
||||
>
|
||||
Restore default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Keybindings</h2>
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { derivePendingApprovals, deriveWorkLogEntries } from "./session-logic";
|
||||
import {
|
||||
derivePendingApprovals,
|
||||
deriveWorkLogEntries,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
} from "./session-logic";
|
||||
|
||||
function makeActivity(overrides: {
|
||||
id?: string;
|
||||
@@ -126,3 +131,72 @@ describe("deriveWorkLogEntries", () => {
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasToolActivityForTurn", () => {
|
||||
it("returns false when turn id is missing", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
|
||||
expect(hasToolActivityForTurn(activities, null)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true only for matching tool activity in the target turn", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
|
||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-2"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isLatestTurnSettled", () => {
|
||||
const latestTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
} as const;
|
||||
|
||||
it("returns false while the same turn is still active in a running session", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(latestTurn, {
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(latestTurn, {
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-2"),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true once the session is no longer running that turn", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(latestTurn, {
|
||||
orchestrationStatus: "ready",
|
||||
activeTurnId: undefined,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when turn timestamps are incomplete", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: null,
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
},
|
||||
null,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderKind,
|
||||
type TurnId,
|
||||
@@ -75,6 +76,17 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
export function isLatestTurnSettled(
|
||||
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
|
||||
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
if (!session) return true;
|
||||
if (session.orchestrationStatus === "running") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
@@ -147,6 +159,14 @@ export function deriveWorkLogEntries(
|
||||
});
|
||||
}
|
||||
|
||||
export function hasToolActivityForTurn(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
turnId: TurnId | null | undefined,
|
||||
): boolean {
|
||||
if (!turnId) return false;
|
||||
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ChatMessage[],
|
||||
workEntries: WorkLogEntry[],
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { reducer, type AppState } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
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: "2026-02-13T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeState(thread: Thread): AppState {
|
||||
return {
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer", () => {
|
||||
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
|
||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-25T12:28:00.000Z",
|
||||
startedAt: "2026-02-25T12:28:30.000Z",
|
||||
completedAt: latestTurnCompletedAt,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
const updatedThread = next.threads[0];
|
||||
expect(updatedThread).toBeDefined();
|
||||
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
|
||||
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
|
||||
Date.parse(latestTurnCompletedAt),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not change a thread without a completed turn", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: null,
|
||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
expect(next).toEqual(initialState);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store terminal activity reducer", () => {
|
||||
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
|
||||
});
|
||||
|
||||
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
runningTerminalIds: ["alt"],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores activity events for unknown terminal ids", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "missing",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
+107
-18
@@ -33,7 +33,15 @@ import {
|
||||
type Action =
|
||||
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
||||
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
||||
| {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY";
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||
@@ -184,6 +192,43 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
||||
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:"
|
||||
? "https:"
|
||||
: wsUrl.protocol === "ws:"
|
||||
? "http:"
|
||||
: wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
if (rawUrl.startsWith("/")) {
|
||||
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||
}
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -369,6 +414,27 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
thread: Thread,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): Thread {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(terminalId)) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIds],
|
||||
});
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
@@ -385,19 +451,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
const latestTurnStartedAt =
|
||||
thread.latestTurnId === null
|
||||
? undefined
|
||||
: thread.messages.find(
|
||||
(message) => message.turnId === thread.latestTurnId && message.role === "user",
|
||||
)?.createdAt;
|
||||
const latestTurnCompletedAt = thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.turnId === thread.latestTurnId,
|
||||
)?.completedAt;
|
||||
const latestTurnDurationMs =
|
||||
latestTurnStartedAt && latestTurnCompletedAt
|
||||
? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
|
||||
: undefined;
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
id: thread.id,
|
||||
@@ -440,7 +493,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
@@ -455,10 +508,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurnId: thread.latestTurnId ?? undefined,
|
||||
latestTurnStartedAt,
|
||||
latestTurnCompletedAt,
|
||||
latestTurnDurationMs,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
@@ -504,6 +554,29 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_UNREAD": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) {
|
||||
return thread;
|
||||
}
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
||||
return thread;
|
||||
}
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) {
|
||||
return thread;
|
||||
}
|
||||
return {
|
||||
...thread,
|
||||
lastVisitedAt: unreadVisitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
@@ -512,6 +585,22 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_ACTIVITY":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_PROJECT_EXPANDED":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts";
|
||||
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
|
||||
|
||||
const snapshot: TerminalSessionSnapshot = {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
cwd: "/tmp",
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function eventBase() {
|
||||
return {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("terminalRunningSubprocessFromEvent", () => {
|
||||
it("returns the subprocess flag for terminal activity events", () => {
|
||||
const active = terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
const idle = terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(active).toBe(true);
|
||||
expect(idle).toBe(false);
|
||||
});
|
||||
|
||||
it("clears running state when a terminal session starts/restarts/exits", () => {
|
||||
const events: TerminalEvent[] = [
|
||||
{ ...eventBase(), type: "started", snapshot },
|
||||
{ ...eventBase(), type: "restarted", snapshot },
|
||||
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
|
||||
];
|
||||
|
||||
for (const event of events) {
|
||||
expect(terminalRunningSubprocessFromEvent(event)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores non-activity terminal events", () => {
|
||||
expect(
|
||||
terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "output",
|
||||
data: "hello",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "error",
|
||||
message: "oops",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TerminalEvent } from "@t3tools/contracts";
|
||||
|
||||
export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolean | null {
|
||||
switch (event.type) {
|
||||
case "activity":
|
||||
return event.hasRunningSubprocess;
|
||||
case "started":
|
||||
case "restarted":
|
||||
case "exited":
|
||||
return false;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationSessionStatus,
|
||||
OrchestrationThreadActivity,
|
||||
ProjectScript as ContractProjectScript,
|
||||
@@ -89,10 +90,7 @@ export interface Thread {
|
||||
messages: ChatMessage[];
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
latestTurnId?: TurnId | undefined;
|
||||
latestTurnStartedAt?: string | undefined;
|
||||
latestTurnCompletedAt?: string | undefined;
|
||||
latestTurnDurationMs?: number | undefined;
|
||||
latestTurn: OrchestrationLatestTurn | null;
|
||||
lastVisitedAt?: string | undefined;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
|
||||
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
activities: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
|
||||
@@ -65,16 +65,41 @@ describe("wsNativeApi", () => {
|
||||
emitPush(WS_CHANNELS.serverWelcome, payload);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(payload);
|
||||
expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||
|
||||
const lateListener = vi.fn();
|
||||
onServerWelcome(lateListener);
|
||||
|
||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||
expect(lateListener).toHaveBeenCalledWith(payload);
|
||||
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||
expect(warnSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves bootstrap ids from server.welcome payloads", async () => {
|
||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||
|
||||
createWsNativeApi();
|
||||
const listener = vi.fn();
|
||||
onServerWelcome(listener);
|
||||
|
||||
emitPush(WS_CHANNELS.serverWelcome, {
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: "project-1",
|
||||
bootstrapThreadId: "thread-1",
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
cwd: "/tmp/workspace",
|
||||
projectName: "t3-code",
|
||||
bootstrapProjectId: "project-1",
|
||||
bootstrapThreadId: "thread-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||
@@ -87,7 +112,9 @@ describe("wsNativeApi", () => {
|
||||
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith({ cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
|
||||
);
|
||||
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
|
||||
reason: "decode-failed",
|
||||
|
||||
@@ -3,7 +3,7 @@ import react from "@vitejs/plugin-react";
|
||||
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5173);
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
|
||||
@@ -71,12 +71,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
},
|
||||
@@ -863,20 +861,14 @@
|
||||
|
||||
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
|
||||
"hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
|
||||
|
||||
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
|
||||
|
||||
"highlight.js": ["[email protected]", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
|
||||
|
||||
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
@@ -983,8 +975,6 @@
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
|
||||
"lowlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="],
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
@@ -1197,8 +1187,6 @@
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
|
||||
"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
|
||||
@@ -1361,8 +1349,6 @@
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
"unist-util-find-after": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="],
|
||||
|
||||
"unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
|
||||
|
||||
"unist-util-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# ADR 0001: Provider Runtime Lifecycle Ownership
|
||||
|
||||
## Status
|
||||
Accepted
|
||||
|
||||
## Context
|
||||
Provider runtime streams can include auxiliary work (for example collab/child-agent turns) under the same provider session as a user-visible primary turn.
|
||||
|
||||
The previous orchestration ingestion and checkpoint flows keyed lifecycle updates by `providerSessionId` alone. This allowed auxiliary `turn.completed` events to:
|
||||
|
||||
- mark thread sessions as `ready` before the primary turn completed
|
||||
- clear `activeTurnId` for a still-running primary turn
|
||||
- emit checkpoint turn-diff summaries for auxiliary turns in the main thread timeline
|
||||
|
||||
## Decision
|
||||
Define and enforce a lifecycle ownership invariant:
|
||||
|
||||
- Only events in the primary thread/turn lane may mutate thread session lifecycle state (`status`, `activeTurnId`, `providerThreadId`) and checkpoint turn completion.
|
||||
- Auxiliary events may still append messages and activities.
|
||||
|
||||
Current enforcement is implemented with scope guards:
|
||||
|
||||
- Runtime ingestion only applies lifecycle transitions when the event targets the active primary scope (provider thread and active turn checks).
|
||||
- Checkpoint capture ignores `turn.completed` events from non-primary provider thread scope, and ignores non-active turn completions while a primary turn is active.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
- Prevents premature loss of "working" state from auxiliary turn completion.
|
||||
- Prevents auxiliary changed-files/checkpoint cards from appearing as if they were primary turn completion.
|
||||
- Keeps useful auxiliary activity/message visibility.
|
||||
|
||||
### Negative
|
||||
- Runtime events that omit thread/turn identifiers are treated conservatively in lifecycle transitions.
|
||||
- Full explicit lane modeling is still desirable in contracts for long-term clarity.
|
||||
|
||||
## Follow-up
|
||||
1. Add explicit runtime lane metadata (`primary` vs `auxiliary`) to canonical provider runtime events.
|
||||
2. Persist orchestration-to-provider turn binding (`TurnId` <-> `ProviderTurnId`) for stronger reconciliation and replay safety.
|
||||
3. Promote lifecycle ownership checks from heuristic guards to schema-level invariants once lane metadata is available.
|
||||
@@ -18,6 +18,8 @@ export const GitPrStepStatus = Schema.Literals([
|
||||
"opened_existing",
|
||||
"skipped_not_requested",
|
||||
]);
|
||||
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||
export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
@@ -91,6 +93,16 @@ export type GitInitInput = typeof GitInitInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
export const GitStatusPr = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
state: GitStatusPrState,
|
||||
});
|
||||
export type GitStatusPr = typeof GitStatusPr.Type;
|
||||
|
||||
export const GitStatusResult = Schema.Struct({
|
||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
hasWorkingTreeChanges: Schema.Boolean,
|
||||
@@ -108,15 +120,7 @@ export const GitStatusResult = Schema.Struct({
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
openPr: Schema.NullOr(
|
||||
Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
pr: Schema.NullOr(GitStatusPr),
|
||||
});
|
||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||
|
||||
|
||||
@@ -35,6 +35,12 @@ it.effect("parses keybinding rules", () =>
|
||||
});
|
||||
assert.strictEqual(parsedClose.command, "terminal.close");
|
||||
|
||||
const parsedDiffToggle = yield* decode(KeybindingRule, {
|
||||
key: "mod+d",
|
||||
command: "diff.toggle",
|
||||
});
|
||||
assert.strictEqual(parsedDiffToggle.command, "diff.toggle");
|
||||
|
||||
const parsedLocal = yield* decode(KeybindingRule, {
|
||||
key: "mod+shift+n",
|
||||
command: "chat.newLocal",
|
||||
|
||||
@@ -14,6 +14,7 @@ export const STATIC_KEYBINDING_COMMANDS = [
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"diff.toggle",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
|
||||
@@ -22,9 +22,14 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default for missing and unknown models", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe("gpt-4.1");
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
|
||||
@@ -5,11 +5,12 @@ export const MODEL_OPTIONS = [
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
] as const;
|
||||
|
||||
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type BuiltInModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type ModelSlug = string;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
@@ -26,16 +27,12 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
||||
return normalized ?? DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user