Compare commits

..
Author SHA1 Message Date
Julius Marminge c0e3c1a93a Add Mark unread thread action to sidebar context menu
- Add `mark-unread` option to thread context menu and dispatch reducer action
- Implement `MARK_THREAD_UNREAD` to set `lastVisitedAt` just before latest completion
- Add reducer tests for unread behavior and no-op when no completed turn
- Update fallback context menu styling so only delete uses destructive color
2026-02-26 18:57:40 -08:00
38 changed files with 275 additions and 1073 deletions

No files matched your search

-1
View File
@@ -11,4 +11,3 @@ packages/*/dist
build/ build/
.logs/ .logs/
release/ release/
.t3
+2 -2
View File
@@ -15,11 +15,11 @@
- [x] "Response" bar should ONLY appear above the FINAL message in a series - [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc) - [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [x] Insta focus input on new thread creation - [x] Insta focus input on new thread creation
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it - [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box - [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank) - [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things ## Bigger things
- [ ] Queueing messages - [ ] Queueing messages
- [x] External runners (i.e. running the cli on a mac mini) - [ ] External runners (i.e. running the cli on a mac mini)
@@ -9,17 +9,7 @@ import {
type OrchestrationEvent, type OrchestrationEvent,
type OrchestrationThread, type OrchestrationThread,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts"; import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts"; import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
@@ -85,27 +75,20 @@ export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): st
return runGit(cwd, ["show", `${ref}:${filePath}`]); return runGit(cwd, ["show", `${ref}:${filePath}`]);
} }
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()( function waitFor<A>(
"WaitForTimeoutError", read: Effect.Effect<A, unknown>,
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean, predicate: (value: A) => boolean,
description: string, description: string,
timeoutMs?: number, timeoutMs?: number,
): Effect.Effect<A, never>; ): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>( function waitFor<A, B extends A>(
read: Effect.Effect<A, E>, read: Effect.Effect<A, unknown>,
predicate: (value: A) => value is B, predicate: (value: A) => value is B,
description: string, description: string,
timeoutMs?: number, timeoutMs?: number,
): Effect.Effect<B, never>; ): Effect.Effect<B, never>;
function waitFor<A, E>( function waitFor<A>(
read: Effect.Effect<A, E>, read: Effect.Effect<A, unknown>,
predicate: (value: A) => boolean, predicate: (value: A) => boolean,
description: string, description: string,
timeoutMs = 3000, timeoutMs = 3000,
@@ -123,26 +106,12 @@ function waitFor<A, E>(
while: (error) => error === RETRY_SIGNAL, while: (error) => error === RETRY_SIGNAL,
}), }),
Effect.mapError((error) => Effect.mapError((error) =>
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error, error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
), ),
Effect.orDie, Effect.orDie,
); );
} }
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
Effect.tryPromise({
try: run,
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
});
export interface OrchestrationIntegrationHarness { export interface OrchestrationIntegrationHarness {
readonly rootDir: string; readonly rootDir: string;
readonly workspaceDir: string; readonly workspaceDir: string;
@@ -183,7 +152,8 @@ export interface OrchestrationIntegrationHarness {
} }
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () { export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) => Effect.sleep(ms); const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const adapterHarness = yield* makeTestProviderAdapterHarness; const adapterHarness = yield* makeTestProviderAdapterHarness;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-")); const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
@@ -245,34 +215,30 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
); );
const runtime = ManagedRuntime.make(layer); const runtime = ManagedRuntime.make(layer);
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () => const engine = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationEngineService)), runtime.runPromise(Effect.service(OrchestrationEngineService)),
).pipe(Effect.orDie); );
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () => const reactor = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationReactor)), runtime.runPromise(Effect.service(OrchestrationReactor)),
).pipe(Effect.orDie); );
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () => const snapshotQuery = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)), runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
).pipe(Effect.orDie); );
const providerService = yield* tryRuntimePromise("load ProviderService service", () => const providerService = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProviderService)), runtime.runPromise(Effect.service(ProviderService)),
).pipe(Effect.orDie); );
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () => const checkpointStore = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(CheckpointStore)), runtime.runPromise(Effect.service(CheckpointStore)),
).pipe(Effect.orDie); );
const checkpointRepository = yield* tryRuntimePromise( const checkpointRepository = yield* Effect.promise(() =>
"load ProjectionCheckpointRepository service", runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)), );
).pipe(Effect.orDie); const pendingApprovalRepository = yield* Effect.promise(() =>
const pendingApprovalRepository = yield* tryRuntimePromise( runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
"load ProjectionPendingApprovalRepository service", );
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
).pipe(Effect.orDie);
const scope = yield* Scope.make("sequential"); const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
yield* tryRuntimePromise("start OrchestrationReactor", () => yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
yield* sleep(10); yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = ( const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
@@ -13,7 +13,7 @@ import {
ThreadId, ThreadId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest"; import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect"; import { Effect, Exit, Option } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts"; import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import { import {
@@ -45,14 +45,8 @@ function nowIso() {
return new Date().toISOString(); return new Date().toISOString();
} }
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()( const sleep = (ms: number) =>
"IntegrationWaitTimeoutError", Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
{
description: Schema.String,
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>( function waitForSync<A>(
read: () => A, read: () => A,
@@ -69,7 +63,7 @@ function waitForSync<A>(
return value; return value;
} }
if (Date.now() >= deadline) { if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description })); return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
} }
yield* sleep(10); yield* sleep(10);
} }
@@ -139,6 +133,24 @@ const startTurn = (input: {
createdAt: nowIso(), createdAt: nowIso(),
}); });
it.live("always removes integration temp dirs when shutdown fails", () =>
Effect.gen(function* () {
const harness = yield* makeOrchestrationIntegrationHarness;
const rootDir = harness.rootDir;
const originalStopAll = harness.providerService.stopAll.bind(harness.providerService);
(
harness.providerService as unknown as {
stopAll: typeof harness.providerService.stopAll;
}
).stopAll = () => originalStopAll().pipe(Effect.andThen(Effect.fail(new Error("boom"))));
const disposeExit = yield* Effect.exit(harness.dispose);
assert.equal(Exit.isFailure(disposeExit), true);
assert.equal(fs.existsSync(rootDir), false);
}),
);
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () => it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
withHarness((harness) => withHarness((harness) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect"; import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { TextGenerationError } from "../Errors.ts"; import { TextGenerationError } from "../Errors.ts";
@@ -40,7 +40,7 @@ function normalizeCodexError(
error: unknown, error: unknown,
fallback: string, fallback: string,
): TextGenerationError { ): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) { if (error instanceof TextGenerationError) {
return error; return error;
} }
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const path = yield* Path.Path; const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const readStreamAsString = <E>( const readStreamAsString = (
operation: string, operation: string,
stream: Stream.Stream<Uint8Array, E>, stream: Stream.Stream<Uint8Array, unknown>,
): Effect.Effect<string, TextGenerationError> => ): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () { Effect.gen(function* () {
let text = ""; let text = "";
+42 -23
View File
@@ -6,7 +6,7 @@ import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest"; import { expect } from "vitest";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts"; import { GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts"; import { type GitManagerShape } from "../Services/GitManager.ts";
import { import {
type GitHubCliShape, type GitHubCliShape,
@@ -23,7 +23,7 @@ interface FakeGhScenario {
prListSequence?: string[]; prListSequence?: string[];
createdPrUrl?: string; createdPrUrl?: string;
defaultBranch?: string; defaultBranch?: string;
failWith?: GitHubCliError; failWith?: Error;
} }
interface FakeGitTextGeneration { interface FakeGitTextGeneration {
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
branch: string | null; branch: string | null;
stagedSummary: string; stagedSummary: string;
stagedPatch: string; stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>; }) => Effect.Effect<{ subject: string; body: string }, unknown>;
generatePrContent: (input: { generatePrContent: (input: {
cwd: string; cwd: string;
baseBranch: string; baseBranch: string;
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
commitSummary: string; commitSummary: string;
diffSummary: string; diffSummary: string;
diffPatch: string; diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>; }) => Effect.Effect<{ title: string; body: string }, unknown>;
} }
function makeTempDir( function makeTempDir(
@@ -58,7 +58,7 @@ function runGit(
allowNonZeroExit = false, allowNonZeroExit = false,
): Effect.Effect< ): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string }, { readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError, unknown,
GitService GitService
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
@@ -74,7 +74,7 @@ function runGit(
function initRepo( function initRepo(
cwd: string, cwd: string,
): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> { ): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> {
return Effect.gen(function* () { return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem; const fs = yield* FileSystem.FileSystem;
yield* runGit(cwd, ["init", "--initial-branch=main"]); yield* runGit(cwd, ["init", "--initial-branch=main"]);
@@ -88,7 +88,7 @@ function initRepo(
function createBareRemote(): Effect.Effect< function createBareRemote(): Effect.Effect<
string, string,
PlatformError.PlatformError | GitCommandError, unknown,
FileSystem.FileSystem | Scope.Scope | GitService FileSystem.FileSystem | Scope.Scope | GitService
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
@@ -139,6 +139,34 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
}; };
} }
const normalizeGhError = (error: Error): GitHubCliError => {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
return new GitHubCliError({
operation: "execute",
detail: error.message,
cause: error,
});
};
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
service: GitHubCliShape; service: GitHubCliShape;
ghCalls: string[]; ghCalls: string[];
@@ -151,7 +179,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
ghCalls.push(args.join(" ")); ghCalls.push(args.join(" "));
if (scenario.failWith) { if (scenario.failWith) {
return Effect.fail(scenario.failWith); return Effect.fail(normalizeGhError(scenario.failWith));
} }
if (args[0] === "pr" && args[1] === "list") { if (args[0] === "pr" && args[1] === "list") {
@@ -345,10 +373,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new GitHubCliError({ failWith: new Error("Command not found: gh"),
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
}, },
}); });
@@ -575,7 +600,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push", action: "commit_push",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => error.message), Effect.map((error) => (error instanceof Error ? error.message : String(error))),
); );
expect(errorMessage).toContain("detached HEAD"); expect(errorMessage).toContain("detached HEAD");
}), }),
@@ -592,10 +617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new GitHubCliError({ failWith: new Error("Command not found: gh"),
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
}, },
}); });
@@ -604,7 +626,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr", action: "commit_push_pr",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => error.message), Effect.map((error) => (error instanceof Error ? error.message : String(error))),
); );
expect(errorMessage).toContain("GitHub CLI (`gh`) is required"); expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
}), }),
@@ -621,10 +643,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new GitHubCliError({ failWith: new Error("authentication failed"),
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
}, },
}); });
@@ -633,7 +652,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr", action: "commit_push_pr",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => error.message), Effect.map((error) => (error instanceof Error ? error.message : String(error))),
); );
expect(errorMessage).toContain("gh auth login"); expect(errorMessage).toContain("gh auth login");
}), }),
@@ -1,6 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest"; import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect"; import { Effect, Layer } from "effect";
import { GitCommandError } from "../Errors.ts"; import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts"; import { GitServiceLive } from "./GitService.ts";
@@ -50,7 +50,7 @@ layer("GitServiceLive", (it) => {
assert.equal(result._tag, "Failure"); assert.equal(result._tag, "Failure");
if (result._tag === "Failure") { if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure)); assert.ok(result.failure instanceof GitCommandError);
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero"); assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__"); assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
} }
+4 -4
View File
@@ -6,7 +6,7 @@
* *
* @module GitServiceLive * @module GitServiceLive
*/ */
import { Effect, Layer, Option, Schema, Stream } from "effect"; import { Effect, Layer, Option, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts"; import { GitCommandError } from "../Errors.ts";
import { import {
@@ -28,7 +28,7 @@ function toGitCommandError(
detail: string, detail: string,
) { ) {
return (cause: unknown) => return (cause: unknown) =>
Schema.is(GitCommandError)(cause) cause instanceof GitCommandError
? cause ? cause
: new GitCommandError({ : new GitCommandError({
operation: input.operation, operation: input.operation,
@@ -39,9 +39,9 @@ function toGitCommandError(
}); });
} }
const collectOutput = Effect.fn(function* <E>( const collectOutput = Effect.fn(function* (
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">, input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>, stream: Stream.Stream<Uint8Array, unknown>,
maxOutputBytes: number, maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> { ): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
+7 -1
View File
@@ -211,7 +211,13 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}); });
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle")); assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command")); assert.isFalse(
configState.keybindings.some(
(entry) =>
// @ts-expect-error - invalid command
entry.command === "invalid.command",
),
);
assert.deepEqual(configState.issues, [ assert.deepEqual(configState.issues, [
{ {
kind: "keybindings.invalid-entry", kind: "keybindings.invalid-entry",
-1
View File
@@ -65,7 +65,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" }, { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" }, { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" }, { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
+1 -4
View File
@@ -117,10 +117,7 @@ export const launchDetached = (launch: EditorLaunch) =>
}); });
const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({ const open = yield* Effect.promise(() => import("open"));
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
return { return {
openBrowser: (target) => openBrowser: (target) =>
@@ -2,7 +2,6 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { import {
CommandId, CommandId,
EventId, EventId,
MessageId,
ProjectId, ProjectId,
ProviderItemId, ProviderItemId,
ProviderSessionId, ProviderSessionId,
@@ -34,7 +33,6 @@ const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.make
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value); const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value); const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
function createProviderServiceHarness() { function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>()); const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -260,201 +258,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false); expect(message?.streaming).toBe(false);
}); });
it("buffers assistant deltas by default until completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
delta: "buffer me",
});
await Effect.runPromise(Effect.sleep("30 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
false,
);
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
expect(message?.text).toBe("buffer me");
expect(message?.streaming).toBe(false);
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("message-streaming-mode"),
role: "user",
text: "stream please",
attachments: [],
},
assistantDeliveryMode: "streaming",
createdAt: now,
}),
);
await Effect.runPromise(Effect.sleep("30 millis"));
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-streaming-mode",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
itemId: asItemId("item-streaming-mode"),
delta: "hello live",
});
const liveThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) =>
message.id === "assistant:item-streaming-mode" &&
message.streaming &&
message.text === "hello live",
),
);
const liveMessage = liveThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
);
expect(liveMessage?.streaming).toBe(true);
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
itemId: asItemId("item-streaming-mode"),
});
const finalThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
),
);
const finalMessage = finalThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
);
expect(finalMessage?.text).toBe("hello live");
expect(finalMessage?.streaming).toBe(false);
});
it("spills oversized buffered deltas and still finalizes full assistant text", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const oversizedText = "x".repeat(40_000);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffer-spill",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
itemId: asItemId("item-buffer-spill"),
delta: oversizedText,
});
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
itemId: asItemId("item-buffer-spill"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
expect(message?.text.length).toBe(oversizedText.length);
expect(message?.text).toBe(oversizedText);
expect(message?.streaming).toBe(false);
});
it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => { it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => {
const harness = await createHarness(); const harness = await createHarness();
const now = new Date().toISOString(); const now = new Date().toISOString();
@@ -1,16 +1,13 @@
import { import {
type AssistantDeliveryMode,
CommandId, CommandId,
MessageId, MessageId,
type OrchestrationEvent,
ProviderThreadId, ProviderThreadId,
type ThreadId,
TurnId, TurnId,
type OrchestrationThreadActivity, type OrchestrationThreadActivity,
type ProviderRuntimeEvent, type ProviderRuntimeEvent,
type ProviderSessionId, type ProviderSessionId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect"; import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -22,28 +19,8 @@ import {
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`; const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId => const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`); CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000; const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120); 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;
type TurnStartRequestedDomainEvent = Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" }
>;
type RuntimeIngestionInput =
| {
source: "runtime";
event: ProviderRuntimeEvent;
}
| {
source: "domain";
event: TurnStartRequestedDomainEvent;
};
function toTurnId(value: string | undefined): TurnId | undefined { function toTurnId(value: string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.makeUnsafe(value); return value === undefined ? undefined : TurnId.makeUnsafe(value);
@@ -111,7 +88,6 @@ function runtimeEventToActivities(
}, },
]; ];
} }
case "tool.completed": { case "tool.completed": {
return [ return [
{ {
@@ -128,7 +104,6 @@ function runtimeEventToActivities(
}, },
]; ];
} }
case "tool.started": { case "tool.started": {
return [ return [
{ {
@@ -155,22 +130,12 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService; const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService; const providerService = yield* ProviderService;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({ const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY, capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL, timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
lookup: () => Effect.succeed(new Set<MessageId>()), lookup: () => Effect.succeed(new Set<MessageId>()),
}); });
const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
lookup: () => Effect.succeed(""),
});
const rememberAssistantMessageId = ( const rememberAssistantMessageId = (
sessionId: ProviderSessionId, sessionId: ProviderSessionId,
turnId: TurnId, turnId: TurnId,
@@ -224,76 +189,6 @@ const make = Effect.gen(function* () {
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) => const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId)); Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
Effect.gen(function* () {
const nextText = Option.match(existingText, {
onNone: () => delta,
onSome: (text) => `${text}${delta}`,
});
if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
return "";
}
// Safety valve: flush full buffered text as an assistant delta to cap memory.
yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
return nextText;
}),
),
);
const takeBufferedAssistantText = (messageId: MessageId) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.as(Option.getOrElse(existingText, () => "")),
),
),
);
const clearBufferedAssistantText = (messageId: MessageId) =>
Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
const finalizeAssistantMessage = (input: {
event: ProviderRuntimeEvent;
threadId: ThreadId;
messageId: MessageId;
turnId?: TurnId;
createdAt: string;
commandTag: string;
finalDeltaCommandTag: string;
}) =>
Effect.gen(function* () {
const text = yield* takeBufferedAssistantText(input.messageId);
if (text.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
}
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
yield* clearAssistantMessageState(input.messageId);
});
const clearTurnStateForSession = (sessionId: ProviderSessionId) => const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
Effect.gen(function* () { Effect.gen(function* () {
const prefix = `${sessionId}:`; const prefix = `${sessionId}:`;
@@ -301,25 +196,12 @@ const make = Effect.gen(function* () {
yield* Effect.forEach( yield* Effect.forEach(
turnKeys, turnKeys,
(key) => (key) =>
Effect.gen(function* () { key.startsWith(prefix) ? Cache.invalidate(turnMessageIdsByTurnKey, key) : Effect.void,
if (!key.startsWith(prefix)) {
return;
}
const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
if (Option.isSome(messageIds)) {
yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
concurrency: 1,
}).pipe(Effect.asVoid);
}
yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
}),
{ concurrency: 1 }, { concurrency: 1 },
).pipe(Effect.asVoid); ).pipe(Effect.asVoid);
}); });
const processRuntimeEvent = (event: ProviderRuntimeEvent) => const processEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () { Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel(); const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find( const thread = readModel.threads.find(
@@ -388,31 +270,15 @@ const make = Effect.gen(function* () {
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId); yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
} }
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef); yield* orchestrationEngine.dispatch({
if (assistantDeliveryMode === "buffered") { type: "thread.message.assistant.delta",
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, event.delta); commandId: providerCommandId(event, "assistant-delta"),
if (spillChunk.length > 0) { threadId: thread.id,
yield* orchestrationEngine.dispatch({ messageId: assistantMessageId,
type: "thread.message.assistant.delta", delta: event.delta,
commandId: providerCommandId(event, "assistant-delta-buffer-spill"), ...(turnId ? { turnId } : {}),
threadId: thread.id, createdAt: now,
messageId: assistantMessageId, });
delta: spillChunk,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: event.delta,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
} }
if (event.type === "message.completed") { if (event.type === "message.completed") {
@@ -422,14 +288,13 @@ const make = Effect.gen(function* () {
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId); yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
} }
yield* finalizeAssistantMessage({ yield* orchestrationEngine.dispatch({
event, type: "thread.message.assistant.complete",
commandId: providerCommandId(event, "assistant-complete"),
threadId: thread.id, threadId: thread.id,
messageId: assistantMessageId, messageId: assistantMessageId,
...(turnId ? { turnId } : {}), ...(turnId ? { turnId } : {}),
createdAt: now, createdAt: now,
commandTag: "assistant-complete",
finalDeltaCommandTag: "assistant-delta-finalize",
}); });
if (turnId) { if (turnId) {
@@ -441,19 +306,15 @@ const make = Effect.gen(function* () {
const turnId = toTurnId(event.turnId); const turnId = toTurnId(event.turnId);
if (turnId) { if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId); const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
yield* Effect.forEach( yield* Effect.forEach(assistantMessageIds, (assistantMessageId) =>
assistantMessageIds, orchestrationEngine.dispatch({
(assistantMessageId) => type: "thread.message.assistant.complete",
finalizeAssistantMessage({ commandId: providerCommandId(event, "assistant-complete-finalize"),
event, threadId: thread.id,
threadId: thread.id, messageId: assistantMessageId,
messageId: assistantMessageId, turnId,
turnId, createdAt: now,
createdAt: now, }),
commandTag: "assistant-complete-finalize",
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
}),
{ concurrency: 1 },
).pipe(Effect.asVoid); ).pipe(Effect.asVoid);
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId); yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
} }
@@ -499,50 +360,33 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid); ).pipe(Effect.asVoid);
}); });
const processDomainEvent = (event: TurnStartRequestedDomainEvent) => const processEventSafely = (event: ProviderRuntimeEvent) =>
Ref.set( processEvent(event).pipe(
assistantDeliveryModeRef,
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const processInput = (input: RuntimeIngestionInput) =>
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
const processInputSafely = (input: RuntimeIngestionInput) =>
processInput(input).pipe(
Effect.catchCause((cause) => { Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) { if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause); return Effect.failCause(cause);
} }
return Effect.logWarning("provider runtime ingestion failed to process event", { return Effect.logWarning("provider runtime ingestion failed to process event", {
source: input.source, eventId: event.eventId,
eventId: input.event.eventId, eventType: event.type,
eventType: input.event.type,
cause: Cause.pretty(cause), cause: Cause.pretty(cause),
}); });
}), }),
); );
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () { const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>(); const providerEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
yield* Effect.addFinalizer(() => Queue.shutdown(providerEventQueue).pipe(Effect.asVoid));
yield* Effect.forkScoped( yield* Effect.forkScoped(
Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))), Effect.forever(Queue.take(providerEventQueue).pipe(Effect.flatMap(processEventSafely))),
); );
yield* Effect.forkScoped( yield* Effect.forkScoped(
Stream.runForEach(providerService.streamEvents, (event) => Stream.runForEach(providerService.streamEvents, (event) =>
Queue.offer(inputQueue, { source: "runtime", event }).pipe(Effect.asVoid), Queue.offer(providerEventQueue, event).pipe(Effect.asVoid),
), ),
); );
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.turn-start-requested") {
return Effect.void;
}
return Queue.offer(inputQueue, { source: "domain", event }).pipe(Effect.asVoid);
}),
);
}); });
return { return {
@@ -162,12 +162,7 @@ describe("decider project scripts", () => {
const events = Array.isArray(result) ? result : [result]; const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2); expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent"); expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1]; expect(events[1]?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.type).toBe("thread.turn-start-requested"); expect(events[1]?.causationEventId).toBe(events[0]?.eventId ?? null);
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
}); });
}); });
-2
View File
@@ -14,7 +14,6 @@ import {
} from "./commandInvariants.ts"; } from "./commandInvariants.ts";
const nowIso = () => new Date().toISOString(); const nowIso = () => new Date().toISOString();
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = { const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"], eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
@@ -253,7 +252,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId, messageId: command.message.messageId,
...(command.model !== undefined ? { model: command.model } : {}), ...(command.model !== undefined ? { model: command.model } : {}),
...(command.effort !== undefined ? { effort: command.effort } : {}), ...(command.effort !== undefined ? { effort: command.effort } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
createdAt: command.createdAt, createdAt: command.createdAt,
}, },
}; };
+3 -4
View File
@@ -40,10 +40,9 @@ function decodeForEvent<A>(
eventType: OrchestrationEvent["type"], eventType: OrchestrationEvent["type"],
field: string, field: string,
): Effect.Effect<A, OrchestrationProjectorDecodeError> { ): Effect.Effect<A, OrchestrationProjectorDecodeError> {
return Effect.try({ return Schema.decodeUnknownEffect(schema)(value).pipe(
try: () => Schema.decodeUnknownSync(schema as any)(value), Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError), ) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
});
} }
function retainThreadMessagesAfterRevert( function retainThreadMessagesAfterRevert(
+1 -2
View File
@@ -17,7 +17,6 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -36,7 +35,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
export function makeServerProviderLayer(): Layer.Layer< export function makeServerProviderLayer(): Layer.Layer<
ProviderService, ProviderService,
ProviderUnsupportedError, unknown,
SqlClient.SqlClient | ServerConfig SqlClient.SqlClient | ServerConfig
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
+2 -3
View File
@@ -323,14 +323,14 @@ describe("WebSocket Server", () => {
async function createTestServer( async function createTestServer(
options: { options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>; persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>;
cwd?: string; cwd?: string;
autoBootstrapProjectFromCwd?: boolean; autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean; logWebSocketEvents?: boolean;
devUrl?: string; devUrl?: string;
authToken?: string; authToken?: string;
stateDir?: string; stateDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>; providerLayer?: Layer.Layer<ProviderService, unknown>;
open?: OpenShape; open?: OpenShape;
gitManager?: GitManagerShape; gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">; gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
@@ -959,7 +959,6 @@ describe("WebSocket Server", () => {
text: "hello", text: "hello",
attachments: [], attachments: [],
}, },
assistantDeliveryMode: "streaming",
createdAt, createdAt,
}); });
expect(startTurnResponse.error).toBeUndefined(); expect(startTurnResponse.error).toBeUndefined();
+20 -34
View File
@@ -66,14 +66,14 @@ export interface ServerShape {
*/ */
readonly start: Effect.Effect< readonly start: Effect.Effect<
http.Server, http.Server,
ServerLifecycleError, unknown,
Scope.Scope | ServerRuntimeServices | ServerConfig Scope.Scope | ServerRuntimeServices | ServerConfig
>; >;
/** /**
* Wait for process shutdown signals. * Wait for process shutdown signals.
*/ */
readonly stopSignal: Effect.Effect<void, never>; readonly stopSignal: Effect.Effect<unknown, never>;
} }
/** /**
@@ -165,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return< export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server, http.Server,
ServerLifecycleError, unknown, // TODO: This should not be unknown
Scope.Scope | ServerRuntimeServices | ServerConfig Scope.Scope | ServerRuntimeServices | ServerConfig
> { > {
const serverConfig = yield* ServerConfig; const serverConfig = yield* ServerConfig;
@@ -338,27 +338,21 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope); yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
if (autoBootstrapProjectFromCwd) { if (autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () { const snapshot = yield* projectionReadModelQuery.getSnapshot();
const snapshot = yield* projectionReadModelQuery.getSnapshot(); const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd); if (!existing) {
if (!existing) { const createdAt = new Date().toISOString();
const createdAt = new Date().toISOString(); const projectName = path.basename(cwd) || "project";
const projectName = path.basename(cwd) || "project"; yield* orchestrationEngine.dispatch({
yield* orchestrationEngine.dispatch({ type: "project.create",
type: "project.create", commandId: CommandId.makeUnsafe(crypto.randomUUID()),
commandId: CommandId.makeUnsafe(crypto.randomUUID()), projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()), title: projectName,
title: projectName, workspaceRoot: cwd,
workspaceRoot: cwd, defaultModel: "gpt-5-codex",
defaultModel: "gpt-5-codex", createdAt,
createdAt, });
}); }
}
}).pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
),
);
} }
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) { const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
@@ -395,13 +389,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: { case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body); const body = stripRequestTag(request.body);
return yield* Effect.tryPromise({ return yield* Effect.promise(() => searchWorkspaceEntries(body));
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
new RouteRequestError({
message: `Failed to search workspace entries: ${String(cause)}`,
}),
});
} }
case WS_METHODS.shellOpenInEditor: { case WS_METHODS.shellOpenInEditor: {
@@ -624,9 +612,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
); );
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents())); yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe( yield* NodeHttpServer.make(() => httpServer, listenOptions);
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* Effect.addFinalizer(() => yield* Effect.addFinalizer(() =>
Effect.all([ Effect.all([
-3
View File
@@ -11,9 +11,6 @@ const AppSettingsSchema = Schema.Struct({
Schema.withConstructorDefault(() => Option.some("")), Schema.withConstructorDefault(() => Option.some("")),
), ),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
}); });
export type AppSettings = typeof AppSettingsSchema.Type; export type AppSettings = typeof AppSettingsSchema.Type;
+78 -179
View File
@@ -53,7 +53,6 @@ import { truncateTitle } from "../truncateTitle";
import { import {
DEFAULT_THREAD_TERMINAL_ID, DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT, MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type ChatImageAttachment, type ChatImageAttachment,
type TurnDiffSummary, type TurnDiffSummary,
} from "../types"; } from "../types";
@@ -92,7 +91,6 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
import { CursorIcon, Icon } from "./Icons"; import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command"; import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl"; import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
@@ -107,7 +105,6 @@ import { Toggle } from "./ui/toggle";
import { SidebarTrigger } from "./ui/sidebar"; import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId } from "~/lib/utils"; import { newCommandId, newMessageId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi"; import { readNativeApi } from "~/nativeApi";
import { useAppSettings } from "../appSettings";
function formatMessageMeta(createdAt: string, duration: string | null): string { function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt); if (!duration) return formatTimestamp(createdAt);
@@ -190,8 +187,6 @@ type ComposerCommandItem =
description: string; description: string;
}; };
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
function readFileAsDataUrl(file: File): Promise<string> { function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
@@ -333,7 +328,6 @@ interface ChatViewProps {
export default function ChatView({ threadId }: ChatViewProps) { export default function ChatView({ threadId }: ChatViewProps) {
const { state, dispatch } = useStore(); const { state, dispatch } = useStore();
const { settings } = useAppSettings();
const navigate = useNavigate(); const navigate = useNavigate();
const rawSearch = useSearch({ const rawSearch = useSearch({
strict: false, strict: false,
@@ -347,9 +341,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]); const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false); const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null); const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]); const [isSending, setIsSending] = useState(false);
const [sendPhase, setSendPhase] = useState<SendPhase>("idle"); const [isConnecting, setIsConnecting] = useState(false);
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING); const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("local"); const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
@@ -403,9 +396,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL, activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
); );
const phase = derivePhase(activeThread?.session ?? null); const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle"; const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
const isPreparingWorktree = sendPhase === "preparing-worktree";
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString(); const nowIso = new Date(nowTick).toISOString();
const threadActivities = activeThread?.activities ?? []; const threadActivities = activeThread?.activities ?? [];
const workLogEntries = useMemo( const workLogEntries = useMemo(
@@ -425,21 +416,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => derivePendingApprovals(threadActivities), () => derivePendingApprovals(threadActivities),
[threadActivities], [threadActivities],
); );
const timelineMessages = useMemo(() => {
const serverMessages = activeThread?.messages ?? [];
if (optimisticUserMessages.length === 0) {
return serverMessages;
}
const serverIds = new Set(serverMessages.map((message) => message.id));
const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id));
if (pendingMessages.length === 0) {
return serverMessages;
}
return [...serverMessages, ...pendingMessages];
}, [activeThread?.messages, optimisticUserMessages]);
const timelineEntries = useMemo( const timelineEntries = useMemo(
() => deriveTimelineEntries(timelineMessages, workLogEntries), () => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
[timelineMessages, workLogEntries], [activeThread?.messages, workLogEntries],
); );
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread); useTurnDiffSummaries(activeThread);
@@ -636,21 +615,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => shortcutLabelForCommand(keybindings, "terminal.close"), () => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings], [keybindings],
); );
const diffPanelShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "diff.toggle"),
[keybindings],
);
const onToggleDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
replace: true,
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return diffOpen ? rest : { ...rest, diff: "1" };
},
});
}, [diffOpen, navigate, threadId]);
const envLocked = Boolean( const envLocked = Boolean(
activeThread && activeThread &&
@@ -980,7 +944,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [lastInvokedScriptByProjectId]); }, [lastInvokedScriptByProjectId]);
// Auto-scroll on new messages // Auto-scroll on new messages
const messageCount = timelineMessages.length; const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length; const workLogCount = workLogEntries.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => { const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current; const scrollContainer = messagesScrollRef.current;
@@ -1039,30 +1003,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerImagesRef.current = composerImages; composerImagesRef.current = composerImages;
}, [composerImages]); }, [composerImages]);
useEffect(() => {
if (!activeThread?.id) {
setOptimisticUserMessages([]);
return;
}
if (activeThread.messages.length === 0) {
return;
}
const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => {
const next = existing.filter((message) => !serverIds.has(message.id));
return next.length === existing.length ? existing : next;
});
}, [activeThread?.id, activeThread?.messages]);
useEffect(() => { useEffect(() => {
setComposerImages((existing) => { setComposerImages((existing) => {
revokePreviewUrls(existing); revokePreviewUrls(existing);
return []; return [];
}); });
setOptimisticUserMessages([]);
setPrompt(""); setPrompt("");
promptRef.current = ""; promptRef.current = "";
setSendPhase("idle"); setIsSending(false);
setComposerCursor(0); setComposerCursor(0);
setComposerHighlightedItemId(null); setComposerHighlightedItemId(null);
dragDepthRef.current = 0; dragDepthRef.current = 0;
@@ -1199,13 +1147,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
return; return;
} }
if (command === "diff.toggle") {
event.preventDefault();
event.stopPropagation();
onToggleDiff();
return;
}
const scriptId = projectScriptIdFromCommand(command); const scriptId = projectScriptIdFromCommand(command);
if (!scriptId || !activeProject) return; if (!scriptId || !activeProject) return;
const script = activeProject.scripts.find((entry) => entry.id === scriptId); const script = activeProject.scripts.find((entry) => entry.id === scriptId);
@@ -1227,7 +1168,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runProjectScript, runProjectScript,
splitTerminal, splitTerminal,
keybindings, keybindings,
onToggleDiff,
toggleTerminalVisibility, toggleTerminalVisibility,
]); ]);
@@ -1351,7 +1291,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi(); const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return; if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy || isConnecting) { if (phase === "running" || isSending || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return; return;
} }
@@ -1385,67 +1325,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsRevertingCheckpoint(false); setIsRevertingCheckpoint(false);
} }
}, },
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError], [activeThread, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
); );
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => { const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault(); e.preventDefault();
const api = readNativeApi(); const api = readNativeApi();
if (!api || !activeThread || isSendBusy || isConnecting) return; if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim(); const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return; if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return; if (!activeProject) return;
const threadIdForSend = activeThread.id;
const isFirstMessage = activeThread.messages.length === 0;
const baseBranchForWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
: null;
const composerImagesSnapshot = [...composerImages]; const composerImagesSnapshot = [...composerImages];
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
setOptimisticUserMessages((existing) => [
...existing,
{
id: messageIdForSend,
role: "user",
text: trimmed,
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
createdAt: messageCreatedAt,
streaming: false,
},
]);
setThreadError(threadIdForSend, null); // On first message: lock in branch + create worktree if needed.
promptRef.current = ""; if (
setPrompt(""); activeThread.messages.length === 0 &&
setComposerImages([]); activeThread.branch &&
setComposerCursor(0); envMode === "worktree" &&
setComposerHighlightedItemId(null); !activeThread.worktreePath
) {
let attemptedTurnStart = false; try {
try {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
setSendPhase("preparing-worktree");
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`; const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
const result = await createWorktreeMutation.mutateAsync({ const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd, cwd: activeProject.cwd,
branch: baseBranchForWorktree, branch: activeThread.branch,
newBranch, newBranch,
}); });
await api.orchestration.dispatchCommand({ await api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
threadId: threadIdForSend, threadId: activeThread.id,
branch: result.worktree.branch, branch: result.worktree.branch,
worktreePath: result.worktree.path, worktreePath: result.worktree.path,
}); });
@@ -1457,25 +1366,43 @@ export default function ChatView({ threadId }: ChatViewProps) {
rememberAsLastInvoked: false, rememberAsLastInvoked: false,
}); });
} }
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to create worktree",
});
return;
} }
}
// Auto-title from first message // Auto-title from first message
if (isFirstMessage) { if (activeThread.messages.length === 0) {
const titleSeed = const titleSeed =
trimmed || trimmed ||
(composerImagesSnapshot.length > 0 (composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}` ? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread"); : "New thread");
const title = truncateTitle(titleSeed); const title = truncateTitle(titleSeed);
if (api) {
await api.orchestration.dispatchCommand({ await api.orchestration.dispatchCommand({
type: "thread.meta.update", type: "thread.meta.update",
commandId: newCommandId(), commandId: newCommandId(),
threadId: threadIdForSend, threadId: activeThread.id,
title, title,
}); });
} }
}
setSendPhase("sending-turn"); setThreadError(activeThread.id, null);
promptRef.current = "";
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
setComposerHighlightedItemId(null);
setIsSending(true);
try {
const turnAttachments = await Promise.all( const turnAttachments = await Promise.all(
composerImagesSnapshot.map( composerImagesSnapshot.map(
async ( async (
@@ -1495,42 +1422,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
}), }),
), ),
); );
attemptedTurnStart = true;
await api.orchestration.dispatchCommand({ await api.orchestration.dispatchCommand({
type: "thread.turn.start", type: "thread.turn.start",
commandId: newCommandId(), commandId: newCommandId(),
threadId: threadIdForSend, threadId: activeThread.id,
message: { message: {
messageId: messageIdForSend, messageId: newMessageId(),
role: "user", role: "user",
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT, text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
attachments: turnAttachments, attachments: turnAttachments,
}, },
model: selectedModel || undefined, model: selectedModel || undefined,
effort: selectedEffort || undefined, effort: selectedEffort || undefined,
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered", createdAt: new Date().toISOString(),
createdAt: messageCreatedAt,
}); });
} catch (err) { } catch (err) {
if (
!attemptedTurnStart &&
promptRef.current.length === 0 &&
composerImagesRef.current.length === 0
) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
promptRef.current = trimmed;
setPrompt(trimmed);
setComposerImages(composerImagesSnapshot);
setComposerCursor(trimmed.length);
}
setThreadError( setThreadError(
threadIdForSend, activeThread.id,
err instanceof Error ? err.message : "Failed to send message.", err instanceof Error ? err.message : "Failed to send message.",
); );
} finally { } finally {
setSendPhase("idle"); setIsSending(false);
} }
}; };
@@ -1700,6 +1612,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => { const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
setExpandedImage(image); setExpandedImage(image);
}, []); }, []);
const onToggleDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return diffOpen ? rest : { ...rest, diff: "1" };
},
});
}, [diffOpen, navigate, threadId]);
const onOpenTurnDiff = useCallback( const onOpenTurnDiff = useCallback(
(turnId: TurnId, filePath?: string) => { (turnId: TurnId, filePath?: string) => {
void navigate({ void navigate({
@@ -1770,7 +1692,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
} }
keybindings={keybindings} keybindings={keybindings}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd} gitCwd={gitCwd}
diffOpen={diffOpen} diffOpen={diffOpen}
onRunProjectScript={(script) => { onRunProjectScript={(script) => {
@@ -1797,7 +1718,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onScroll={onMessagesScroll} onScroll={onMessagesScroll}
> >
<MessagesTimeline <MessagesTimeline
hasMessages={timelineMessages.length > 0} hasMessages={activeThread.messages.length > 0}
isWorking={isWorking} isWorking={isWorking}
scrollContainerRef={messagesScrollRef} scrollContainerRef={messagesScrollRef}
timelineEntries={timelineEntries} timelineEntries={timelineEntries}
@@ -1915,7 +1836,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Ask for follow-up changes or attach images" ? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use /model" : "Ask anything, @tag files/folders, or use /model"
} }
disabled={isConnecting} disabled={isSending || isConnecting}
/> />
</div> </div>
@@ -1961,9 +1882,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Right side: send / stop button */} {/* Right side: send / stop button */}
<div className="flex shrink-0 items-center gap-2"> <div className="flex shrink-0 items-center gap-2">
{isPreparingWorktree ? (
<span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
) : null}
{phase === "running" ? ( {phase === "running" ? (
<button <button
type="button" type="button"
@@ -1986,19 +1904,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit" type="submit"
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8" className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={ disabled={
isSendBusy || isConnecting || (!prompt.trim() && composerImages.length === 0) isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
} }
aria-label={ aria-label={
isConnecting isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
} }
> >
{isConnecting || isSendBusy ? ( {isConnecting || isSending ? (
<svg <svg
width="14" width="14"
height="14" height="14"
@@ -2131,7 +2043,6 @@ interface ChatHeaderProps {
activeProjectScripts: ProjectScript[] | undefined; activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null; preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig; keybindings: ResolvedKeybindingsConfig;
diffToggleShortcutLabel: string | null;
gitCwd: string | null; gitCwd: string | null;
diffOpen: boolean; diffOpen: boolean;
onRunProjectScript: (script: ProjectScript) => void; onRunProjectScript: (script: ProjectScript) => void;
@@ -2147,7 +2058,6 @@ const ChatHeader = memo(function ChatHeader({
activeProjectScripts, activeProjectScripts,
preferredScriptId, preferredScriptId,
keybindings, keybindings,
diffToggleShortcutLabel,
gitCwd, gitCwd,
diffOpen, diffOpen,
onRunProjectScript, onRunProjectScript,
@@ -2186,27 +2096,16 @@ const ChatHeader = memo(function ChatHeader({
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} /> <OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
)} )}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />} {activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
<Tooltip> <Toggle
<TooltipTrigger className="shrink-0"
render={ pressed={diffOpen}
<Toggle onPressedChange={onToggleDiff}
className="shrink-0" aria-label="Toggle diff panel"
pressed={diffOpen} variant="outline"
onPressedChange={onToggleDiff} size="xs"
aria-label="Toggle diff panel" >
variant="outline" <DiffIcon className="size-3" />
size="xs" </Toggle>
>
<DiffIcon className="size-3" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
</TooltipPopup>
</Tooltip>
</div> </div>
</div> </div>
); );
@@ -1,5 +1,5 @@
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts"; import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react"; import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons"; import { GitHubIcon } from "./Icons";
@@ -33,7 +33,6 @@ import { toastManager } from "~/components/ui/toast";
import { import {
gitBranchesQueryOptions, gitBranchesQueryOptions,
gitInitMutationOptions, gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions, gitPullMutationOptions,
gitRunStackedActionMutationOptions, gitRunStackedActionMutationOptions,
gitStatusQueryOptions, gitStatusQueryOptions,
@@ -169,10 +168,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
); );
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient })); const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning = const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isDefaultBranch = useMemo(() => { const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch; const branchName = gitStatusForActions?.branch;
if (!branchName) return false; if (!branchName) return false;
+14
View File
@@ -24,6 +24,7 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem"; const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))"; const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
const SIDEBAR_WIDTH_ICON = "3rem"; const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16; const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
type SidebarContextProps = { type SidebarContextProps = {
@@ -128,6 +129,19 @@ function SidebarProvider({
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open); return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen]); }, [isMobile, setOpen]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed". // We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes. // This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"; const state = open ? "expanded" : "collapsed";
-22
View File
@@ -10,7 +10,6 @@ import {
formatShortcutLabel, formatShortcutLabel,
isChatNewShortcut, isChatNewShortcut,
isChatNewLocalShortcut, isChatNewLocalShortcut,
isDiffToggleShortcut,
isOpenFavoriteEditorShortcut, isOpenFavoriteEditorShortcut,
isTerminalClearShortcut, isTerminalClearShortcut,
isTerminalCloseShortcut, isTerminalCloseShortcut,
@@ -92,11 +91,6 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.close", command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"), whenAst: whenIdentifier("terminalFocus"),
}, },
{
shortcut: modShortcut("d"),
command: "diff.toggle",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" }, { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" },
@@ -236,7 +230,6 @@ describe("shortcutLabelForCommand", () => {
it("returns labels for non-terminal commands", () => { it("returns labels for non-terminal commands", () => {
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O"); assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
assert.strictEqual( assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"), shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
"Ctrl+O", "Ctrl+O",
@@ -283,21 +276,6 @@ describe("chat/editor shortcuts", () => {
}), }),
); );
}); });
it("matches diff.toggle shortcut outside terminal focus", () => {
assert.isTrue(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
assert.isFalse(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
);
});
}); });
describe("cross-command precedence", () => { describe("cross-command precedence", () => {
-8
View File
@@ -198,14 +198,6 @@ export function isTerminalCloseShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.close", options); return matchesCommandShortcut(event, keybindings, "terminal.close", options);
} }
export function isDiffToggleShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
}
export function isChatNewShortcut( export function isChatNewShortcut(
event: ShortcutEventLike, event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig, keybindings: ResolvedKeybindingsConfig,
-33
View File
@@ -1,33 +0,0 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import {
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
} from "./gitReactQuery";
describe("gitMutationKeys", () => {
it("scopes stacked action keys by cwd", () => {
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
gitMutationKeys.runStackedAction("/repo/b"),
);
});
it("scopes pull keys by cwd", () => {
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
});
});
describe("git mutation options", () => {
const queryClient = new QueryClient();
it("attaches cwd-scoped mutation key for runStackedAction", () => {
const options = gitRunStackedActionMutationOptions({ cwd: "/repo/a", queryClient });
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
});
it("attaches cwd-scoped mutation key for pull", () => {
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
});
});
+1 -17
View File
@@ -1,6 +1,6 @@
import type { GitStackedAction } from "@t3tools/contracts"; import type { GitStackedAction } from "@t3tools/contracts";
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query"; import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
import { ensureNativeApi } from "../nativeApi"; import { ensureNativeApi } from "~/nativeApi";
const GIT_STATUS_STALE_TIME_MS = 5_000; const GIT_STATUS_STALE_TIME_MS = 5_000;
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000; const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
@@ -13,15 +13,6 @@ export const gitQueryKeys = {
branches: (cwd: string | null) => ["git", "branches", cwd] as const, branches: (cwd: string | null) => ["git", "branches", cwd] as const,
}; };
export const gitMutationKeys = {
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
createBranchAndCheckout: (cwd: string | null) =>
["git", "mutation", "create-branch-and-checkout", cwd] as const,
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
};
export function invalidateGitQueries(queryClient: QueryClient) { export function invalidateGitQueries(queryClient: QueryClient) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all }); return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
} }
@@ -60,7 +51,6 @@ export function gitBranchesQueryOptions(cwd: string | null) {
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) { export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
return mutationOptions({ return mutationOptions({
mutationKey: gitMutationKeys.init(input.cwd),
mutationFn: async () => { mutationFn: async () => {
const api = ensureNativeApi(); const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git init is unavailable."); if (!input.cwd) throw new Error("Git init is unavailable.");
@@ -77,7 +67,6 @@ export function gitCheckoutMutationOptions(input: {
queryClient: QueryClient; queryClient: QueryClient;
}) { }) {
return mutationOptions({ return mutationOptions({
mutationKey: gitMutationKeys.checkout(input.cwd),
mutationFn: async (branch: string) => { mutationFn: async (branch: string) => {
const api = ensureNativeApi(); const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git checkout is unavailable."); if (!input.cwd) throw new Error("Git checkout is unavailable.");
@@ -94,7 +83,6 @@ export function gitCreateBranchAndCheckoutMutationOptions(input: {
queryClient: QueryClient; queryClient: QueryClient;
}) { }) {
return mutationOptions({ return mutationOptions({
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
mutationFn: async (branch: string) => { mutationFn: async (branch: string) => {
const api = ensureNativeApi(); const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git branch creation is unavailable."); if (!input.cwd) throw new Error("Git branch creation is unavailable.");
@@ -112,7 +100,6 @@ export function gitRunStackedActionMutationOptions(input: {
queryClient: QueryClient; queryClient: QueryClient;
}) { }) {
return mutationOptions({ return mutationOptions({
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
mutationFn: async ({ mutationFn: async ({
action, action,
commitMessage, commitMessage,
@@ -136,7 +123,6 @@ export function gitRunStackedActionMutationOptions(input: {
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) { export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
return mutationOptions({ return mutationOptions({
mutationKey: gitMutationKeys.pull(input.cwd),
mutationFn: async () => { mutationFn: async () => {
const api = ensureNativeApi(); const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git pull is unavailable."); if (!input.cwd) throw new Error("Git pull is unavailable.");
@@ -165,7 +151,6 @@ export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClie
if (!cwd) throw new Error("Git worktree creation is unavailable."); if (!cwd) throw new Error("Git worktree creation is unavailable.");
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null }); return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
}, },
mutationKey: ["git", "mutation", "create-worktree"] as const,
onSettled: async () => { onSettled: async () => {
await invalidateGitQueries(input.queryClient); await invalidateGitQueries(input.queryClient);
}, },
@@ -179,7 +164,6 @@ export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClie
if (!cwd) throw new Error("Git worktree removal is unavailable."); if (!cwd) throw new Error("Git worktree removal is unavailable.");
return api.git.removeWorktree({ cwd, path, force }); return api.git.removeWorktree({ cwd, path, force });
}, },
mutationKey: ["git", "mutation", "remove-worktree"] as const,
onSettled: async () => { onSettled: async () => {
await invalidateGitQueries(input.queryClient); await invalidateGitQueries(input.queryClient);
}, },
+5 -16
View File
@@ -1,5 +1,8 @@
import { ThreadId } from "@t3tools/contracts"; import {
import { Outlet, createRootRouteWithContext, type ErrorComponentProps } from "@tanstack/react-router"; Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query"; import { QueryClient, useQueryClient } from "@tanstack/react-query";
@@ -10,7 +13,6 @@ import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQue
import { readNativeApi } from "../nativeApi"; import { readNativeApi } from "../nativeApi";
import { useStore } from "../store"; import { useStore } from "../store";
import { preferredTerminalEditor } from "../terminal-links"; import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi"; import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
import { providerQueryKeys } from "../lib/providerReactQuery"; import { providerQueryKeys } from "../lib/providerReactQuery";
@@ -168,18 +170,6 @@ function EventRouter() {
} }
void syncSnapshot(); void syncSnapshot();
}); });
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
if (hasRunningSubprocess === null) {
return;
}
dispatch({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe(event.threadId),
terminalId: event.terminalId,
hasRunningSubprocess,
});
});
const unsubWelcome = onServerWelcome(() => { const unsubWelcome = onServerWelcome(() => {
void syncSnapshot(); void syncSnapshot();
}); });
@@ -228,7 +218,6 @@ function EventRouter() {
return () => { return () => {
disposed = true; disposed = true;
unsubDomainEvent(); unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome(); unsubWelcome();
unsubServerConfigUpdated(); unsubServerConfigUpdated();
}; };
-43
View File
@@ -237,49 +237,6 @@ function SettingsRouteView() {
</div> </div>
</section> </section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Responses</h2>
<p className="mt-1 text-xs text-muted-foreground">
Control how assistant output is rendered during a turn.
</p>
</div>
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
<div>
<p className="text-sm font-medium text-foreground">Stream assistant messages</p>
<p className="text-xs text-muted-foreground">
Show token-by-token output while a response is in progress.
</p>
</div>
<Switch
checked={settings.enableAssistantStreaming}
onCheckedChange={(checked) =>
updateSettings({
enableAssistantStreaming: Boolean(checked),
})
}
aria-label="Stream assistant messages"
/>
</div>
{settings.enableAssistantStreaming !== defaults.enableAssistantStreaming ? (
<div className="mt-3 flex justify-end">
<Button
size="xs"
variant="outline"
onClick={() =>
updateSettings({
enableAssistantStreaming: defaults.enableAssistantStreaming,
})
}
>
Restore default
</Button>
</div>
) : null}
</section>
<section className="rounded-2xl border border-border bg-card p-5"> <section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4"> <div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Keybindings</h2> <h2 className="text-sm font-medium text-foreground">Keybindings</h2>
-59
View File
@@ -92,62 +92,3 @@ describe("store reducer", () => {
expect(next).toEqual(initialState); expect(next).toEqual(initialState);
}); });
}); });
describe("store terminal activity reducer", () => {
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
});
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
runningTerminalIds: ["alt"],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: false,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
it("ignores activity events for unknown terminal ids", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "missing",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
});
-35
View File
@@ -35,12 +35,6 @@ type Action =
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string } | { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId } | { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] } | { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
| {
type: "SET_THREAD_TERMINAL_ACTIVITY";
threadId: ThreadId;
terminalId: string;
hasRunningSubprocess: boolean;
}
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId } | { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean } | { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number } | { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
@@ -376,27 +370,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
}); });
} }
function setThreadTerminalActivity(
thread: Thread,
terminalId: string,
hasRunningSubprocess: boolean,
): Thread {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(terminalId)) {
return normalizedThread;
}
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
} else {
runningTerminalIds.delete(terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIds],
});
}
// ── Reducer ────────────────────────────────────────────────────────── // ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState { export function reducer(state: AppState, action: Action): AppState {
@@ -563,14 +536,6 @@ export function reducer(state: AppState, action: Action): AppState {
), ),
}; };
case "SET_THREAD_TERMINAL_ACTIVITY":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
),
};
case "TOGGLE_THREAD_TERMINAL": case "TOGGLE_THREAD_TERMINAL":
return { return {
...state, ...state,
-71
View File
@@ -1,71 +0,0 @@
import { describe, expect, it } from "vitest";
import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts";
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
const snapshot: TerminalSessionSnapshot = {
threadId: "thread-1",
terminalId: "default",
cwd: "/tmp",
status: "running",
pid: 1234,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-01-01T00:00:00.000Z",
};
function eventBase() {
return {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-01-01T00:00:00.000Z",
};
}
describe("terminalRunningSubprocessFromEvent", () => {
it("returns the subprocess flag for terminal activity events", () => {
const active = terminalRunningSubprocessFromEvent({
...eventBase(),
type: "activity",
hasRunningSubprocess: true,
});
const idle = terminalRunningSubprocessFromEvent({
...eventBase(),
type: "activity",
hasRunningSubprocess: false,
});
expect(active).toBe(true);
expect(idle).toBe(false);
});
it("clears running state when a terminal session starts/restarts/exits", () => {
const events: TerminalEvent[] = [
{ ...eventBase(), type: "started", snapshot },
{ ...eventBase(), type: "restarted", snapshot },
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
];
for (const event of events) {
expect(terminalRunningSubprocessFromEvent(event)).toBe(false);
}
});
it("ignores non-activity terminal events", () => {
expect(
terminalRunningSubprocessFromEvent({
...eventBase(),
type: "output",
data: "hello",
}),
).toBeNull();
expect(
terminalRunningSubprocessFromEvent({
...eventBase(),
type: "error",
message: "oops",
}),
).toBeNull();
});
});
-14
View File
@@ -1,14 +0,0 @@
import type { TerminalEvent } from "@t3tools/contracts";
export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolean | null {
switch (event.type) {
case "activity":
return event.hasRunningSubprocess;
case "started":
case "restarted":
case "exited":
return false;
default:
return null;
}
}
@@ -35,12 +35,6 @@ it.effect("parses keybinding rules", () =>
}); });
assert.strictEqual(parsedClose.command, "terminal.close"); assert.strictEqual(parsedClose.command, "terminal.close");
const parsedDiffToggle = yield* decode(KeybindingRule, {
key: "mod+d",
command: "diff.toggle",
});
assert.strictEqual(parsedDiffToggle.command, "diff.toggle");
const parsedLocal = yield* decode(KeybindingRule, { const parsedLocal = yield* decode(KeybindingRule, {
key: "mod+shift+n", key: "mod+shift+n",
command: "chat.newLocal", command: "chat.newLocal",
-1
View File
@@ -14,7 +14,6 @@ export const STATIC_KEYBINDING_COMMANDS = [
"terminal.split", "terminal.split",
"terminal.new", "terminal.new",
"terminal.close", "terminal.close",
"diff.toggle",
"chat.new", "chat.new",
"chat.newLocal", "chat.newLocal",
"editor.openFavorite", "editor.openFavorite",
-4
View File
@@ -46,8 +46,6 @@ export const ProviderSandboxMode = Schema.Literals([
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type; export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const ProviderRequestKind = Schema.Literals(["command", "file-change"]); export const ProviderRequestKind = Schema.Literals(["command", "file-change"]);
export type ProviderRequestKind = typeof ProviderRequestKind.Type; export type ProviderRequestKind = typeof ProviderRequestKind.Type;
export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]);
export type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type;
export const ProviderApprovalDecision = Schema.Literals([ export const ProviderApprovalDecision = Schema.Literals([
"accept", "accept",
"acceptForSession", "acceptForSession",
@@ -281,7 +279,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
}), }),
model: Schema.optional(TrimmedNonEmptyString), model: Schema.optional(TrimmedNonEmptyString),
effort: Schema.optional(TrimmedNonEmptyString), effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
createdAt: IsoDateTime, createdAt: IsoDateTime,
}); });
@@ -495,7 +492,6 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
messageId: MessageId, messageId: MessageId,
model: Schema.optional(TrimmedNonEmptyString), model: Schema.optional(TrimmedNonEmptyString),
effort: Schema.optional(TrimmedNonEmptyString), effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
createdAt: IsoDateTime, createdAt: IsoDateTime,
}); });
+2 -3
View File
@@ -154,13 +154,12 @@ export function parseDevRunnerArgs(rawArgs) {
function resolveStateDir(env, envOverrides) { function resolveStateDir(env, envOverrides) {
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim(); const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
if (overrideValue) { if (overrideValue) {
// Resolve relative paths against cwd (monorepo root) before turbo changes directories return overrideValue;
return path.resolve(overrideValue);
} }
const envValue = env?.T3CODE_STATE_DIR?.trim(); const envValue = env?.T3CODE_STATE_DIR?.trim();
if (envValue) { if (envValue) {
return path.resolve(envValue); return envValue;
} }
return DEFAULT_DEV_STATE_DIR; return DEFAULT_DEV_STATE_DIR;
-1
View File
@@ -30,7 +30,6 @@
}, },
"test": { "test": {
"dependsOn": ["^build"], "dependsOn": ["^build"],
"cache": false,
"outputs": [] "outputs": []
} }
} }