Compare commits

..
Author SHA1 Message Date
Julius Marminge 8effcf380a 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:01:54 -08:00
Julius Marminge 9e8363ceca 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 20:52:30 -08:00
Julius Marminge 080752a3f7 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 20:52:30 -08:00
Julius Marminge cd685c9a64 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 20:52:30 -08:00
Julius Marminge a8d0e9b06b 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 20:52:30 -08:00
Julius Marminge 7276b75dd6 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 20:52:30 -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
Julius Marminge 4d6e8e1ca5 rm redundant gen 2026-02-26 20:43:22 -08:00
Julius Marminge 7e4da5b157 Remove assistant-complete text payload from orchestration flow
- Drop optional `text` from `ThreadMessageAssistantCompleteCommand`
- Stop passing text on assistant-complete ingestion and decider paths
- Ensure completion events no longer overwrite message content
2026-02-26 20:43:22 -08:00
Julius Marminge 9acce6ddaa todo 2026-02-26 20:43:22 -08:00
Julius Marminge 8054a32417 update todo 2026-02-26 20:43:22 -08:00
Julius Marminge ed3958daa8 Clarify assistant buffer flush safety-valve comment
- Update wording to say buffered text is flushed as an assistant delta
- Keeps intent clear: memory is capped by emitting the current buffer
2026-02-26 20:43:22 -08:00
Julius Marminge 9d5c515680 Always flush buffered assistant text as final delta
- Remove spilled-state cache tracking for buffered assistant messages
- Emit any remaining buffered text as a finalize delta on completion
- Keep assistant completion payload text empty in buffered mode
2026-02-26 20:43:22 -08:00
Julius Marminge 0e9677965c Spill full buffered assistant text when buffer exceeds cap
- Change provider runtime ingestion to flush the entire buffered assistant text once it crosses the max size
- Remove partial-retention logic and its keep-chars constant to simplify memory safety behavior
2026-02-26 20:43:22 -08:00
Julius Marminge cc29ceea80 Spill oversized buffered assistant deltas without losing final text
- cap buffered assistant text memory and spill older chunks as delta events
- finalize buffered messages by emitting retained remainder before completion when spilled
- add regression coverage for oversized buffered deltas and tighten type-safe test assertions
2026-02-26 20:43:22 -08:00
Julius Marminge 32a17b9109 Simplify assistant delivery mode state in runtime ingestion
- Replace per-thread/turn/message delivery-mode caches with a single `Ref`
- Always complete assistant messages with buffered text from message state
- Remove obsolete delivery-mode cleanup and resolution paths
2026-02-26 20:43:22 -08:00
Julius MarmingeandClaude Opus 4.5 e119e18ed3 Fix type errors with exactOptionalPropertyTypes
Use conditional spread for turnId to avoid passing undefined
explicitly when the target type expects an optional property.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 20:43:22 -08:00
Julius Marminge 001902c881 Add configurable assistant delivery mode across server and web
- add `AssistantDeliveryMode` contracts and carry mode through turn-start events
- default assistant responses to buffered mode and preserve buffered text until completion
- support streaming mode end-to-end with ingestion/decider updates and test coverage
- add a Settings toggle to enable assistant streaming in the chat UI
2026-02-26 20:43:22 -08:00
7 changed files with 261 additions and 20 deletions

No files matched your search

+98 -3
View File
@@ -3,6 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
@@ -38,7 +39,7 @@ import type {
TerminalWriteInput,
} from "@t3tools/contracts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient } from "effect/unstable/sql";
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
import { Open, type OpenShape } from "./open";
@@ -448,23 +449,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)) as unknown as Layer.Layer<SqlClient.SqlClient, never>;
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 () => {
+50 -7
View File
@@ -16,6 +16,7 @@ import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProjectId,
ThreadId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
@@ -337,22 +338,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 +619,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));
+29 -2
View File
@@ -368,6 +368,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -1391,7 +1392,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || isConnecting) return;
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
@@ -1401,6 +1402,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
: null;
// In worktree mode, require an explicit base branch so we don't silently
// fall back to local execution when branch selection is missing.
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
return;
}
sendInFlightRef.current = true;
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
const composerImagesSnapshot = [...composerImages];
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
@@ -1449,9 +1467,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
await runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
@@ -1530,6 +1556,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
err instanceof Error ? err.message : "Failed to send message.",
);
} finally {
sendInFlightRef.current = false;
setSendPhase("idle");
}
};
+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;
}
+9
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 }
@@ -571,6 +572,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,
+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",
+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;