Compare commits

..
Author SHA1 Message Date
Julius Marminge cd7081bd88 simplify layers 2026-02-27 21:27:19 -08:00
Julius Marminge b060982d66 Flatten attachment paths with message-prefixed filenames
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
2026-02-27 21:12:01 -08:00
Julius Marminge 569b928ea6 Serve attachments using URL-encoded relative paths
- Read attachment route paths without URI decoding before normalization
- Align test fixture paths with encoded thread/message/file names
2026-02-27 21:07:06 -08:00
Julius Marminge a4c99abec7 Overwrite attachment bytes for repeated message attachment index
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
2026-02-27 21:00:53 -08:00
Julius Marminge 87c8c4026f Preserve empty attachment updates in projection pipeline
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
2026-02-27 20:56:51 -08:00
Julius Marminge dcf556a080 dedupe 2026-02-27 20:52:38 -08:00
Julius Marminge 327ea416a0 nit 2026-02-27 20:49:28 -08:00
Julius Marminge 13c62ede8f kewl 2026-02-27 20:48:48 -08:00
Julius Marminge 93dc7313f2 fixxx 2026-02-27 20:35:31 -08:00
Julius Marminge 7b39369f27 Add gallery navigation to expanded chat image previews
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
2026-02-27 20:20:01 -08:00
Julius Marminge fc6f4ac8a9 Make attachment writes transactional and decode attachment URLs
- Stage attachment file writes until projector transactions commit, then apply write/prune/delete side effects
- Remove orphaned attachment files on thread revert and delete thread attachment dirs on thread deletion
- Serve URL-encoded attachment paths in `wsServer` and stream file responses
- Add regression tests for rollback safety, revert/delete cleanup, and encoded attachment URLs
2026-02-27 20:18:35 -08:00
Julius Marminge 9f56dd0193 Harden attachment materialization and static file path handling
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
2026-02-27 20:18:35 -08:00
Julius Marminge 6845143b9e Persist and serve projected message image attachments
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
2026-02-27 20:18:35 -08:00
Julius Marminge aa267ebb05 clamp 2026-02-27 19:27:05 -08:00
Cursor AgentandJulius Marminge 1a33f25970 web: keep active turn out of virtualization
Co-authored-by: Julius Marminge <[email protected]>
2026-02-27 19:27:05 -08:00
Julius Marminge 21c823ecdc Guard delayed terminal exit callback
- Skip `onSessionExited` if exit handling was reset before timeout runs
- Prevent stale async exit callbacks from firing in terminal drawer
2026-02-27 18:08:18 -08:00
Julius Marminge 80498f1709 Handle terminal exit writes and auto-close exited terminal view
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
2026-02-27 18:08:18 -08:00
Julius Marminge e6c5a4a4bb Handle favicon links when href precedes rel
- Update favicon regex parsing to support rel/href in either order
- Add route tests for HTML link tags and object-style metadata with href-first ordering
2026-02-27 15:21:31 -08:00
Julius Marminge 732b3abf99 match assets/{icon,logo} as well 2026-02-27 15:21:31 -08:00
Julius Marminge ffbf541ff8 Extract project favicon route and tighten turn-settled logic
- move `/api/project-favicon` handling into a dedicated server route with coverage for root and source-linked icons
- wire `wsServer` to use the new route helper
- treat any running session as unsettled in `isLatestTurnSettled` to prevent stale latest-turn banners, with test coverage
2026-02-27 15:21:31 -08:00
Julius Marminge 709f961e1c Gate latest-turn completion UI on settled turn state
- Add `isLatestTurnSettled` to avoid treating an active running turn as complete
- Use the guard in `ChatView` for visited timestamps and completion summary/divider rendering
- Add unit tests covering running, ready, and incomplete-timestamp cases
2026-02-27 15:21:31 -08:00
Theo Browne 1653383573 Remove my junk paths 2026-02-27 15:21:31 -08:00
Theo Browne c7ae6b9471 Favicons + custom port during dev 2026-02-27 15:21:31 -08:00
Julius Marminge bbcf9ba9db Show pending approvals in sidebar thread status
- derive pending approvals from thread activities and label status as "Pending Approval"
- remove `isolate` class from chat `SidebarInset` containers
2026-02-27 14:49:27 -08:00
Julius Marminge 3f81f9dcb4 Replace thread latestTurnId with structured latestTurn metadata
- add `OrchestrationLatestTurn` schema and store full turn state/timestamps/message linkage
- update server projector/snapshot queries to populate `latestTurn` from session + projection_turns
- migrate web store/components to consume `latestTurn` and adjust related tests
2026-02-27 14:10:34 -08:00
Julius Marminge b073fea5fb Handle provider turn IDs correctly in runtime ingestion
- Use `ProviderTurnId` in `CheckpointReactor` tests instead of `TurnId`
- Guard `event.turnId` access in provider runtime ingestion when the field is absent
2026-02-27 14:10:34 -08:00
Julius Marminge 834236931e Inline provider thread and turn ID schemas in runtime events
- Remove redundant runtime schema aliases for thread and turn IDs
- Use `ProviderThreadId` and `ProviderTurnId` directly across runtime event contracts
2026-02-27 14:10:34 -08:00
Julius Marminge 872b907372 Guard provider lifecycle updates to primary thread and active turn
- Ignore auxiliary/non-active turn completions for session lifecycle and checkpoints
- Restrict runtime thread/turn IDs to provider IDs in contracts
- Add regression tests and ADR for lifecycle ownership rules
2026-02-27 14:10:34 -08:00
Theo Browne 0b8e098c10 copy on hover, better button treatments (#110) 2026-02-27 14:06:09 -08:00
blacksmith-sh[bot] 7c6a0f869d Migrate workflows to Blacksmith (#111)
Co-authored-by: blacksmith-sh[bot] <157653362+blacksmith-sh[bot]@users.noreply.github.com>
2026-02-27 14:05:22 -08:00
Julius Marminge 3a43047102 Sync diff renderer theme with app theme changes
- Pass explicit Pierre light/dark theme into diff render options
- Re-key file diffs on resolved theme so views rerender on theme switch
- Stabilize `useTheme` snapshots to propagate system theme updates reliably
2026-02-27 11:09:21 -08:00
Julius Marminge 041acf158a fix nullability 2026-02-26 21:36:44 -08:00
Julius Marminge f9752d7c08 migr 2026-02-26 21:26:35 -08:00
Julius Marminge 766592b83b tone down defautls 2026-02-26 21:26:35 -08:00
Julius Marminge 1c3c412ce4 Disable two Effect lint rules in server tsconfig
- Turn off `preferSchemaOverJson`
- Turn off `globalErrorInEffectFailure`
2026-02-26 21:26:35 -08:00
Julius Marminge f9e6d1290d Handle session restart failures without dropping active thread session
- Reorder restart flow to bind the new provider session before stopping the old one
- Log (and swallow) stop-session failures for superseded sessions
- Add regression test ensuring failed restart does not stop the active session
2026-02-26 21:26:35 -08:00
Julius Marminge 8ef653fcc0 Persist required approval policy and sandbox mode for sessions
- Make `approvalPolicy` and `sandboxMode` required in orchestration contracts and turn-start flow
- Add defaults in provider reactors/ingestion to guarantee values are always set
- Store and hydrate both fields in projection persistence, snapshots, and related tests
2026-02-26 21:26:35 -08:00
Julius Marminge fb8d66b8d3 rm 2026-02-26 21:26:35 -08:00
Julius MarmingeandClaude Opus 4.5 e70b34de62 Fix type error with optional approvalPolicy and sandboxMode
Use conditional spreading for these properties to handle undefined
values correctly with exactOptionalPropertyTypes.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 21:26:35 -08:00
Julius Marminge b1584fab8f Add .t3 keybindings and initial local runtime state files
- add default `.t3/keybindings.json` for terminal/chat/editor/diff shortcuts
- include initial provider log files and SQLite state artifacts under `apps/server/.t3`
2026-02-26 21:26:35 -08:00
Julius Marminge 718084065e Restart provider sessions when runtime mode changes
- Persist `approvalPolicy` and `sandboxMode` on orchestration sessions
- Reuse existing sessions when runtime mode is unchanged
- Stop and recreate provider sessions when runtime mode settings change
- Add reactor tests for reuse vs restart behavior
2026-02-26 21:26:35 -08:00
Julius Marminge 57dd091e05 Propagate runtime approval and sandbox settings to turn startup
- Add `approvalPolicy` and `sandboxMode` to turn-start command and requested payload contracts
- Pass runtime mode-derived values from `ChatView` when dispatching `thread.turn.start`
- Thread provider options through decider/reactor into session startup, with tests updated
2026-02-26 21:26:35 -08:00
Julius Marminge a1f208f1e6 Provide NodeServices layer in wsServer bootstrap test
- inject `NodeServices.layer` into sqlite persistence setup in `wsServer.test.ts`
- fixes test runtime dependencies for existing-state bootstrap path
2026-02-26 21:05:53 -08:00
Julius Marminge 581aa7279f Require bootstrap IDs for root thread auto-navigation
- Remove snapshot fallback lookup for missing bootstrap project/thread IDs
- Only expand project and navigate when server payload includes both IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 0b29924648 Recover bootstrap thread from snapshot when IDs are missing
- Fetch orchestration snapshot when bootstrap project/thread IDs are absent
- Resolve project by current workspace and choose latest non-deleted thread
- Continue auto-navigation and expansion using resolved fallback IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 49472da669 Return existing bootstrap thread IDs in welcome and guard root navigatio
- Server welcome now includes bootstrap project/thread IDs when cwd project/thread already exist
- Added regression test for reconnecting with persisted bootstrap state
- Root route ignores post-dispose welcome handling and marks thread as handled after navigate
2026-02-26 21:05:53 -08:00
Julius Marminge 69a2eac2ff Use pathname ref in EventRouter bootstrap navigation
- Track latest `pathname` in a ref for bootstrap event handling
- Prevent effect resubscriptions by removing `pathname` from deps
- Keep auto-navigation gated to root route using current path
2026-02-26 21:05:53 -08:00
Julius Marminge 5fd632c357 Bootstrap default thread and route to it on server welcome
- Create or reuse cwd project, create initial thread, and include bootstrap IDs in `server.welcome`
- Update web event routing to expand the project and auto-navigate from `/` to the bootstrapped thread
- Extend WebSocket welcome contract and add server/web tests for bootstrap payload handling
2026-02-26 21:05:53 -08:00
Julius Marminge bb2164c945 Prevent duplicate sends and sync worktree branch state
- Guard `onSend` with an in-flight ref to block double submits
- Set send phase before worktree prep and always clear in-flight state in `finally`
- Sync thread branch/worktree path immediately and await setup script execution
2026-02-26 20:51:29 -08:00
Julius Marminge 8c91aa5570 Prevent duplicate sends while composer request is in flight
- Add `sendInFlightRef` guard in `ChatView` send handler
- Set sending state before async work and always clear it in `finally`
- Wrap early send flow in one `try/finally` to avoid double-submit races
2026-02-26 20:51:29 -08:00
Julius Marminge 6db8257b1e Stop forcing setup script to open a new terminal
- Remove `preferNewTerminal` when invoking `runProjectScript` in `ChatView`
- Lets setup scripts use default terminal behavior for worktree runs
2026-02-26 20:51:29 -08:00
Julius Marminge f6e7166e79 Capture threadId before async send flow
- Store `activeThread.id` once at send start and reuse it
- Prevents updates/errors from targeting the wrong thread during async worktree/send steps
2026-02-26 20:51:29 -08:00
Julius Marmingeandcodex 2da8290040 Require base branch before first send in worktree mode
- show an explicit error when New worktree mode has no base branch selected
- sync thread branch/worktree path immediately after creation
- run setup script in the new worktree terminal before continuing

Co-authored-by: codex <[email protected]>
2026-02-26 20:51:29 -08:00
55 changed files with 3865 additions and 627 deletions

No files matched your search

+1 -1
View File
@@ -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
+64
View File
@@ -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));
}
+1 -1
View File
@@ -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`
+1 -1
View File
@@ -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({
@@ -215,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(
@@ -319,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),
);
@@ -653,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,
+1 -1
View File
@@ -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,
@@ -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);
@@ -334,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,
@@ -349,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(
@@ -381,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();
@@ -413,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",
});
@@ -505,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",
});
@@ -554,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",
});
@@ -607,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",
});
@@ -619,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(
@@ -698,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);
@@ -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;
}
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;
@@ -481,7 +767,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
});
});
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.turn-start-requested": {
@@ -714,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": {
@@ -837,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
@@ -901,6 +1216,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
OrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline,
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ProjectionProjectRepositoryLive),
Layer.provideMerge(ProjectionThreadRepositoryLive),
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
@@ -243,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,
@@ -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"
@@ -226,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,
@@ -250,6 +285,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activityRows,
sessionRows,
checkpointRows,
latestTurnRows,
stateRows,
] = yield* Effect.all([
listProjectRows(undefined).pipe(
@@ -300,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(
@@ -314,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;
@@ -334,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,
@@ -372,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, {
@@ -406,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,
@@ -31,6 +31,8 @@ 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);
@@ -220,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();
@@ -33,6 +33,7 @@ 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,
@@ -53,6 +54,17 @@ 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;
}
@@ -332,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" ||
@@ -340,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)
@@ -349,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"
@@ -365,24 +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,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
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) {
@@ -470,29 +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,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
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);
@@ -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: [],
@@ -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,
@@ -207,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");
});
@@ -504,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 () => {
+54 -6
View File
@@ -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,
@@ -220,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,
@@ -351,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,
}),
};
@@ -396,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,
}),
};
@@ -422,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,
@@ -431,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 } : {}),
})),
),
);
@@ -18,6 +18,7 @@ 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.
@@ -36,6 +37,7 @@ const loader = Migrator.fromRecord({
"4_ProviderSessionRuntime": Migration0004,
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
"7_ProjectionThreadMessageAttachments": Migration0007,
});
/**
@@ -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,
+155
View File
@@ -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>");
});
});
});
+188
View File
@@ -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);
@@ -564,7 +565,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 +613,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 +625,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 +635,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",
},
@@ -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)));
}));
});
+3 -3
View File
@@ -61,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}`,
);
+211 -7
View File
@@ -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,13 +355,17 @@ describe("WebSocket Server", () => {
async function createTestServer(
options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
persistenceLayer?: Layer.Layer<
SqlClient.SqlClient,
SqlError.SqlError | MigrationError | PlatformError.PlatformError
>;
cwd?: string;
autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
open?: OpenShape;
gitManager?: GitManagerShape;
@@ -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 () => {
+218 -75
View File
@@ -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.
@@ -67,7 +66,7 @@ export interface ServerShape {
readonly start: Effect.Effect<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
>;
/**
@@ -166,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
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,59 @@ 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) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
if (!existing) {
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();
const projectName = path.basename(cwd) || "project";
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: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
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(
@@ -581,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));
File diff suppressed because it is too large. Load diff
+8 -2
View File
@@ -16,7 +16,11 @@ import { useStore } from "../store";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark" | "system";
type DiffThemeType = "light" | "dark";
function resolveDiffThemeName(theme: "light" | "dark") {
return theme === "dark" ? "pierre-dark" : "pierre-light";
}
type RenderablePatch =
| {
@@ -472,13 +476,15 @@ 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="rounded-md">
<FileDiff
fileDiff={fileDiff}
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
}}
/>
@@ -1,8 +1,39 @@
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";
function resolveDiffThemeName(theme: "light" | "dark") {
return theme === "dark" ? "pierre-dark" : "pierre-light";
}
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
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 +48,11 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
totalASTLRUCacheSize: 240,
}}
highlighterOptions={{
theme: diffThemeName,
tokenizeMaxLineLength: 1_000,
}}
>
<DiffWorkerThemeSync themeName={diffThemeName} />
{children}
</WorkerPoolContextProvider>
);
+58 -6
View File
@@ -1,4 +1,4 @@
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
DEFAULT_MODEL,
@@ -15,6 +15,7 @@ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
@@ -50,7 +51,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;
@@ -63,8 +64,8 @@ interface TerminalStatusIndicator {
}
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 +77,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,
@@ -140,6 +141,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 +203,13 @@ 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 handleNewThread = useCallback(
(
@@ -566,6 +617,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>
@@ -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}
+18 -4
View File
@@ -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);
+42 -4
View File
@@ -1,5 +1,11 @@
import { ThreadId } from "@t3tools/contracts";
import { Outlet, createRootRouteWithContext, type ErrorComponentProps } from "@tanstack/react-router";
import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useNavigate,
useRouterState,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
@@ -119,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();
@@ -180,8 +191,35 @@ function EventRouter() {
hasRunningSubprocess,
});
});
const unsubWelcome = onServerWelcome(() => {
void syncSnapshot();
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);
@@ -232,7 +270,7 @@ function EventRouter() {
unsubWelcome();
unsubServerConfigUpdated();
};
}, [dispatch, queryClient]);
}, [dispatch, navigate, queryClient]);
return null;
}
+2 -2
View File
@@ -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}>
+75 -1
View File
@@ -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);
});
});
+20
View File
@@ -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[],
+11 -3
View File
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { reducer, type AppState } from "./store";
@@ -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,
@@ -58,7 +59,14 @@ describe("store reducer", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
latestTurnCompletedAt,
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",
}),
);
@@ -79,7 +87,7 @@ describe("store reducer", () => {
it("does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurnCompletedAt: undefined,
latestTurn: null,
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
+50 -20
View File
@@ -41,6 +41,7 @@ type Action =
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 }
@@ -191,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);
@@ -413,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,
@@ -468,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,
@@ -483,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,
@@ -536,10 +558,10 @@ export function reducer(state: AppState, action: Action): AppState {
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
if (!thread.latestTurnCompletedAt) {
if (!thread.latestTurn?.completedAt) {
return thread;
}
const latestTurnCompletedAtMs = Date.parse(thread.latestTurnCompletedAt);
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return thread;
}
@@ -571,6 +593,14 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
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,
+2 -4
View File
@@ -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;
+1
View File
@@ -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,
+30 -3
View File
@@ -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",
+1 -1
View File
@@ -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: [
@@ -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.
+23 -5
View File
@@ -142,8 +142,8 @@ export const OrchestrationSession = Schema.Struct({
providerName: Schema.NullOr(TrimmedNonEmptyString),
providerSessionId: Schema.NullOr(ProviderSessionId),
providerThreadId: Schema.NullOr(ProviderThreadId),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(TrimmedNonEmptyString),
updatedAt: IsoDateTime,
@@ -191,6 +191,24 @@ export const OrchestrationThreadActivity = Schema.Struct({
});
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
export const OrchestrationLatestTurnState = Schema.Literals([
"running",
"interrupted",
"completed",
"error",
]);
export type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;
export const OrchestrationLatestTurn = Schema.Struct({
turnId: TurnId,
state: OrchestrationLatestTurnState,
requestedAt: IsoDateTime,
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
});
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
export const OrchestrationThread = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
@@ -198,7 +216,7 @@ export const OrchestrationThread = Schema.Struct({
model: TrimmedNonEmptyString,
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
latestTurnId: Schema.NullOr(TurnId),
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
deletedAt: Schema.NullOr(IsoDateTime),
@@ -500,8 +518,8 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
createdAt: IsoDateTime,
});
+23 -27
View File
@@ -9,15 +9,11 @@ import {
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
IsoDateTime,
} from "./baseSchemas";
import { ProviderApprovalDecision, ProviderKind, ProviderRequestKind } from "./orchestration";
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
const RuntimeThreadIdSchema = Schema.Union([ThreadId, ProviderThreadId]);
const RuntimeTurnIdSchema = Schema.Union([TurnId, ProviderTurnId]);
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
@@ -36,7 +32,7 @@ export const ProviderRuntimeSessionStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
threadId: Schema.optional(ProviderThreadId),
message: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
@@ -47,7 +43,7 @@ export const ProviderRuntimeSessionExitedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
threadId: Schema.optional(ProviderThreadId),
message: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;
@@ -58,7 +54,7 @@ export const ProviderRuntimeThreadStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: RuntimeThreadIdSchema,
threadId: ProviderThreadId,
});
export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;
@@ -68,8 +64,8 @@ export const ProviderRuntimeTurnStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: RuntimeTurnIdSchema,
threadId: Schema.optional(ProviderThreadId),
turnId: ProviderTurnId,
});
export type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;
@@ -79,8 +75,8 @@ export const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
status: Schema.optional(ProviderRuntimeTurnStatus),
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
});
@@ -92,8 +88,8 @@ export const ProviderRuntimeMessageDeltaEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
delta: Schema.String,
});
@@ -106,8 +102,8 @@ export const ProviderRuntimeMessageCompletedEvent = Schema.Struct({
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
itemId: ProviderItemId,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
});
export type ProviderRuntimeMessageCompletedEvent = typeof ProviderRuntimeMessageCompletedEvent.Type;
@@ -117,8 +113,8 @@ export const ProviderRuntimeToolStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
toolKind: ProviderRuntimeToolKind,
title: TrimmedNonEmptyStringSchema,
@@ -132,8 +128,8 @@ export const ProviderRuntimeToolCompletedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
toolKind: ProviderRuntimeToolKind,
title: TrimmedNonEmptyStringSchema,
@@ -147,8 +143,8 @@ export const ProviderRuntimeApprovalRequestedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
requestId: ApprovalRequestId,
requestKind: ProviderRequestKind,
@@ -163,8 +159,8 @@ export const ProviderRuntimeApprovalResolvedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
requestId: ApprovalRequestId,
requestKind: Schema.optional(ProviderRequestKind),
@@ -178,8 +174,8 @@ export const ProviderRuntimeCheckpointCapturedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: RuntimeThreadIdSchema,
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: ProviderThreadId,
turnId: Schema.optional(ProviderTurnId),
turnCount: NonNegativeInt,
status: Schema.optional(ProviderRuntimeTurnStatus),
});
@@ -192,8 +188,8 @@ export const ProviderRuntimeErrorEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
message: TrimmedNonEmptyStringSchema,
});
+3 -1
View File
@@ -1,5 +1,5 @@
import { Schema, Struct } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
import {
ClientOrchestrationCommand,
@@ -163,5 +163,7 @@ export type WsResponse = typeof WsResponse.Type;
export const WsWelcomePayload = Schema.Struct({
cwd: TrimmedNonEmptyString,
projectName: TrimmedNonEmptyString,
bootstrapProjectId: Schema.optional(ProjectId),
bootstrapThreadId: Schema.optional(ThreadId),
});
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
+1 -1
View File
@@ -4,7 +4,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5173;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {