Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eca89790d4 | ||
|
|
f9dab13472 | ||
|
|
4babb1a859 | ||
|
|
75533fbd40 | ||
|
|
fd98835834 | ||
|
|
c6dc7c6524 | ||
|
|
a04e3561ed | ||
|
|
dd51d4faec | ||
|
|
e21687300e | ||
|
|
c97c6b7836 | ||
|
|
59b0527c38 | ||
|
|
b74c7a79ab | ||
|
|
f772720d8c | ||
|
|
0763a35fbc | ||
|
|
e1c33dcd33 | ||
|
|
0a902790ca | ||
|
|
0837c8b639 | ||
|
|
5a90b6be9c | ||
|
|
42675571c9 | ||
|
|
e9f00f65ca | ||
|
|
04b95e37c5 | ||
|
|
5820e1b6ff | ||
|
|
8c904ffe34 | ||
|
|
9fa9cb4b31 |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: btca-cli
|
||||
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
|
||||
---
|
||||
|
||||
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
|
||||
|
||||
For example, assuming you have a resource named `codex`, you can ask questions like:
|
||||
|
||||
```bash
|
||||
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
|
||||
```
|
||||
|
||||
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
|
||||
|
||||
New resources can be created if the ones you need do not yet exist.
|
||||
|
||||
```bash
|
||||
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
|
||||
```
|
||||
@@ -1,3 +0,0 @@
|
||||
interface:
|
||||
display_name: "BTCA CLI"
|
||||
short_description: "Help with BTCA CLI setup and usage workflows"
|
||||
@@ -22,6 +22,8 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -45,6 +47,13 @@ jobs:
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -239,7 +248,7 @@ jobs:
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
@@ -260,7 +269,8 @@ jobs:
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
|
||||
@@ -8,10 +8,10 @@ T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Clau
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
|
||||
```bash
|
||||
npx t3@alpha
|
||||
npx t3
|
||||
```
|
||||
|
||||
Use can also just install the desktop app (it's cooler).
|
||||
You can also just install the desktop app. It's cooler.
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
|
||||
@@ -21,4 +21,4 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Discord link coming soon.
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -2,24 +2,12 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
- [ ] Thread archiving
|
||||
- [x] Selecting folder should instantly create project
|
||||
- [ ] New projects should go on top
|
||||
- [ ] Projects should be sorted by latest thread update
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
|
||||
@@ -725,7 +727,10 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.allowPrerelease = app.getVersion().includes("-");
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 414 B |
Binary file not shown.
|
After Width: | Height: | Size: 662 B |
Binary file not shown.
|
Before Width: | Height: | Size: 279 KiB After Width: | Height: | Size: 9.9 KiB |
@@ -12,8 +12,10 @@
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<link rel="icon" type="image/png" href="/icon.png" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<title>T3 Code</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
|
||||
@@ -316,6 +316,59 @@ describe("startSession", () => {
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const versionCheck = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {
|
||||
throw new Error(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
expect(versionCheck).toHaveBeenCalledTimes(1);
|
||||
expect(events).toEqual([
|
||||
{
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message:
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
versionCheck.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
|
||||
@@ -22,6 +22,12 @@ import {
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -138,6 +144,8 @@ export interface CodexThreadSnapshot {
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -535,6 +543,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
...(codexHomePath ? { homePath: codexHomePath } : {}),
|
||||
});
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
@@ -1320,6 +1333,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
assertSupportedCodexCliVersion(input);
|
||||
}
|
||||
|
||||
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
|
||||
context.session = {
|
||||
...context.session,
|
||||
@@ -1500,6 +1521,51 @@ function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||
};
|
||||
}
|
||||
|
||||
function assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
const result = spawnSync(input.binaryPath, ["--version"], {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
timeout: CODEX_VERSION_CHECK_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
const lower = result.error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("command not found") ||
|
||||
lower.includes("not found")
|
||||
) {
|
||||
throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const stdout = result.stdout ?? "";
|
||||
const stderr = result.stderr ?? "";
|
||||
if (result.status !== 0) {
|
||||
const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`;
|
||||
throw new Error(`Codex CLI version check failed. ${detail}`);
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
throw new Error(formatCodexCliUpgradeMessage(parsedVersion));
|
||||
}
|
||||
}
|
||||
|
||||
function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
|
||||
return undefined;
|
||||
|
||||
@@ -654,7 +654,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let fetchStarted = false;
|
||||
let releaseFetch: () => void = () => undefined;
|
||||
let releaseFetch!: () => void;
|
||||
const waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { CheckpointReactor, type CheckpointReactorShape } from "../Services/Chec
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -144,6 +145,8 @@ const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
|
||||
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
|
||||
) {
|
||||
@@ -184,6 +187,14 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
yield* Effect.logDebug("checkpoint capture skipped for non-git workspace", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
cwd: checkpointCwd,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -319,6 +330,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -378,6 +392,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -425,6 +442,15 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Checkpoints are unavailable because this project is not a git repository.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
|
||||
@@ -111,81 +111,6 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("seeds branched thread history during thread creation", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-branch-seed",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-branch-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Branch of Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: "feature/source",
|
||||
worktreePath: null,
|
||||
seedMessages: [
|
||||
{
|
||||
messageId: asMessageId("msg-seed-user"),
|
||||
role: "user",
|
||||
text: "original question",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
messageId: asMessageId("msg-seed-assistant"),
|
||||
role: "assistant",
|
||||
text: "original answer",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:01.000Z",
|
||||
updatedAt: "2026-02-01T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = await system.run(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === "thread-branch-seed");
|
||||
expect(thread?.messages.map((message) => message.text)).toEqual([
|
||||
"original question",
|
||||
"original answer",
|
||||
]);
|
||||
expect(thread?.messages.every((message) => message.turnId === null)).toBe(true);
|
||||
expect(thread?.session).toBeNull();
|
||||
|
||||
const events = await system.run(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
"thread.message-sent",
|
||||
"thread.message-sent",
|
||||
]);
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -112,6 +116,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -122,9 +133,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||
const provider = createProviderServiceHarness();
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -152,7 +168,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
@@ -507,6 +509,22 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
@@ -1041,7 +1059,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
|
||||
@@ -144,7 +144,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const threadCreatedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -165,32 +165,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
const seedMessageEvents: ReadonlyArray<Omit<OrchestrationEvent, "sequence">> =
|
||||
command.seedMessages?.map((message) => ({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.message-sent" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: message.messageId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.updatedAt,
|
||||
},
|
||||
})) ?? [];
|
||||
|
||||
return seedMessageEvents.length > 0
|
||||
? [threadCreatedEvent, ...seedMessageEvents]
|
||||
: threadCreatedEvent;
|
||||
}
|
||||
|
||||
case "thread.delete": {
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
@@ -20,12 +17,12 @@ export function fixPath(): void {
|
||||
}
|
||||
|
||||
export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
const { join, sep } = yield* Path.Path;
|
||||
const { join } = yield* Path.Path;
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith(`~${sep}`)) {
|
||||
return join(OS.homedir(), input.slice(sep.length));
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
|
||||
@@ -85,6 +85,28 @@ it.effect("returns unavailable when codex is missing", () =>
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
|
||||
@@ -13,9 +13,14 @@ import type {
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { Array, Effect, Fiber, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
@@ -247,6 +252,18 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
};
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
@@ -295,9 +312,13 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatus = yield* checkCodexProviderStatus;
|
||||
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.map(Array.of),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
getStatuses: Fiber.join(codexStatusFiber),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -436,13 +436,17 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
return session;
|
||||
}
|
||||
|
||||
return {
|
||||
...session,
|
||||
...(session.resumeCursor === undefined && binding.resumeCursor !== undefined
|
||||
? { resumeCursor: binding.resumeCursor }
|
||||
: {}),
|
||||
...(binding.runtimeMode !== undefined ? { runtimeMode: binding.runtimeMode } : {}),
|
||||
};
|
||||
const overrides: {
|
||||
resumeCursor?: ProviderSession["resumeCursor"];
|
||||
runtimeMode?: ProviderSession["runtimeMode"];
|
||||
} = {};
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
overrides.resumeCursor = binding.resumeCursor;
|
||||
}
|
||||
if (binding.runtimeMode !== undefined) {
|
||||
overrides.runtimeMode = binding.runtimeMode;
|
||||
}
|
||||
return Object.assign({}, session, overrides);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
|
||||
|
||||
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
|
||||
|
||||
interface ParsedSemver {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly prerelease: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
function normalizeCodexVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
}
|
||||
|
||||
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
|
||||
}
|
||||
|
||||
function parseSemver(version: string): ParsedSemver | null {
|
||||
const normalized = normalizeCodexVersion(version);
|
||||
const [main = "", prerelease] = normalized.split("-", 2);
|
||||
const segments = main.split(".");
|
||||
if (segments.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [majorSegment, minorSegment, patchSegment] = segments;
|
||||
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const major = Number.parseInt(majorSegment, 10);
|
||||
const minor = Number.parseInt(minorSegment, 10);
|
||||
const patch = Number.parseInt(patchSegment, 10);
|
||||
if (![major, minor, patch].every(Number.isInteger)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = /^\d+$/.test(left);
|
||||
const rightNumeric = /^\d+$/.test(right);
|
||||
|
||||
if (leftNumeric && rightNumeric) {
|
||||
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
|
||||
}
|
||||
if (leftNumeric) {
|
||||
return -1;
|
||||
}
|
||||
if (rightNumeric) {
|
||||
return 1;
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareCodexCliVersions(left: string, right: string): number {
|
||||
const parsedLeft = parseSemver(left);
|
||||
const parsedRight = parseSemver(right);
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
if (parsedLeft.major !== parsedRight.major) {
|
||||
return parsedLeft.major - parsedRight.major;
|
||||
}
|
||||
if (parsedLeft.minor !== parsedRight.minor) {
|
||||
return parsedLeft.minor - parsedRight.minor;
|
||||
}
|
||||
if (parsedLeft.patch !== parsedRight.patch) {
|
||||
return parsedLeft.patch - parsedRight.patch;
|
||||
}
|
||||
|
||||
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (parsedLeft.prerelease.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
if (parsedRight.prerelease.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftIdentifier = parsedLeft.prerelease[index];
|
||||
const rightIdentifier = parsedRight.prerelease[index];
|
||||
if (leftIdentifier === undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (rightIdentifier === undefined) {
|
||||
return 1;
|
||||
}
|
||||
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function parseCodexCliVersion(output: string): string | null {
|
||||
const match = CODEX_VERSION_PATTERN.exec(output);
|
||||
if (!match?.[1]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = parseSemver(match[1]);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeCodexVersion(match[1]);
|
||||
}
|
||||
|
||||
export function isCodexCliVersionSupported(version: string): boolean {
|
||||
return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
|
||||
}
|
||||
|
||||
export function formatCodexCliUpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
|
||||
}
|
||||
@@ -1150,7 +1150,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
|
||||
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
||||
let release: () => void = () => {};
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
@@ -1108,13 +1108,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-diff-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-diff-project-create",
|
||||
projectId: "project-diff",
|
||||
title: "Diff Project",
|
||||
workspaceRoot: "/tmp/ws-diff-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
@@ -1143,72 +1144,6 @@ describe("WebSocket Server", () => {
|
||||
expect(response.error?.message).toContain("exceeds current turn count");
|
||||
});
|
||||
|
||||
it("returns seeded thread messages in snapshots after thread creation", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-seed-project-create",
|
||||
projectId: "project-seed",
|
||||
title: "Seed Project",
|
||||
workspaceRoot: "/tmp/ws-seed-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
|
||||
const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "thread.create",
|
||||
commandId: "cmd-seed-thread-create",
|
||||
threadId: "thread-seed",
|
||||
projectId: "project-seed",
|
||||
title: "Seed Thread",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
seedMessages: [
|
||||
{
|
||||
messageId: "msg-seed-1",
|
||||
role: "user",
|
||||
text: "seeded question",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
messageId: "msg-seed-2",
|
||||
role: "assistant",
|
||||
text: "seeded answer",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:01.000Z",
|
||||
updatedAt: "2026-02-01T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
createdAt,
|
||||
});
|
||||
expect(createThreadResponse.error).toBeUndefined();
|
||||
|
||||
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
||||
expect(snapshotResponse.error).toBeUndefined();
|
||||
const snapshot = snapshotResponse.result as {
|
||||
threads: Array<{ id: string; messages: Array<{ text: string }> }>;
|
||||
};
|
||||
const thread = snapshot.threads.find((entry) => entry.id === "thread-seed");
|
||||
expect(thread?.messages.map((message) => message.text)).toEqual([
|
||||
"seeded question",
|
||||
"seeded answer",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps orchestration domain push behavior for provider runtime events", async () => {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
|
||||
@@ -1252,13 +1187,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-ws-project-create",
|
||||
projectId: "project-1",
|
||||
title: "WS Project",
|
||||
workspaceRoot: "/tmp/ws-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
WebSocketRequest,
|
||||
WsPush,
|
||||
WsResponse,
|
||||
ServerProviderStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ import {
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { expandHomePath } from "./os-jank.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -194,6 +196,13 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
|
||||
function messageFromCause(cause: Cause.Cause<unknown>): string {
|
||||
const squashed = Cause.squash(cause);
|
||||
const message =
|
||||
squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
|
||||
return message.length > 0 ? message : Cause.pretty(cause);
|
||||
}
|
||||
|
||||
export type ServerCoreRuntimeServices =
|
||||
| OrchestrationEngineService
|
||||
| ProjectionSnapshotQuery
|
||||
@@ -260,8 +269,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
),
|
||||
);
|
||||
|
||||
const providerStatuses = yield* providerHealth.getStatuses;
|
||||
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const logger = createLogger("ws");
|
||||
|
||||
@@ -298,6 +305,41 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
|
||||
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (
|
||||
input.command.type === "project.meta.update" &&
|
||||
input.command.workspaceRoot !== undefined
|
||||
) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type !== "thread.turn.start") {
|
||||
return input.command as OrchestrationCommand;
|
||||
}
|
||||
@@ -574,6 +616,23 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const subscriptionsScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
|
||||
|
||||
// Push updated provider statuses to connected clients once background health checks finish.
|
||||
let providers: ReadonlyArray<ServerProviderStatus> = [];
|
||||
yield* providerHealth.getStatuses.pipe(
|
||||
Effect.flatMap((statuses) => {
|
||||
providers = statuses;
|
||||
return broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: [],
|
||||
providers: statuses,
|
||||
},
|
||||
});
|
||||
}),
|
||||
Effect.forkIn(subscriptionsScope),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
@@ -588,7 +647,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
providers,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
@@ -658,7 +717,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
}
|
||||
|
||||
const runPromise = yield* Effect.map(Effect.services<never>(), Effect.runPromiseWith);
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(onTerminalEvent(event)),
|
||||
@@ -837,7 +899,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
providers,
|
||||
availableEditors,
|
||||
};
|
||||
|
||||
@@ -873,7 +935,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (request._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: "unknown",
|
||||
error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
|
||||
error: { message: `Invalid request format: ${messageFromCause(request.cause)}` },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
@@ -883,7 +945,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (result._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: request.value.id,
|
||||
error: { message: Cause.pretty(result.cause) },
|
||||
error: { message: messageFromCause(result.cause) },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
@@ -28,6 +28,27 @@ import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
{ hasError: boolean }
|
||||
> {
|
||||
constructor(props: { fallback: ReactNode; children: ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
override render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
@@ -99,6 +120,14 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
return getHighlighterPromise("text");
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
@@ -179,10 +208,14 @@ function SuspenseShikiCodeBlock({
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch {
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
@@ -235,14 +268,16 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</CodeHighlightErrorBoundary>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -68,6 +67,7 @@ import {
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findLatestProposedPlan,
|
||||
type PendingApproval,
|
||||
@@ -109,8 +109,6 @@ import {
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { buildBootstrapInput, resolveTurnBootstrapMessages } from "../historyBootstrap";
|
||||
import { buildTemporaryWorktreeBranchName } from "../worktreeBranches";
|
||||
import {
|
||||
buildTurnDiffTree,
|
||||
summarizeTurnDiffStats,
|
||||
@@ -137,7 +135,6 @@ import {
|
||||
DiffIcon,
|
||||
EllipsisIcon,
|
||||
FolderClosedIcon,
|
||||
GitBranchIcon,
|
||||
LockIcon,
|
||||
LockOpenIcon,
|
||||
Undo2Icon,
|
||||
@@ -190,11 +187,6 @@ import {
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
branchConversationThread,
|
||||
createBranchedThreadWorktree,
|
||||
selectBranchedMessages,
|
||||
} from "./threadBranching";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
@@ -232,6 +224,29 @@ function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
return `${formatTimestamp(createdAt)} • ${duration}`;
|
||||
}
|
||||
|
||||
function formatWorkingTimer(startIso: string, endIso: string): string | null {
|
||||
const startedAtMs = Date.parse(startIso);
|
||||
const endedAtMs = Date.parse(endIso);
|
||||
if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 60) {
|
||||
return `${elapsedSeconds}s`;
|
||||
}
|
||||
|
||||
const hours = Math.floor(elapsedSeconds / 3600);
|
||||
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
|
||||
const seconds = elapsedSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
|
||||
}
|
||||
|
||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||
const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
@@ -249,6 +264,7 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
||||
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
||||
@@ -426,6 +442,12 @@ function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
function cloneComposerImageForRetry(image: ComposerImageAttachment): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
@@ -586,7 +608,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const bootstrapMessages = composerDraft.bootstrapMessages;
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
@@ -596,7 +617,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
(store) => store.setInteractionMode,
|
||||
);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const setBootstrapMessages = useComposerDraftStore((store) => store.setBootstrapMessages);
|
||||
const setComposerDraftCodexFastMode = useComposerDraftStore((store) => store.setCodexFastMode);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
@@ -623,6 +643,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
||||
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
@@ -797,11 +818,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const selectedEffort = composerDraft.effort ?? getDefaultReasoningEffort(selectedProvider);
|
||||
const turnBootstrapMessages = resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: bootstrapMessages,
|
||||
threadMessages: activeThread?.messages ?? [],
|
||||
providerThreadId: activeThread?.codexThreadId ?? null,
|
||||
});
|
||||
const selectedCodexFastModeEnabled =
|
||||
selectedProvider === "codex" ? composerDraft.codexFastMode : false;
|
||||
const selectedModelOptionsForDispatch = useMemo(() => {
|
||||
@@ -847,6 +863,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
sendStartedAt,
|
||||
);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
@@ -1002,17 +1023,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
|
||||
}, []);
|
||||
const serverMessages = activeThread?.messages;
|
||||
const displayMessages = useMemo(() => {
|
||||
if (serverMessages && serverMessages.length > 0) {
|
||||
return serverMessages;
|
||||
}
|
||||
if (bootstrapMessages.length > 0 && (activeThread?.codexThreadId ?? null) === null) {
|
||||
return bootstrapMessages;
|
||||
}
|
||||
return serverMessages ?? [];
|
||||
}, [activeThread?.codexThreadId, bootstrapMessages, serverMessages]);
|
||||
const timelineMessages = useMemo(() => {
|
||||
const messages = displayMessages;
|
||||
const messages = serverMessages ?? [];
|
||||
const serverMessagesWithPreviewHandoff =
|
||||
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
|
||||
? messages
|
||||
@@ -1063,7 +1075,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return serverMessagesWithPreviewHandoff;
|
||||
}
|
||||
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
|
||||
}, [displayMessages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
|
||||
}, [serverMessages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
|
||||
const timelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
|
||||
@@ -1309,7 +1321,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(displayMessages.length > 0 ||
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const hasReachedTerminalLimit = terminalState.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
@@ -1961,6 +1973,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return [];
|
||||
});
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerCursor(promptRef.current.length);
|
||||
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
|
||||
@@ -2100,6 +2113,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
|
||||
setSendStartedAt((current) => current ?? new Date().toISOString());
|
||||
setSendPhase(nextPhase);
|
||||
}, []);
|
||||
|
||||
const resetSendPhase = useCallback(() => {
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (sendPhase === "idle") {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
phase === "running" ||
|
||||
activePendingApproval !== null ||
|
||||
activePendingUserInput !== null ||
|
||||
activeThread?.error
|
||||
) {
|
||||
resetSendPhase();
|
||||
}
|
||||
}, [
|
||||
activePendingApproval,
|
||||
activePendingUserInput,
|
||||
activeThread?.error,
|
||||
phase,
|
||||
resetSendPhase,
|
||||
sendPhase,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
|
||||
@@ -2409,7 +2453,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const messageIdForSend = newMessageId();
|
||||
@@ -2460,7 +2504,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await (async () => {
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
if (baseBranchForWorktree) {
|
||||
setSendPhase("preparing-worktree");
|
||||
beginSendPhase("preparing-worktree");
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
@@ -2499,14 +2543,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
const title = truncateTitle(titleSeed);
|
||||
const promptTextForSend =
|
||||
turnBootstrapMessages.length > 0 && (activeThread?.codexThreadId ?? null) === null
|
||||
? buildBootstrapInput(
|
||||
turnBootstrapMessages,
|
||||
trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
).text
|
||||
: (trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT);
|
||||
let threadCreateModel: ModelSlug =
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
@@ -2573,7 +2609,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}
|
||||
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
const turnAttachments = await turnAttachmentsPromise;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
@@ -2582,7 +2618,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
message: {
|
||||
messageId: messageIdForSend,
|
||||
role: "user",
|
||||
text: promptTextForSend,
|
||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
model: selectedModel || undefined,
|
||||
@@ -2635,7 +2671,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
if (!turnStartSucceeded) {
|
||||
resetSendPhase();
|
||||
}
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
@@ -2822,7 +2860,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
setThreadError(threadIdForSend, null);
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -2871,7 +2909,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
} catch (err) {
|
||||
setOptimisticUserMessages((existing) =>
|
||||
existing.filter((message) => message.id !== messageIdForSend),
|
||||
@@ -2881,16 +2918,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
err instanceof Error ? err.message : "Failed to send plan follow-up.",
|
||||
);
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
resetSendPhase();
|
||||
}
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
@@ -2928,10 +2967,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
const finish = () => {
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
resetSendPhase();
|
||||
};
|
||||
|
||||
await api.orchestration
|
||||
@@ -3004,10 +3043,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
@@ -3309,50 +3350,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
void onRevertToTurnCount(targetTurnCount);
|
||||
};
|
||||
const onBranchAssistantMessage = useCallback(
|
||||
(messageId: MessageId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThread) return;
|
||||
|
||||
void branchConversationThread({
|
||||
api,
|
||||
thread: activeThread,
|
||||
seedMessages: selectBranchedMessages({
|
||||
messages: displayMessages,
|
||||
targetMessageId: messageId,
|
||||
}),
|
||||
projectCwd: activeProject?.cwd ?? null,
|
||||
createWorktree: ({ cwd, branch }) =>
|
||||
createBranchedThreadWorktree({
|
||||
createWorktree: (args) => createWorktreeMutation.mutateAsync(args),
|
||||
cwd,
|
||||
branch,
|
||||
}),
|
||||
syncServerReadModel,
|
||||
setBootstrapMessages,
|
||||
navigateToThread: (threadId) =>
|
||||
navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
}),
|
||||
}).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to branch conversation",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
},
|
||||
[
|
||||
activeProject?.cwd,
|
||||
activeThread,
|
||||
createWorktreeMutation,
|
||||
displayMessages,
|
||||
navigate,
|
||||
setBootstrapMessages,
|
||||
syncServerReadModel,
|
||||
],
|
||||
);
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
@@ -3393,6 +3390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThreadId={activeThread.id}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
@@ -3436,8 +3434,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={!latestTurnSettled}
|
||||
activeTurnStartedAt={activeLatestTurn?.startedAt ?? null}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
scrollContainer={messagesScrollElement}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
@@ -3449,7 +3447,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
onRevertUserMessage={onRevertUserMessage}
|
||||
onBranchAssistantMessage={onBranchAssistantMessage}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
@@ -3467,7 +3464,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
data-chat-composer-form="true"
|
||||
>
|
||||
<div
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45 ${
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border"
|
||||
}`}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
@@ -3974,6 +3971,7 @@ interface ChatHeaderProps {
|
||||
activeThreadId: ThreadId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isGitRepo: boolean;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -3992,6 +3990,7 @@ const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isGitRepo,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -4020,6 +4019,11 @@ const ChatHeader = memo(function ChatHeader({
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
@@ -4050,15 +4054,18 @@ const ChatHeader = memo(function ChatHeader({
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!isGitRepo}
|
||||
>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
{!isGitRepo
|
||||
? "Diff panel is unavailable because this project is not a git repository."
|
||||
: diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -4691,7 +4698,6 @@ interface MessagesTimelineProps {
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
onBranchAssistantMessage: (messageId: MessageId) => void;
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
markdownCwd: string | undefined;
|
||||
@@ -4746,7 +4752,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onOpenTurnDiff,
|
||||
revertTurnCountByUserMessageId,
|
||||
onRevertUserMessage,
|
||||
onBranchAssistantMessage,
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
@@ -4992,23 +4997,43 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
{visibleEntries.map((workEntry) => (
|
||||
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
||||
>
|
||||
{workEntry.detail ? (
|
||||
<>
|
||||
{workEntry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
<div className="min-w-0 flex-1 py-[2px]">
|
||||
<p className={`text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}>
|
||||
{workEntry.label}
|
||||
</p>
|
||||
{workEntry.command && (
|
||||
<pre className="mt-1 overflow-x-auto rounded-md border border-border/70 bg-background/80 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80">
|
||||
{workEntry.command}
|
||||
</pre>
|
||||
)}
|
||||
{workEntry.changedFiles && workEntry.changedFiles.length > 0 && (
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{workEntry.changedFiles.slice(0, 6).map((filePath) => (
|
||||
<span
|
||||
key={`${workEntry.id}:${filePath}`}
|
||||
className="rounded-md border border-border/70 bg-background/65 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/85"
|
||||
title={filePath}
|
||||
>
|
||||
{filePath}
|
||||
</span>
|
||||
))}
|
||||
{workEntry.changedFiles.length > 6 && (
|
||||
<span className="px-1 text-[10px] text-muted-foreground/65">
|
||||
+{workEntry.changedFiles.length - 6} more
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{workEntry.detail &&
|
||||
(!workEntry.command || workEntry.detail !== workEntry.command) && (
|
||||
<p
|
||||
className="mt-1 text-[11px] leading-relaxed text-muted-foreground/75"
|
||||
title={workEntry.detail}
|
||||
>
|
||||
{workEntry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
workEntry.label
|
||||
)}
|
||||
</p>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -5095,7 +5120,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
row.message.role === "assistant" &&
|
||||
(() => {
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
const canBranchFromAssistantMessage = !row.message.streaming;
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && (
|
||||
@@ -5107,7 +5131,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="group min-w-0 px-1 py-0.5">
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
@@ -5169,30 +5193,14 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{canBranchFromAssistantMessage && (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onBranchAssistantMessage(row.message.id)}
|
||||
title="Branch from this response"
|
||||
>
|
||||
<GitBranchIcon className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.message.createdAt, nowIso)
|
||||
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.message.createdAt, nowIso)
|
||||
: formatElapsed(row.message.createdAt, row.message.completedAt),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
@@ -5211,12 +5219,17 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
{row.kind === "working" && (
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<div className="flex items-center pt-1">
|
||||
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt
|
||||
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
|
||||
: "Working..."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
@@ -175,6 +176,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
|
||||
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -250,6 +253,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
@@ -530,6 +534,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : !isGitRepo ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { planBranchedThread } from "./Sidebar.logic";
|
||||
|
||||
describe("planBranchedThread", () => {
|
||||
it("reuses the source branch without cloning a worktree for local threads", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Branch of Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
createWorktree: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("requests a fresh worktree when branching a worktree-backed thread", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Branch of Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: null,
|
||||
createWorktree: {
|
||||
cwd: "/repo",
|
||||
branch: "feature/original",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a generic fallback title when the source title is blank", () => {
|
||||
expect(
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: " ",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}).title,
|
||||
).toBe("Branched thread");
|
||||
});
|
||||
|
||||
it("rejects worktree threads that are missing a branch", () => {
|
||||
expect(() =>
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: null,
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: "/repo",
|
||||
}),
|
||||
).toThrow("Cannot branch a worktree thread without a branch.");
|
||||
});
|
||||
|
||||
it("rejects worktree threads when the project cwd is unavailable", () => {
|
||||
expect(() =>
|
||||
planBranchedThread({
|
||||
thread: {
|
||||
title: "Original thread",
|
||||
branch: "feature/original",
|
||||
worktreePath: "/tmp/original",
|
||||
},
|
||||
projectCwd: null,
|
||||
}),
|
||||
).toThrow("Project working directory is unavailable.");
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { Thread } from "../types";
|
||||
import { truncateTitle } from "../truncateTitle";
|
||||
|
||||
export interface BranchedThreadPlan {
|
||||
title: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
createWorktree: {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export function planBranchedThread(input: {
|
||||
thread: Pick<Thread, "title" | "branch" | "worktreePath">;
|
||||
projectCwd: string | null;
|
||||
}): BranchedThreadPlan {
|
||||
const { thread, projectCwd } = input;
|
||||
|
||||
if (thread.worktreePath) {
|
||||
if (!thread.branch) {
|
||||
throw new Error("Cannot branch a worktree thread without a branch.");
|
||||
}
|
||||
if (!projectCwd) {
|
||||
throw new Error("Project working directory is unavailable.");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: truncateTitle(
|
||||
thread.title.trim().length > 0 ? `Branch of ${thread.title}` : "Branched thread",
|
||||
),
|
||||
branch: thread.branch,
|
||||
worktreePath: null,
|
||||
createWorktree: thread.worktreePath
|
||||
? {
|
||||
cwd: projectCwd!,
|
||||
branch: thread.branch!,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -26,11 +26,7 @@ import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import {
|
||||
gitCreateWorktreeMutationOptions,
|
||||
gitRemoveWorktreeMutationOptions,
|
||||
gitStatusQueryOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
@@ -64,7 +60,6 @@ import {
|
||||
} from "./ui/sidebar";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import { branchConversationThread, createBranchedThreadWorktree } from "./threadBranching";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
@@ -265,7 +260,6 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
export default function Sidebar() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
@@ -273,7 +267,6 @@ export default function Sidebar() {
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const setBootstrapMessages = useComposerDraftStore((store) => store.setBootstrapMessages);
|
||||
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
@@ -295,7 +288,6 @@ export default function Sidebar() {
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
@@ -507,8 +499,8 @@ export default function Sidebar() {
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
const projectCreated = await api.orchestration
|
||||
.dispatchCommand({
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
@@ -516,11 +508,17 @@ export default function Sidebar() {
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
});
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
} catch (error) {
|
||||
setIsAddingProject(false);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to add project",
|
||||
description:
|
||||
error instanceof Error ? error.message : "An error occurred while adding the project.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
@@ -596,40 +594,12 @@ export default function Sidebar() {
|
||||
[],
|
||||
);
|
||||
|
||||
const branchConversation = useCallback(
|
||||
async (thread: Thread) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
await branchConversationThread({
|
||||
api,
|
||||
thread,
|
||||
seedMessages: thread.messages,
|
||||
projectCwd: projectCwdById.get(thread.projectId) ?? null,
|
||||
createWorktree: ({ cwd, branch }) =>
|
||||
createBranchedThreadWorktree({
|
||||
createWorktree: (args) => createWorktreeMutation.mutateAsync(args),
|
||||
cwd,
|
||||
branch,
|
||||
}),
|
||||
syncServerReadModel,
|
||||
setBootstrapMessages,
|
||||
navigateToThread: (threadId) =>
|
||||
navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
}),
|
||||
});
|
||||
},
|
||||
[createWorktreeMutation, navigate, projectCwdById, setBootstrapMessages, syncServerReadModel],
|
||||
);
|
||||
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "branch", label: "Branch conversation" },
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
@@ -640,19 +610,6 @@ export default function Sidebar() {
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (clicked === "branch") {
|
||||
try {
|
||||
await branchConversation(thread);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to branch conversation",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadId(threadId);
|
||||
setRenamingTitle(thread.title);
|
||||
@@ -782,7 +739,6 @@ export default function Sidebar() {
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
branchConversation,
|
||||
markThreadUnread,
|
||||
navigate,
|
||||
projects,
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ChatMessage } from "../types";
|
||||
import { selectBranchedMessages } from "./threadBranching";
|
||||
|
||||
function messageId(value: string): MessageId {
|
||||
return MessageId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function makeMessage(input: {
|
||||
id: string;
|
||||
role: ChatMessage["role"];
|
||||
text: string;
|
||||
createdAt?: string;
|
||||
}): ChatMessage {
|
||||
return {
|
||||
id: messageId(input.id),
|
||||
role: input.role,
|
||||
text: input.text,
|
||||
createdAt: input.createdAt ?? "2026-03-05T00:00:00.000Z",
|
||||
streaming: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("selectBranchedMessages", () => {
|
||||
it("returns the full transcript when no target message is provided", () => {
|
||||
const messages = [
|
||||
makeMessage({ id: "msg-1", role: "user", text: "first" }),
|
||||
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
|
||||
];
|
||||
|
||||
expect(selectBranchedMessages({ messages })).toEqual(messages);
|
||||
});
|
||||
|
||||
it("returns messages up to and including the targeted assistant message", () => {
|
||||
const messages = [
|
||||
makeMessage({ id: "msg-1", role: "user", text: "first" }),
|
||||
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
|
||||
makeMessage({ id: "msg-3", role: "user", text: "third" }),
|
||||
makeMessage({ id: "msg-4", role: "assistant", text: "fourth" }),
|
||||
];
|
||||
|
||||
expect(
|
||||
selectBranchedMessages({
|
||||
messages,
|
||||
targetMessageId: messageId("msg-2"),
|
||||
}).map((message) => message.id),
|
||||
).toEqual([messageId("msg-1"), messageId("msg-2")]);
|
||||
});
|
||||
|
||||
it("rejects non-assistant branch targets", () => {
|
||||
expect(() =>
|
||||
selectBranchedMessages({
|
||||
messages: [makeMessage({ id: "msg-1", role: "user", text: "first" })],
|
||||
targetMessageId: messageId("msg-1"),
|
||||
}),
|
||||
).toThrow("Can only branch from an assistant message.");
|
||||
});
|
||||
|
||||
it("rejects missing branch targets", () => {
|
||||
expect(() =>
|
||||
selectBranchedMessages({
|
||||
messages: [makeMessage({ id: "msg-1", role: "assistant", text: "first" })],
|
||||
targetMessageId: messageId("missing"),
|
||||
}),
|
||||
).toThrow("Branch target message was not found.");
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { MessageId, NativeApi, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { newCommandId, newThreadId } from "../lib/utils";
|
||||
|
||||
import type { ChatMessage, Thread } from "../types";
|
||||
import { buildTemporaryWorktreeBranchName } from "../worktreeBranches";
|
||||
import { planBranchedThread } from "./Sidebar.logic";
|
||||
|
||||
export function selectBranchedMessages(input: {
|
||||
messages: ReadonlyArray<ChatMessage>;
|
||||
targetMessageId?: MessageId | null;
|
||||
}): ChatMessage[] {
|
||||
if (!input.targetMessageId) {
|
||||
return [...input.messages];
|
||||
}
|
||||
|
||||
const targetIndex = input.messages.findIndex((message) => message.id === input.targetMessageId);
|
||||
if (targetIndex < 0) {
|
||||
throw new Error("Branch target message was not found.");
|
||||
}
|
||||
|
||||
const targetMessage = input.messages[targetIndex];
|
||||
if (!targetMessage || targetMessage.role !== "assistant") {
|
||||
throw new Error("Can only branch from an assistant message.");
|
||||
}
|
||||
|
||||
return input.messages.slice(0, targetIndex + 1);
|
||||
}
|
||||
|
||||
export async function branchConversationThread(input: {
|
||||
api: NativeApi;
|
||||
thread: Thread;
|
||||
seedMessages: ChatMessage[];
|
||||
projectCwd: string | null;
|
||||
createWorktree: (args: { cwd: string; branch: string }) => Promise<{
|
||||
branch: string;
|
||||
path: string;
|
||||
}>;
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
|
||||
navigateToThread: (threadId: ThreadId) => Promise<void>;
|
||||
}): Promise<ThreadId> {
|
||||
const branchedThreadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const plan = planBranchedThread({ thread: input.thread, projectCwd: input.projectCwd });
|
||||
let branchedThreadBranch = plan.branch;
|
||||
let branchedThreadWorktreePath = plan.worktreePath;
|
||||
|
||||
if (plan.createWorktree) {
|
||||
const result = await input.createWorktree({
|
||||
cwd: plan.createWorktree.cwd,
|
||||
branch: plan.createWorktree.branch,
|
||||
});
|
||||
branchedThreadBranch = result.branch;
|
||||
branchedThreadWorktreePath = result.path;
|
||||
}
|
||||
|
||||
await input.api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId: branchedThreadId,
|
||||
projectId: input.thread.projectId,
|
||||
title: plan.title,
|
||||
model: input.thread.model,
|
||||
runtimeMode: input.thread.runtimeMode,
|
||||
interactionMode: input.thread.interactionMode,
|
||||
branch: branchedThreadBranch,
|
||||
worktreePath: branchedThreadWorktreePath,
|
||||
seedMessages: input.seedMessages.map((message) => ({
|
||||
messageId: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments ?? [],
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.completedAt ?? message.createdAt,
|
||||
})),
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const snapshot = await input.api.orchestration.getSnapshot();
|
||||
input.syncServerReadModel(snapshot);
|
||||
if (input.seedMessages.length > 0) {
|
||||
input.setBootstrapMessages(branchedThreadId, input.seedMessages);
|
||||
}
|
||||
|
||||
await input.navigateToThread(branchedThreadId);
|
||||
return branchedThreadId;
|
||||
}
|
||||
|
||||
export async function createBranchedThreadWorktree(input: {
|
||||
createWorktree: (args: { cwd: string; branch: string; newBranch: string }) => Promise<{
|
||||
worktree: { branch: string; path: string };
|
||||
}>;
|
||||
cwd: string;
|
||||
branch: string;
|
||||
}): Promise<{ branch: string; path: string }> {
|
||||
const result = await input.createWorktree({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
newBranch: buildTemporaryWorktreeBranchName(),
|
||||
});
|
||||
return {
|
||||
branch: result.worktree.branch,
|
||||
path: result.worktree.path,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
createDebouncedStorage,
|
||||
useComposerDraftStore,
|
||||
} from "./composerDraftStore";
|
||||
|
||||
function makeImage(input: {
|
||||
id: string;
|
||||
@@ -152,35 +156,6 @@ describe("composerDraftStore clearComposerContent", () => {
|
||||
expect(draft).toBeUndefined();
|
||||
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
|
||||
});
|
||||
|
||||
it("preserves hidden bootstrap transcript state", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setPrompt(threadId, "draft prompt");
|
||||
store.setBootstrapMessages(threadId, [
|
||||
{
|
||||
id: MessageId.makeUnsafe("msg-bootstrap"),
|
||||
role: "user",
|
||||
text: "Earlier context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
|
||||
store.clearComposerContent(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
prompt: "",
|
||||
bootstrapMessages: [
|
||||
{
|
||||
id: "msg-bootstrap",
|
||||
role: "user",
|
||||
text: "Earlier context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore project draft thread mapping", () => {
|
||||
@@ -480,3 +455,125 @@ describe("composerDraftStore runtime and interaction settings", () => {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// createDebouncedStorage
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createMockStorage() {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: vi.fn((name: string) => store.get(name) ?? null),
|
||||
setItem: vi.fn((name: string, value: string) => {
|
||||
store.set(name, value);
|
||||
}),
|
||||
removeItem: vi.fn((name: string) => {
|
||||
store.delete(name);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("createDebouncedStorage", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("delegates getItem immediately", () => {
|
||||
const base = createMockStorage();
|
||||
base.getItem.mockReturnValueOnce("value");
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
expect(storage.getItem("key")).toBe("value");
|
||||
expect(base.getItem).toHaveBeenCalledWith("key");
|
||||
});
|
||||
|
||||
it("does not write to base storage until the debounce fires", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(299);
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
|
||||
});
|
||||
|
||||
it("only writes the last value when setItem is called rapidly", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
storage.setItem("key", "v2");
|
||||
storage.setItem("key", "v3");
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(base.setItem).toHaveBeenCalledTimes(1);
|
||||
expect(base.setItem).toHaveBeenCalledWith("key", "v3");
|
||||
});
|
||||
|
||||
it("removeItem cancels a pending setItem write", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
storage.removeItem("key");
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
expect(base.removeItem).toHaveBeenCalledWith("key");
|
||||
});
|
||||
|
||||
it("flush writes the pending value immediately", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
|
||||
storage.flush();
|
||||
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
|
||||
|
||||
// Timer should be cancelled; no duplicate write.
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(base.setItem).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("flush is a no-op when nothing is pending", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.flush();
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("flush after removeItem is a no-op", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
storage.removeItem("key");
|
||||
storage.flush();
|
||||
|
||||
expect(base.setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("setItem works normally after removeItem cancels a pending write", () => {
|
||||
const base = createMockStorage();
|
||||
const storage = createDebouncedStorage(base);
|
||||
|
||||
storage.setItem("key", "v1");
|
||||
storage.removeItem("key");
|
||||
storage.setItem("key", "v2");
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(base.setItem).toHaveBeenCalledTimes(1);
|
||||
expect(base.setItem).toHaveBeenCalledWith("key", "v2");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
ThreadId,
|
||||
@@ -14,14 +13,55 @@ import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type ChatImageAttachment,
|
||||
type ChatMessage,
|
||||
} from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
export type DraftThreadEnvMode = "local" | "worktree";
|
||||
|
||||
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
|
||||
|
||||
interface DebouncedStorage extends StateStorage {
|
||||
flush: () => void;
|
||||
}
|
||||
|
||||
export function createDebouncedStorage(baseStorage: StateStorage): DebouncedStorage {
|
||||
const debouncedSetItem = new Debouncer(
|
||||
(name: string, value: string) => {
|
||||
baseStorage.setItem(name, value);
|
||||
},
|
||||
{ wait: COMPOSER_PERSIST_DEBOUNCE_MS },
|
||||
);
|
||||
|
||||
return {
|
||||
getItem: (name) => baseStorage.getItem(name),
|
||||
setItem: (name, value) => {
|
||||
debouncedSetItem.maybeExecute(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
debouncedSetItem.cancel();
|
||||
baseStorage.removeItem(name);
|
||||
},
|
||||
flush: () => {
|
||||
debouncedSetItem.flush();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const composerDebouncedStorage: DebouncedStorage =
|
||||
typeof localStorage !== "undefined"
|
||||
? createDebouncedStorage(localStorage)
|
||||
: { getItem: () => null, setItem: () => {}, removeItem: () => {}, flush: () => {} };
|
||||
|
||||
// Flush pending composer draft writes before page unload to prevent data loss.
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("beforeunload", () => {
|
||||
composerDebouncedStorage.flush();
|
||||
});
|
||||
}
|
||||
|
||||
export interface PersistedComposerImageAttachment {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -38,7 +78,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
bootstrapMessages?: ChatMessage[];
|
||||
provider?: ProviderKind | null;
|
||||
model?: string | null;
|
||||
runtimeMode?: RuntimeMode | null;
|
||||
@@ -69,7 +108,6 @@ interface ComposerThreadDraftState {
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
bootstrapMessages: ChatMessage[];
|
||||
provider: ProviderKind | null;
|
||||
model: string | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
@@ -126,8 +164,6 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
|
||||
clearBootstrapMessages: (threadId: ThreadId) => void;
|
||||
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
|
||||
@@ -158,17 +194,14 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_BOOTSTRAP_MESSAGES: ChatMessage[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
Object.freeze(EMPTY_BOOTSTRAP_MESSAGES);
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze({
|
||||
prompt: "",
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
bootstrapMessages: EMPTY_BOOTSTRAP_MESSAGES,
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -187,7 +220,6 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
bootstrapMessages: [],
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -208,7 +240,6 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.prompt.length === 0 &&
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.bootstrapMessages.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -263,81 +294,6 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBootstrapAttachment(
|
||||
value: unknown,
|
||||
): Omit<ChatImageAttachment, "previewUrl"> | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const name = candidate.name;
|
||||
const mimeType = candidate.mimeType;
|
||||
const sizeBytes = candidate.sizeBytes;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
id.length === 0 ||
|
||||
typeof name !== "string" ||
|
||||
name.length === 0 ||
|
||||
typeof mimeType !== "string" ||
|
||||
mimeType.length === 0 ||
|
||||
typeof sizeBytes !== "number" ||
|
||||
!Number.isFinite(sizeBytes)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
id,
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBootstrapMessage(value: unknown): ChatMessage | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const role = candidate.role;
|
||||
const text = candidate.text;
|
||||
const createdAt = candidate.createdAt;
|
||||
const streaming = candidate.streaming;
|
||||
const completedAt = candidate.completedAt;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
id.length === 0 ||
|
||||
(role !== "user" && role !== "assistant" && role !== "system") ||
|
||||
typeof text !== "string" ||
|
||||
typeof createdAt !== "string" ||
|
||||
createdAt.length === 0 ||
|
||||
typeof streaming !== "boolean"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const attachments = Array.isArray(candidate.attachments)
|
||||
? candidate.attachments.flatMap((entry) => {
|
||||
const normalized = normalizeBootstrapAttachment(entry);
|
||||
if (!normalized) {
|
||||
return [];
|
||||
}
|
||||
return [normalized];
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: MessageId.makeUnsafe(id),
|
||||
role,
|
||||
text,
|
||||
createdAt,
|
||||
streaming,
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
...(typeof completedAt === "string" && completedAt.length > 0 ? { completedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeDraftThreadEnvMode(
|
||||
value: unknown,
|
||||
fallbackWorktreePath: string | null,
|
||||
@@ -452,12 +408,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const bootstrapMessages = Array.isArray(draftCandidate.bootstrapMessages)
|
||||
? draftCandidate.bootstrapMessages.flatMap((entry) => {
|
||||
const normalized = normalizeBootstrapMessage(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const provider = normalizeProviderKind(draftCandidate.provider);
|
||||
const model =
|
||||
typeof draftCandidate.model === "string"
|
||||
@@ -484,7 +434,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
if (
|
||||
prompt.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
bootstrapMessages.length === 0 &&
|
||||
!provider &&
|
||||
!model &&
|
||||
!runtimeMode &&
|
||||
@@ -497,7 +446,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
attachments,
|
||||
...(bootstrapMessages.length > 0 ? { bootstrapMessages } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
@@ -605,7 +553,6 @@ function toHydratedThreadDraft(
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
bootstrapMessages: persistedDraft.bootstrapMessages ?? [],
|
||||
provider: persistedDraft.provider ?? null,
|
||||
model: persistedDraft.model ?? null,
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
@@ -873,47 +820,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setBootstrapMessages: (threadId, messages) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
bootstrapMessages: [...messages],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearBootstrapMessages: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
bootstrapMessages: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProvider: (threadId, provider) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1305,7 +1211,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
{
|
||||
name: COMPOSER_DRAFT_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
storage: createJSONStorage(() => composerDebouncedStorage),
|
||||
partialize: (state) => {
|
||||
const persistedDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
|
||||
for (const [threadId, draft] of Object.entries(state.draftsByThreadId)) {
|
||||
@@ -1315,7 +1221,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.bootstrapMessages.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -1329,22 +1234,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
prompt: draft.prompt,
|
||||
attachments: draft.persistedAttachments,
|
||||
};
|
||||
if (draft.bootstrapMessages.length > 0) {
|
||||
persistedDraft.bootstrapMessages = draft.bootstrapMessages.map((message) => ({
|
||||
...message,
|
||||
...(message.attachments
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
}
|
||||
if (draft.model) {
|
||||
persistedDraft.model = draft.model;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildBootstrapInput,
|
||||
resolveTurnBootstrapMessages,
|
||||
selectBootstrapMessages,
|
||||
} from "./historyBootstrap";
|
||||
import { buildBootstrapInput } from "./historyBootstrap";
|
||||
|
||||
const messageId = (value: string) => MessageId.makeUnsafe(value);
|
||||
|
||||
@@ -126,126 +122,4 @@ describe("buildBootstrapInput", () => {
|
||||
expect(result.text).toContain("Attached image");
|
||||
expect(result.text).toContain("screenshot.png");
|
||||
});
|
||||
|
||||
it("labels system messages distinctly in transcript blocks", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: messageId("sys-1"),
|
||||
role: "system",
|
||||
text: "Follow repository rules.",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"continue",
|
||||
1_500,
|
||||
);
|
||||
|
||||
expect(result.text).toContain("SYSTEM:\nFollow repository rules.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectBootstrapMessages", () => {
|
||||
it("returns the newest fitting suffix in chronological order", () => {
|
||||
const result = selectBootstrapMessages(
|
||||
[
|
||||
{
|
||||
id: messageId("u-1"),
|
||||
role: "user",
|
||||
text: "first question with details",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: messageId("a-1"),
|
||||
role: "assistant",
|
||||
text: "first answer with details",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: messageId("u-2"),
|
||||
role: "user",
|
||||
text: "second question with details",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"final request",
|
||||
320,
|
||||
);
|
||||
|
||||
expect(result.omittedCount).toBeGreaterThan(0);
|
||||
expect(result.messages.map((message) => message.id)).toEqual([messageId("u-2")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTurnBootstrapMessages", () => {
|
||||
it("prefers explicit draft bootstrap messages", () => {
|
||||
const draftBootstrapMessages = [
|
||||
{
|
||||
id: messageId("draft-1"),
|
||||
role: "user" as const,
|
||||
text: "draft bootstrap",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const threadMessages = [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages,
|
||||
threadMessages,
|
||||
providerThreadId: null,
|
||||
}),
|
||||
).toEqual(draftBootstrapMessages);
|
||||
});
|
||||
|
||||
it("reuses visible thread history when no provider thread exists yet", () => {
|
||||
const threadMessages = [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: [],
|
||||
threadMessages,
|
||||
providerThreadId: null,
|
||||
}),
|
||||
).toEqual(threadMessages);
|
||||
});
|
||||
|
||||
it("skips bootstrap when the provider thread already exists", () => {
|
||||
expect(
|
||||
resolveTurnBootstrapMessages({
|
||||
draftBootstrapMessages: [],
|
||||
threadMessages: [
|
||||
{
|
||||
id: messageId("thread-1"),
|
||||
role: "assistant" as const,
|
||||
text: "visible history",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
providerThreadId: "provider-thread-1",
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -7,28 +7,6 @@ export interface BootstrapInputResult {
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export interface BootstrapMessageSelectionResult {
|
||||
messages: ChatMessage[];
|
||||
omittedCount: number;
|
||||
promptTruncated: boolean;
|
||||
}
|
||||
|
||||
export function resolveTurnBootstrapMessages(input: {
|
||||
draftBootstrapMessages: ChatMessage[];
|
||||
threadMessages: ChatMessage[];
|
||||
providerThreadId: string | null;
|
||||
}): ChatMessage[] {
|
||||
if (input.draftBootstrapMessages.length > 0) {
|
||||
return input.draftBootstrapMessages;
|
||||
}
|
||||
|
||||
if (input.providerThreadId === null && input.threadMessages.length > 0) {
|
||||
return input.threadMessages;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
const BOOTSTRAP_PREAMBLE =
|
||||
"Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
|
||||
const TRANSCRIPT_HEADER = "Transcript context:";
|
||||
@@ -36,14 +14,8 @@ const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
|
||||
const OMITTED_SUMMARY = (count: number) =>
|
||||
`[${count} earlier message(s) omitted to stay within input limits.]`;
|
||||
|
||||
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" | "SYSTEM" {
|
||||
if (message.role === "assistant") {
|
||||
return "ASSISTANT";
|
||||
}
|
||||
if (message.role === "system") {
|
||||
return "SYSTEM";
|
||||
}
|
||||
return "USER";
|
||||
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
|
||||
return message.role === "assistant" ? "ASSISTANT" : "USER";
|
||||
}
|
||||
|
||||
function attachmentSummary(message: ChatMessage): string | null {
|
||||
@@ -85,85 +57,6 @@ function finalizeWithPrompt(
|
||||
return text.length <= maxChars ? text : null;
|
||||
}
|
||||
|
||||
function buildTranscriptBody(messages: ReadonlyArray<ChatMessage>, omittedCount: number): string {
|
||||
const transcript = messages.map(buildMessageBlock).join("\n\n");
|
||||
if (omittedCount === 0) {
|
||||
return transcript;
|
||||
}
|
||||
if (transcript.length === 0) {
|
||||
return OMITTED_SUMMARY(omittedCount);
|
||||
}
|
||||
return `${OMITTED_SUMMARY(omittedCount)}\n\n${transcript}`;
|
||||
}
|
||||
|
||||
export function selectBootstrapMessages(
|
||||
previousMessages: ChatMessage[],
|
||||
latestPrompt: string,
|
||||
maxChars: number,
|
||||
): BootstrapMessageSelectionResult {
|
||||
const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
|
||||
const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
|
||||
const promptTruncated = latestPrompt.length !== promptOnly.length;
|
||||
|
||||
if (previousMessages.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: 0,
|
||||
promptTruncated,
|
||||
};
|
||||
}
|
||||
|
||||
const newestFirstMessages: ChatMessage[] = [];
|
||||
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = previousMessages[index];
|
||||
if (!message) continue;
|
||||
newestFirstMessages.push(message);
|
||||
}
|
||||
|
||||
if (newestFirstMessages.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: previousMessages.length,
|
||||
promptTruncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
let includedNewestFirst: ChatMessage[] = [];
|
||||
for (const message of newestFirstMessages) {
|
||||
const nextNewestFirst = [...includedNewestFirst, message];
|
||||
const nextChronological = nextNewestFirst.toReversed();
|
||||
const omittedCount = newestFirstMessages.length - nextChronological.length;
|
||||
const transcriptBody = buildTranscriptBody(nextChronological, omittedCount);
|
||||
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
break;
|
||||
}
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
}
|
||||
|
||||
let includedChronological = includedNewestFirst.toReversed();
|
||||
while (true) {
|
||||
const omittedCount = newestFirstMessages.length - includedChronological.length;
|
||||
const transcriptBody = buildTranscriptBody(includedChronological, omittedCount);
|
||||
if (finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
return {
|
||||
messages: includedChronological,
|
||||
omittedCount,
|
||||
promptTruncated,
|
||||
};
|
||||
}
|
||||
|
||||
if (includedChronological.length === 0) {
|
||||
return {
|
||||
messages: [],
|
||||
omittedCount: previousMessages.length,
|
||||
promptTruncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
includedChronological = includedChronological.slice(1);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildBootstrapInput(
|
||||
previousMessages: ChatMessage[],
|
||||
latestPrompt: string,
|
||||
@@ -180,8 +73,15 @@ export function buildBootstrapInput(
|
||||
truncated: promptOnly.length !== latestPrompt.length,
|
||||
};
|
||||
}
|
||||
const selection = selectBootstrapMessages(previousMessages, latestPrompt, budget);
|
||||
if (selection.messages.length === 0) {
|
||||
|
||||
const newestFirstBlocks: string[] = [];
|
||||
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = previousMessages[index];
|
||||
if (!message) continue;
|
||||
newestFirstBlocks.push(buildMessageBlock(message));
|
||||
}
|
||||
|
||||
if (newestFirstBlocks.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
@@ -190,21 +90,50 @@ export function buildBootstrapInput(
|
||||
};
|
||||
}
|
||||
|
||||
const transcriptBody = buildTranscriptBody(selection.messages, selection.omittedCount);
|
||||
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
|
||||
if (!finalized) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
// Include a contiguous suffix from newest to oldest, then reverse to chronological.
|
||||
let includedNewestFirst: string[] = [];
|
||||
for (const block of newestFirstBlocks) {
|
||||
const nextNewestFirst = [...includedNewestFirst, block];
|
||||
const nextChronological = nextNewestFirst.toReversed();
|
||||
const omittedCount = newestFirstBlocks.length - nextChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
|
||||
: nextChronological.join("\n\n");
|
||||
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
break;
|
||||
}
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
}
|
||||
|
||||
return {
|
||||
text: finalized,
|
||||
includedCount: selection.messages.length,
|
||||
omittedCount: selection.omittedCount,
|
||||
truncated: selection.omittedCount > 0 || selection.promptTruncated,
|
||||
};
|
||||
let includedChronological = includedNewestFirst.toReversed();
|
||||
while (true) {
|
||||
const omittedCount = newestFirstBlocks.length - includedChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? includedChronological.length > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
|
||||
: OMITTED_SUMMARY(omittedCount)
|
||||
: includedChronological.join("\n\n");
|
||||
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
|
||||
if (finalized) {
|
||||
return {
|
||||
text: finalized,
|
||||
includedCount: includedChronological.length,
|
||||
omittedCount,
|
||||
truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
|
||||
};
|
||||
}
|
||||
|
||||
if (includedChronological.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
includedChronological = includedChronological.slice(1);
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -263,9 +263,30 @@ label:has(> select#reasoning-effort) select {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ul {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.chat-markdown ol {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul {
|
||||
list-style-type: circle;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul ul {
|
||||
list-style-type: square;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
.chat-markdown li + li {
|
||||
|
||||
@@ -12,6 +12,7 @@ interface CheckpointDiffQueryInput {
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
cacheScope?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const providerQueryKeys = {
|
||||
@@ -52,6 +53,33 @@ function asCheckpointErrorMessage(error: unknown): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
function normalizeCheckpointErrorMessage(error: unknown): string {
|
||||
const message = asCheckpointErrorMessage(error).trim();
|
||||
if (message.length === 0) {
|
||||
return "Failed to load checkpoint diff.";
|
||||
}
|
||||
|
||||
const lower = message.toLowerCase();
|
||||
if (lower.includes("not a git repository")) {
|
||||
return "Turn diffs are unavailable because this project is not a git repository.";
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("checkpoint unavailable for thread") ||
|
||||
lower.includes("checkpoint invariant violation")
|
||||
) {
|
||||
const separatorIndex = message.indexOf(":");
|
||||
if (separatorIndex >= 0) {
|
||||
const detail = message.slice(separatorIndex + 1).trim();
|
||||
if (detail.length > 0) {
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
|
||||
const message = asCheckpointErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
@@ -71,12 +99,16 @@ export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
|
||||
if (!input.threadId || decodedRequest._tag === "None") {
|
||||
throw new Error("Checkpoint diff is unavailable.");
|
||||
}
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
try {
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return await api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
}
|
||||
return await api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
} catch (error) {
|
||||
throw new Error(normalizeCheckpointErrorMessage(error), { cause: error });
|
||||
}
|
||||
return api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
},
|
||||
enabled: !!input.threadId && decodedRequest._tag === "Some",
|
||||
enabled: (input.enabled ?? true) && !!input.threadId && decodedRequest._tag === "Some",
|
||||
staleTime: Infinity,
|
||||
retry: (failureCount, error) => {
|
||||
if (isCheckpointTemporarilyUnavailable(error)) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import { Throttler } from "@tanstack/react-pacer";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { Button } from "../components/ui/button";
|
||||
@@ -150,6 +151,7 @@ function EventRouter() {
|
||||
let latestSequence = 0;
|
||||
let syncing = false;
|
||||
let pending = false;
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
const flushSnapshotSync = async (): Promise<void> => {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
@@ -185,7 +187,20 @@ function EventRouter() {
|
||||
syncing = false;
|
||||
};
|
||||
|
||||
void syncSnapshot().catch(() => undefined);
|
||||
const domainEventFlushThrottler = new Throttler(
|
||||
() => {
|
||||
if (needsProviderInvalidation) {
|
||||
needsProviderInvalidation = false;
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
}
|
||||
void syncSnapshot();
|
||||
},
|
||||
{
|
||||
wait: 100,
|
||||
leading: false,
|
||||
trailing: true,
|
||||
},
|
||||
);
|
||||
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
if (event.sequence <= latestSequence) {
|
||||
@@ -193,9 +208,9 @@ function EventRouter() {
|
||||
}
|
||||
latestSequence = event.sequence;
|
||||
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
needsProviderInvalidation = true;
|
||||
}
|
||||
void syncSnapshot();
|
||||
domainEventFlushThrottler.maybeExecute();
|
||||
});
|
||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
@@ -280,6 +295,8 @@ function EventRouter() {
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
needsProviderInvalidation = false;
|
||||
domainEventFlushThrottler.cancel();
|
||||
unsubDomainEvent();
|
||||
unsubTerminalEvent();
|
||||
unsubWelcome();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { EventId, MessageId, TurnId, type OrchestrationThreadActivity } from "@t
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
PROVIDER_OPTIONS,
|
||||
derivePendingApprovals,
|
||||
@@ -430,6 +431,54 @@ describe("deriveWorkLogEntries", () => {
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it("extracts command text for command tool activities", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Command run complete",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
item: {
|
||||
command: ["bun", "run", "lint"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("extracts changed file paths for file-change tool activities", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "file-tool",
|
||||
kind: "tool.completed",
|
||||
summary: "File change complete",
|
||||
payload: {
|
||||
itemType: "file_change",
|
||||
data: {
|
||||
item: {
|
||||
changes: [
|
||||
{ path: "apps/web/src/components/ChatView.tsx" },
|
||||
{ filename: "apps/web/src/session-logic.ts" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.changedFiles).toEqual([
|
||||
"apps/web/src/components/ChatView.tsx",
|
||||
"apps/web/src/session-logic.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
@@ -542,6 +591,54 @@ describe("isLatestTurnSettled", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveActiveWorkStartedAt", () => {
|
||||
const latestTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
} as const;
|
||||
|
||||
it("prefers the in-flight turn start when the latest turn is not settled", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
latestTurn,
|
||||
{
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:10:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to sendStartedAt once the latest turn is settled", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
latestTurn,
|
||||
{
|
||||
orchestrationStatus: "ready",
|
||||
activeTurnId: undefined,
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:11:00.000Z");
|
||||
});
|
||||
|
||||
it("uses sendStartedAt for a fresh send after the prior turn completed", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
},
|
||||
null,
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:11:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PROVIDER_OPTIONS", () => {
|
||||
it("keeps Claude Code and Cursor visible as unavailable placeholders in the stack base", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface WorkLogEntry {
|
||||
createdAt: string;
|
||||
label: string;
|
||||
detail?: string;
|
||||
command?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
@@ -111,9 +113,12 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
|
||||
type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
|
||||
|
||||
export function isLatestTurnSettled(
|
||||
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
|
||||
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
@@ -122,6 +127,17 @@ export function isLatestTurnSettled(
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deriveActiveWorkStartedAt(
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
sendStartedAt: string | null,
|
||||
): string | null {
|
||||
if (!isLatestTurnSettled(latestTurn, session)) {
|
||||
return latestTurn?.startedAt ?? sendStartedAt;
|
||||
}
|
||||
return sendStartedAt;
|
||||
}
|
||||
|
||||
function requestKindFromRequestType(
|
||||
requestType: unknown,
|
||||
): PendingApproval["requestKind"] | null {
|
||||
@@ -401,6 +417,8 @@ export function deriveWorkLogEntries(
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const entry: WorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
@@ -410,10 +428,125 @@ export function deriveWorkLogEntries(
|
||||
if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
|
||||
entry.detail = payload.detail;
|
||||
}
|
||||
if (command) {
|
||||
entry.command = command;
|
||||
}
|
||||
if (changedFiles.length > 0) {
|
||||
entry.changedFiles = changedFiles;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | null {
|
||||
const direct = asTrimmedString(value);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
return parts.length > 0 ? parts.join(" ") : null;
|
||||
}
|
||||
|
||||
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
|
||||
const data = asRecord(payload?.data);
|
||||
const item = asRecord(data?.item);
|
||||
const itemResult = asRecord(item?.result);
|
||||
const itemInput = asRecord(item?.input);
|
||||
const candidates = [
|
||||
normalizeCommandValue(item?.command),
|
||||
normalizeCommandValue(itemInput?.command),
|
||||
normalizeCommandValue(itemResult?.command),
|
||||
normalizeCommandValue(data?.command),
|
||||
];
|
||||
return candidates.find((candidate) => candidate !== null) ?? null;
|
||||
}
|
||||
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
|
||||
const normalized = asTrimmedString(value);
|
||||
if (!normalized || seen.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalized);
|
||||
target.push(normalized);
|
||||
}
|
||||
|
||||
function collectChangedFiles(
|
||||
value: unknown,
|
||||
target: string[],
|
||||
seen: Set<string>,
|
||||
depth: number,
|
||||
) {
|
||||
if (depth > 4 || target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectChangedFiles(entry, target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const record = asRecord(value);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushChangedFile(target, seen, record.path);
|
||||
pushChangedFile(target, seen, record.filePath);
|
||||
pushChangedFile(target, seen, record.relativePath);
|
||||
pushChangedFile(target, seen, record.filename);
|
||||
pushChangedFile(target, seen, record.newPath);
|
||||
pushChangedFile(target, seen, record.oldPath);
|
||||
|
||||
for (const nestedKey of [
|
||||
"item",
|
||||
"result",
|
||||
"input",
|
||||
"data",
|
||||
"changes",
|
||||
"files",
|
||||
"edits",
|
||||
"patch",
|
||||
"patches",
|
||||
"operations",
|
||||
]) {
|
||||
if (!(nestedKey in record)) {
|
||||
continue;
|
||||
}
|
||||
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
|
||||
const data = asRecord(payload?.data);
|
||||
const changedFiles: string[] = [];
|
||||
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
|
||||
return changedFiles;
|
||||
}
|
||||
|
||||
function compareActivitiesByOrder(
|
||||
left: OrchestrationThreadActivity,
|
||||
right: OrchestrationThreadActivity,
|
||||
|
||||
+18
-4
@@ -14,6 +14,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -62,6 +63,8 @@ function readPersistedState(): AppState {
|
||||
}
|
||||
}
|
||||
|
||||
let legacyKeysCleanedUp = false;
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
@@ -73,13 +76,17 @@ function persistState(state: AppState): void {
|
||||
.map((project) => project.cwd),
|
||||
}),
|
||||
);
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
if (!legacyKeysCleanedUp) {
|
||||
legacyKeysCleanedUp = true;
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
|
||||
|
||||
// ── Pure helpers ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -394,8 +401,15 @@ export const useStore = create<AppStore>((set) => ({
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
}));
|
||||
|
||||
// Persist on every state change
|
||||
useStore.subscribe((state) => persistState(state));
|
||||
// Persist state changes with debouncing to avoid localStorage thrashing
|
||||
useStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
|
||||
|
||||
// Flush pending writes synchronously before page unload to prevent data loss.
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("beforeunload", () => {
|
||||
debouncedPersistState.flush();
|
||||
});
|
||||
}
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
@@ -43,7 +43,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
@@ -116,7 +116,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
|
||||
@@ -12,6 +12,8 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- Linux `x64` AppImage
|
||||
- Windows `x64` NSIS installer
|
||||
- Publishes one GitHub Release with all produced files.
|
||||
- Versions with a suffix after `X.Y.Z` (for example `1.2.3-alpha.1`) are published as GitHub prereleases.
|
||||
- Only plain `X.Y.Z` releases are marked as the repository's latest release.
|
||||
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -317,18 +317,6 @@ const ThreadCreateCommand = Schema.Struct({
|
||||
),
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
seedMessages: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
messageId: MessageId,
|
||||
role: OrchestrationMessageRole,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
"types": "./src/logging.ts",
|
||||
"import": "./src/logging.ts"
|
||||
},
|
||||
"./shell": {
|
||||
"types": "./src/shell.ts",
|
||||
"import": "./src/shell.ts"
|
||||
},
|
||||
"./Net": {
|
||||
"types": "./src/Net.ts",
|
||||
"import": "./src/Net.ts"
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { extractPathFromShellOutput, readPathFromLoginShell } from "./shell";
|
||||
|
||||
describe("extractPathFromShellOutput", () => {
|
||||
it("extracts the path between capture markers", () => {
|
||||
expect(
|
||||
extractPathFromShellOutput("__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n"),
|
||||
).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("ignores shell startup noise around the capture markers", () => {
|
||||
expect(
|
||||
extractPathFromShellOutput(
|
||||
"Welcome to fish\n__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\nBye\n",
|
||||
),
|
||||
).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("returns null when the markers are missing", () => {
|
||||
expect(extractPathFromShellOutput("/opt/homebrew/bin /usr/bin")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readPathFromLoginShell", () => {
|
||||
it("uses a shell-agnostic printenv PATH probe", () => {
|
||||
const execFile = vi.fn<
|
||||
(
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string
|
||||
>(() => "__T3CODE_PATH_START__\n/a:/b\n__T3CODE_PATH_END__\n");
|
||||
|
||||
expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
|
||||
expect(execFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
const firstCall = execFile.mock.calls[0] as
|
||||
| [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
|
||||
| undefined;
|
||||
expect(firstCall).toBeDefined();
|
||||
if (!firstCall) {
|
||||
throw new Error("Expected execFile to be called");
|
||||
}
|
||||
|
||||
const [shell, args, options] = firstCall;
|
||||
expect(shell).toBe("/opt/homebrew/bin/fish");
|
||||
expect(args).toHaveLength(2);
|
||||
expect(args?.[0]).toBe("-ilc");
|
||||
expect(args?.[1]).toContain("printenv PATH");
|
||||
expect(args?.[1]).toContain("__T3CODE_PATH_START__");
|
||||
expect(args?.[1]).toContain("__T3CODE_PATH_END__");
|
||||
expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
|
||||
const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
|
||||
const PATH_CAPTURE_COMMAND = [
|
||||
`printf '%s\n' '${PATH_CAPTURE_START}'`,
|
||||
"printenv PATH",
|
||||
`printf '%s\n' '${PATH_CAPTURE_END}'`,
|
||||
].join("; ");
|
||||
|
||||
type ExecFileSyncLike = (
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string;
|
||||
|
||||
export function extractPathFromShellOutput(output: string): string | null {
|
||||
const startIndex = output.indexOf(PATH_CAPTURE_START);
|
||||
if (startIndex === -1) return null;
|
||||
|
||||
const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
|
||||
const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
|
||||
if (endIndex === -1) return null;
|
||||
|
||||
const pathValue = output.slice(valueStartIndex, endIndex).trim();
|
||||
return pathValue.length > 0 ? pathValue : null;
|
||||
}
|
||||
|
||||
export function readPathFromLoginShell(
|
||||
shell: string,
|
||||
execFile: ExecFileSyncLike = execFileSync,
|
||||
): string | undefined {
|
||||
const output = execFile(shell, ["-ilc", PATH_CAPTURE_COMMAND], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
return extractPathFromShellOutput(output) ?? undefined;
|
||||
}
|
||||
@@ -455,6 +455,11 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
stderr: "inherit",
|
||||
env,
|
||||
extendEnv: false,
|
||||
// Keep turbo in the same process group so terminal signals (Ctrl+C)
|
||||
// reach it directly. Effect defaults to detached: true on non-Windows,
|
||||
// which would put turbo in a new group and require manual forwarding.
|
||||
detached: false,
|
||||
forceKillAfter: "1500 millis",
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
Reference in new issue
Block a user