Compare commits

..
Author SHA1 Message Date
Julius Marminge ae625d277c Handle missing workspaces across server and UI
- validate workspace paths before git, provider, terminal, and WS ops
- surface workspace availability in projections and client state
- add tests for missing cwd recovery and status handling
2026-03-29 00:45:41 -07:00
113 changed files with 3729 additions and 10190 deletions

No files matched your search

+5 -5
View File
@@ -126,7 +126,7 @@ jobs:
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
@@ -248,7 +248,7 @@ jobs:
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -348,7 +348,7 @@ jobs:
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: bun scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
@@ -364,7 +364,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock; then
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
@@ -372,6 +372,6 @@ jobs:
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
-23
View File
@@ -15,29 +15,6 @@ The file must be a JSON array of rules:
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Editor Schema Support
`keybindings.json` is intentionally a top-level JSON array, so it cannot carry an inline `$schema` property the way `settings.json` can.
To get autocomplete and hover docs in editors like VS Code, associate the file externally with the published schema:
```json
{
"json.schemas": [
{
"fileMatch": ["**/.t3/keybindings.json", "**/keybindings.json"],
"url": "https://t3.codes/schemas/keybindings.json"
}
]
}
```
If you want a pinned schema instead of the latest stable one, use a versioned URL such as:
```text
https://t3.codes/schemas/keybindings/0.0.15.json
```
## Defaults
```json
+4 -28
View File
@@ -2,42 +2,18 @@
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## Installation
## How to use
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
npx t3
```
### Desktop app
You can also just install the desktop app. It's cooler.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
## Some notes
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
@@ -1,69 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Keybindings",
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
"type": "array",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Keyboard shortcut to listen for."
},
"command": {
"anyOf": [
{
"type": "string",
"enum": [
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"diff.toggle",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
"thread.previous",
"thread.next",
"thread.jump.1",
"thread.jump.2",
"thread.jump.3",
"thread.jump.4",
"thread.jump.5",
"thread.jump.6",
"thread.jump.7",
"thread.jump.8",
"thread.jump.9"
]
},
{
"type": "string",
"pattern": "^script\\.[\\s\\S]*?\\.run$",
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
}
],
"description": "Command to execute when the shortcut matches."
},
"when": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional expression limiting when the shortcut is active."
}
},
"required": ["key", "command"],
"additionalProperties": false,
"description": "Single keybinding rule entry in `keybindings.json`."
},
"allOf": [
{
"maxItems": 256,
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
}
]
}
@@ -1,69 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Keybindings",
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
"type": "array",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Keyboard shortcut to listen for."
},
"command": {
"anyOf": [
{
"type": "string",
"enum": [
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"diff.toggle",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
"thread.previous",
"thread.next",
"thread.jump.1",
"thread.jump.2",
"thread.jump.3",
"thread.jump.4",
"thread.jump.5",
"thread.jump.6",
"thread.jump.7",
"thread.jump.8",
"thread.jump.9"
]
},
{
"type": "string",
"pattern": "^script\\.[\\s\\S]*?\\.run$",
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
}
],
"description": "Command to execute when the shortcut matches."
},
"when": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional expression limiting when the shortcut is active."
}
},
"required": ["key", "command"],
"additionalProperties": false,
"description": "Single keybinding rule entry in `keybindings.json`."
},
"allOf": [
{
"maxItems": 256,
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
}
]
}
-302
View File
@@ -1,302 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Default execution environment to use when creating new threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["codex"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": ["xhigh", "high", "medium", "low"]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["claudeAgent"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": ["low", "medium", "high", "max", "ultrathink"]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Default provider and model to use for server-side text generation features."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
@@ -1,302 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Default execution environment to use when creating new threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["codex"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": ["xhigh", "high", "medium", "low"]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["claudeAgent"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": ["low", "medium", "high", "max", "ultrathink"]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Default provider and model to use for server-side text generation features."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
@@ -31,6 +31,7 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
workspaceState: "available",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
@@ -51,6 +52,9 @@ function makeSnapshot(input: {
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
effectiveCwd: input.worktreePath ?? input.workspaceRoot,
effectiveCwdSource: input.worktreePath ? "worktree" : "project",
effectiveCwdState: "available",
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
+2 -25
View File
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("disables spark for api key accounts", () => {
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,20 +318,7 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
sparkEnabled: true,
});
});
});
@@ -356,16 +343,6 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
+94 -10
View File
@@ -26,15 +26,6 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -105,6 +96,23 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -154,6 +162,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -306,13 +358,32 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
killCodexChildProcess(child);
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
@@ -331,6 +402,19 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
@@ -13,7 +13,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
@@ -28,10 +27,10 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -85,8 +84,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
const normalizedOptions = normalizeClaudeModelOptions(
modelSelection.model,
modelSelection.options,
);
const settings = {
@@ -5,7 +5,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
@@ -27,10 +26,10 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -157,8 +156,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
const normalizedOptions = normalizeCodexModelOptions(
modelSelection.model,
modelSelection.options,
);
const reasoningEffort =
+16 -1
View File
@@ -1,9 +1,10 @@
import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { Cause, Effect, Exit, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
@@ -1283,6 +1284,20 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("fails cleanly when statusDetails is requested for a missing workspace", () =>
Effect.gen(function* () {
const missingCwd = path.join(os.tmpdir(), `git-missing-${crypto.randomUUID()}`);
const result = yield* Effect.exit((yield* GitCore).statusDetails(missingCwd));
expect(Exit.isFailure(result)).toBe(true);
if (Exit.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toBeInstanceOf(GitCommandError);
expect((error as GitCommandError).detail).toContain("Workspace folder is missing");
}
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+39 -2
View File
@@ -29,6 +29,7 @@ import {
} from "../Services/GitCore.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -518,12 +519,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const { worktreesDir } = yield* ServerConfig;
let execute: GitCoreShape["execute"];
let rawExecute: GitCoreShape["execute"];
if (options?.executeOverride) {
execute = options.executeOverride;
rawExecute = options.executeOverride;
} else {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
execute = Effect.fnUntraced(function* (input) {
rawExecute = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
@@ -613,6 +615,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
execute = Effect.fnUntraced(function* (input) {
yield* assertWorkspaceDirectory(input.cwd, input.operation).pipe(
Effect.mapError(
(error) =>
new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: error.message,
cause: error,
}),
),
);
return yield* rawExecute(input);
});
const executeGit = (
operation: string,
cwd: string,
@@ -655,6 +673,20 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
}),
);
const ensureGitWorkspace = (operation: string, cwd: string, args: readonly string[] = []) =>
assertWorkspaceDirectory(cwd, operation).pipe(
Effect.mapError(
(error) =>
new GitCommandError({
operation,
command: quoteGitCommand(args),
cwd,
detail: error.message,
cause: error,
}),
),
);
const runGit = (
operation: string,
cwd: string,
@@ -1041,6 +1073,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* ensureGitWorkspace("GitCore.statusDetails", cwd, [
"status",
"--porcelain=2",
"--branch",
]);
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
+9
View File
@@ -14,6 +14,15 @@ export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
+13 -3
View File
@@ -34,6 +34,7 @@ import {
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
@@ -43,7 +44,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -417,7 +418,16 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -666,7 +676,7 @@ const makeKeybindings = Effect.gen(function* () {
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return encodeKeybindingsConfigPrettyJson(rules).pipe(
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
@@ -25,6 +25,10 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import {
inspectWorkspacePathState,
resolveWorkspaceUnavailableReason,
} from "../../workspacePaths.ts";
type ReactorInput =
| {
@@ -154,7 +158,12 @@ const make = Effect.gen(function* () {
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly thread: {
readonly projectId: ProjectId;
readonly worktreePath: string | null;
readonly effectiveCwd: string | null;
readonly effectiveCwdState: string;
};
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
}): Effect.fn.Return<string | undefined> {
@@ -175,7 +184,7 @@ const make = Effect.gen(function* () {
onSome: (runtime) => runtime.cwd,
}));
if (!cwd) {
if (input.thread.effectiveCwdState !== "available" || !cwd) {
return undefined;
}
if (!isGitWorkspace(cwd)) {
@@ -583,6 +592,20 @@ const make = Effect.gen(function* () {
}).pipe(Effect.catch(() => Effect.void));
return;
}
const sessionWorkspaceState = yield* Effect.promise(() =>
inspectWorkspacePathState(sessionRuntime.value.cwd),
);
if (sessionWorkspaceState !== "available") {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
detail:
resolveWorkspaceUnavailableReason(sessionWorkspaceState) ??
"Workspace folder is unavailable.",
createdAt: now,
}).pipe(Effect.catch(() => Effect.void));
return;
}
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
@@ -1,3 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
@@ -23,6 +27,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "projection-snapshot-"));
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
@@ -43,7 +48,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
VALUES (
'project-1',
'Project 1',
'/tmp/project-1',
${workspaceRoot},
'{"provider":"codex","model":"gpt-5-codex"}',
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
'2026-02-24T00:00:00.000Z',
@@ -233,7 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
workspaceRoot,
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -265,6 +271,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: workspaceRoot,
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
@@ -18,6 +18,7 @@ import {
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
type WorkspaceAvailabilityState,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -42,6 +43,7 @@ import {
ProjectionSnapshotQuery,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
import { inspectWorkspacePathState } from "../../workspacePaths.ts";
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
@@ -135,6 +137,12 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
: toPersistenceSqlError(sqlOperation)(cause);
}
type EffectiveWorkspaceMetadata = {
readonly effectiveCwd: string | null;
readonly effectiveCwdSource: "project" | "worktree" | null;
readonly effectiveCwdState: WorkspaceAvailabilityState;
};
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -538,10 +546,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const workspaceRoots = new Set(projectRows.map((row) => row.workspaceRoot));
const worktreePaths = new Set(
threadRows.flatMap((row) => (row.worktreePath ? [row.worktreePath] : [])),
);
const workspaceStateEntries = yield* Effect.promise(() =>
Promise.all(
[...new Set([...workspaceRoots, ...worktreePaths])].map(async (workspacePath) => {
const workspaceState = await inspectWorkspacePathState(workspacePath);
return [workspacePath, workspaceState] as const;
}),
),
);
const workspaceStates = new Map(workspaceStateEntries);
const projectRowsById = new Map(projectRows.map((row) => [row.projectId, row] as const));
const projectWorkspaceStateById = new Map(
projectRows.map((row) => [
row.projectId,
workspaceStates.get(row.workspaceRoot) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
]),
);
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
workspaceState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -549,26 +582,48 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
deletedAt: row.deletedAt,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => {
const effectiveWorkspace: EffectiveWorkspaceMetadata =
row.worktreePath !== null
? {
effectiveCwd: row.worktreePath,
effectiveCwdSource: "worktree",
effectiveCwdState:
workspaceStates.get(row.worktreePath) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
}
: {
effectiveCwd: projectRowsById.get(row.projectId)?.workspaceRoot ?? null,
effectiveCwdSource: projectRowsById.has(row.projectId) ? "project" : null,
effectiveCwdState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
};
return {
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
effectiveCwd: effectiveWorkspace.effectiveCwd,
effectiveCwdSource: effectiveWorkspace.effectiveCwdSource,
effectiveCwdState: effectiveWorkspace.effectiveCwdState,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
};
});
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -45,6 +45,8 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
fs.mkdirSync("/tmp/provider-project", { recursive: true });
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -25,6 +25,7 @@ import {
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -254,6 +255,12 @@ const make = Effect.gen(function* () {
thread,
projects: readModel.projects,
});
if (effectiveCwd) {
yield* assertWorkspaceDirectory(
effectiveCwd,
"ProviderCommandReactor.ensureSessionForThread",
);
}
const resolveActiveSession = (threadId: ThreadId) =>
providerService
@@ -28,6 +28,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -41,6 +42,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -64,6 +66,9 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-a",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -87,6 +92,9 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-b",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -183,6 +183,7 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
workspaceState: "available" as const,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
createdAt: payload.createdAt,
+174 -436
View File
@@ -1,15 +1,15 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -96,9 +96,28 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getClaudeModelCapabilities(model);
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -110,7 +129,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
@@ -125,7 +144,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
@@ -146,286 +165,37 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
// ── Dynamic model capability adjustment ─────────────────────────────
/** Subscription types where the 1M context window is included in the plan. */
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
"max",
"maxplan",
"max5",
"max20",
"enterprise",
"team",
]);
function toTitleCaseWords(value: string): string {
return value
.split(/[\s_-]+/g)
.filter(Boolean)
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
.join(" ");
}
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
switch (normalized) {
case "max":
case "maxplan":
case "max5":
case "max20":
return "Max";
case "enterprise":
return "Enterprise";
case "team":
return "Team";
case "pro":
return "Pro";
case "free":
return "Free";
default:
return toTitleCaseWords(subscriptionType!);
}
}
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
if (normalized === "apikey") return "apiKey";
return undefined;
}
function claudeAuthMetadata(input: {
readonly subscriptionType: string | undefined;
readonly authMethod: string | undefined;
}): { readonly type: string; readonly label: string } | undefined {
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
return {
type: "apiKey",
label: "Claude API Key",
};
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
};
}
return undefined;
}
/**
* Adjust the built-in model list based on the user's detected subscription.
*
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
* - Other tiers (Pro, free, unknown): 200k context stays the default;
* 1M remains available as a manual option so users can still enable it.
*/
export function adjustModelsForSubscription(
baseModels: ReadonlyArray<ServerProviderModel>,
subscriptionType: string | undefined,
): ReadonlyArray<ServerProviderModel> {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
return baseModels;
}
// Flip 1M to be the default for premium users
return baseModels.map((model) => {
const caps = model.capabilities;
if (!caps || caps.contextWindowOptions.length === 0) return model;
return {
...model,
capabilities: {
...caps,
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
opt.value === "1m"
? { value: opt.value, label: opt.label, isDefault: true as const }
: { value: opt.value, label: opt.label },
),
},
};
});
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
*
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
prompt: ".",
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: [],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return { subscriptionType: init.account?.subscriptionType };
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (!abort.signal.aborted) abort.abort();
}),
),
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
};
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
@@ -438,81 +208,144 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Claude is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
@@ -521,99 +354,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
},
);
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
@@ -621,16 +368,7 @@ export const ClaudeProviderLive = Layer.effect(
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) =>
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
});
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath),
).pipe(
const checkProvider = checkClaudeProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
+202 -242
View File
@@ -1,25 +1,16 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -38,13 +29,6 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount";
import { probeCodexAccount } from "../codexAppServer";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
@@ -168,9 +152,25 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
);
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const caps = getCodexModelCapabilities(model);
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
@@ -196,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
@@ -217,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
@@ -290,21 +290,6 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.orElseSucceed(() => false),
);
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
const probeCodexCapabilities = (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) =>
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
@@ -321,88 +306,179 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Codex is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
@@ -411,116 +487,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
auth: { status: "unknown" },
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const account = resolveAccount
? yield* resolveAccount({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
})
: undefined;
const resolvedModels = adjustCodexModelsForAccount(models, account);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const authType = codexAuthSubType(account);
const authLabel = codexAuthSubLabel(account);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
},
);
export const CodexProviderLive = Layer.effect(
CodexProvider,
@@ -529,21 +502,8 @@ export const CodexProviderLive = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: string) => {
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
return probeCodexCapabilities({
binaryPath,
...(homePath ? { homePath } : {}),
});
},
});
const checkProvider = checkCodexProviderStatus((input) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
).pipe(
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -173,133 +173,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "pro" as const,
sparkEnabled: true,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "pro");
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
true,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "plus" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "plus");
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "team" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.auth.type, "team");
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for codex api key auth", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "apiKey" as const,
planType: null,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "OpenAI API Key");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -361,7 +235,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.authStatus, "authenticated");
} finally {
process.env.PATH = previousPath;
}
@@ -375,7 +249,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
@@ -390,7 +264,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
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.",
@@ -413,7 +287,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -439,7 +313,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -464,7 +338,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
@@ -492,7 +366,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -502,7 +376,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "warning",
enabled: true,
installed: true,
auth: { status: "unknown" },
authStatus: "unknown",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -620,7 +494,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
@@ -663,7 +537,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
const status = yield* checkCodexProviderStatus();
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -684,7 +558,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
@@ -694,7 +568,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.auth.status, "unauthenticated");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -704,7 +578,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.auth.status, "unknown");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
@@ -841,7 +715,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -859,63 +733,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "maxplan");
assert.strictEqual(status.auth.label, "Claude Max Subscription");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for claude api key auth", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "Claude API Key");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
@@ -947,7 +771,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
@@ -975,7 +799,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -995,7 +819,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
@@ -1020,7 +844,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
@@ -1030,7 +854,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
@@ -1040,7 +864,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.auth.status, "unauthenticated");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -1050,7 +874,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.auth.status, "unknown");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
},
@@ -20,7 +20,7 @@ import {
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
import { Cause, Effect, Fiber, Layer, Option, PubSub, Ref, Schema, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -44,6 +44,7 @@ import {
} from "../../persistence/Layers/Sqlite.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { clearWorkspacePathStateCache } from "../../workspacePaths.ts";
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
@@ -230,6 +231,16 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
for (const workspaceRoot of [
"/tmp/project",
"/tmp/project-claude",
"/tmp/project-send-turn",
"/tmp/project-claude-send-turn",
"/tmp/project-claude-start",
]) {
fs.mkdirSync(workspaceRoot, { recursive: true });
}
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
@@ -681,6 +692,46 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("fails recovery cleanly when the persisted workspace has been deleted", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "provider-missing-cwd-"));
const initial = yield* provider.startSession(asThreadId("thread-missing-cwd"), {
provider: "codex",
threadId: asThreadId("thread-missing-cwd"),
cwd: workspaceRoot,
runtimeMode: "full-access",
});
fs.rmSync(workspaceRoot, { recursive: true, force: true });
clearWorkspacePathStateCache(workspaceRoot);
yield* routing.codex.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
const exit = yield* Effect.exit(
provider.sendTurn({
threadId: initial.threadId,
input: "resume",
attachments: [],
}),
);
assert.equal(routing.codex.startSession.mock.calls.length, 0);
assert.equal(routing.codex.sendTurn.mock.calls.length, 0);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.equal(Schema.is(ProviderValidationError)(error), true);
assert.equal(
(error as ProviderValidationError).message.includes("Workspace folder is missing"),
true,
);
}
}),
);
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -34,6 +34,7 @@ import {
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
@@ -228,6 +229,21 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
if (persistedCwd) {
yield* assertWorkspaceDirectory(
persistedCwd,
"ProviderService.recoverSessionForThread",
).pipe(
Effect.mapError((error) =>
toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}'. ${error.message}`,
error,
),
),
);
}
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
@@ -315,6 +331,13 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
if (input.cwd) {
yield* assertWorkspaceDirectory(input.cwd, "ProviderService.startSession").pipe(
Effect.mapError((error) =>
toValidationError("ProviderService.startSession", error.message, error),
),
);
}
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
-123
View File
@@ -1,123 +0,0 @@
import type { ServerProviderModel } from "@t3tools/contracts";
export type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
export interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: false,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
if (account?.type === "apiKey") {
return "apiKey";
}
if (account?.type !== "chatgpt") {
return undefined;
}
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
}
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
switch (codexAuthSubType(account)) {
case "apiKey":
return "OpenAI API Key";
case "chatgpt":
return "ChatGPT Subscription";
case "free":
return "ChatGPT Free Subscription";
case "go":
return "ChatGPT Go Subscription";
case "plus":
return "ChatGPT Plus Subscription";
case "pro":
return "ChatGPT Pro Subscription";
case "team":
return "ChatGPT Team Subscription";
case "business":
return "ChatGPT Business Subscription";
case "enterprise":
return "ChatGPT Enterprise Subscription";
case "edu":
return "ChatGPT Edu Subscription";
default:
return undefined;
}
}
export function adjustCodexModelsForAccount(
baseModels: ReadonlyArray<ServerProviderModel>,
account: CodexAccountSnapshot | undefined,
): ReadonlyArray<ServerProviderModel> {
if (account?.sparkEnabled !== false) {
return baseModels;
}
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
-154
View File
@@ -1,154 +0,0 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
interface JsonRpcProbeResponse {
readonly id?: unknown;
readonly result?: unknown;
readonly error?: {
readonly message?: unknown;
};
}
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
return typeof response.error?.message === "string" ? response.error.message : undefined;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill();
}
export async function probeCodexAccount(input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly signal?: AbortSignal;
}): Promise<CodexAccountSnapshot> {
return await new Promise((resolve, reject) => {
const child = spawn(input.binaryPath, ["app-server"], {
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
let completed = false;
const cleanup = () => {
output.removeAllListeners();
output.close();
child.removeAllListeners();
if (!child.killed) {
killCodexChildProcess(child);
}
};
const finish = (callback: () => void) => {
if (completed) return;
completed = true;
cleanup();
callback();
};
const fail = (error: unknown) =>
finish(() =>
reject(
error instanceof Error
? error
: new Error(`Codex account probe failed: ${String(error)}.`),
),
);
if (input.signal?.aborted) {
fail(new Error("Codex account probe aborted."));
return;
}
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
const writeMessage = (message: unknown) => {
if (!child.stdin.writable) {
fail(new Error("Cannot write to codex app-server stdin."));
return;
}
child.stdin.write(`${JSON.stringify(message)}\n`);
};
output.on("line", (line) => {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
fail(new Error("Received invalid JSON from codex app-server during account probe."));
return;
}
if (!parsed || typeof parsed !== "object") {
return;
}
const response = parsed as JsonRpcProbeResponse;
if (response.id === 1) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`initialize failed: ${errorMessage}`));
return;
}
writeMessage({ method: "initialized" });
writeMessage({ id: 2, method: "account/read", params: {} });
return;
}
if (response.id === 2) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`account/read failed: ${errorMessage}`));
return;
}
finish(() => resolve(readCodexAccountSnapshot(response.result)));
}
});
child.once("error", fail);
child.once("exit", (code, signal) => {
if (completed) return;
fail(
new Error(
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
),
);
});
writeMessage({
id: 1,
method: "initialize",
params: buildCodexInitializeParams(),
});
});
}
+3 -3
View File
@@ -1,6 +1,6 @@
import type {
ServerProvider,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderModel,
ServerProviderState,
} from "@t3tools/contracts";
@@ -21,7 +21,7 @@ export interface ProviderProbeResult {
readonly installed: boolean;
readonly version: string | null;
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: ServerProviderAuth;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
}
@@ -137,7 +137,7 @@ export function buildServerProvider(input: {
installed: input.probe.installed,
version: input.probe.version,
status: input.enabled ? input.probe.status : "disabled",
auth: input.probe.auth,
authStatus: input.probe.authStatus,
checkedAt: input.checkedAt,
...(input.probe.message ? { message: input.probe.message } : {}),
models: input.models,
-83
View File
@@ -104,43 +104,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
// Start with Claude text generation selection
yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "high",
},
},
});
// Switch to Codex — the stale Claude "effort" in options must not
// cause the update to lose the selected model.
const next = yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
},
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims provider path settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -216,50 +179,4 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves a top-level $schema declaration when rewriting settings", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(
serverConfig.settingsPath,
`${JSON.stringify(
{
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
},
},
null,
2,
)}\n`,
);
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.start;
yield* serverSettings.updateSettings({
providers: {
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+6 -47
View File
@@ -27,7 +27,6 @@ import {
FileSystem,
Layer,
Path,
Equal,
PubSub,
Ref,
Schema,
@@ -39,7 +38,7 @@ import {
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
@@ -101,9 +100,6 @@ export class ServerSettingsService extends ServiceMap.Service<
}
const ServerSettingsJson = fromLenientJson(ServerSettings);
const UnknownJson = fromLenientJson(Schema.Unknown);
const encodeServerSettingsDocument = encodePrettyJsonEffect(Schema.Unknown);
const SETTINGS_SCHEMA_DECLARATION_KEY = "$schema";
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
@@ -134,12 +130,9 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings
};
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
return Equal.equals(current, defaults) ? undefined : current;
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
}
if (
@@ -153,15 +146,9 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
if (ATOMIC_SETTINGS_KEYS.has(key)) {
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
next[key] = currentRecord[key];
}
} else {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
}
@@ -180,7 +167,6 @@ const makeServerSettings = Effect.gen(function* () {
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
const schemaDeclarationRef = yield* Ref.make<string | undefined>(undefined);
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
@@ -211,27 +197,10 @@ const makeServerSettings = Effect.gen(function* () {
const loadSettingsFromDisk = Effect.gen(function* () {
if (!(yield* readConfigExists)) {
yield* Ref.set(schemaDeclarationRef, undefined);
return DEFAULT_SERVER_SETTINGS;
}
const raw = yield* readRawConfig;
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
if (rawJson._tag === "Success") {
const value = rawJson.value;
const valueRecord =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
const schemaDeclaration =
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
: undefined;
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
} else {
yield* Ref.set(schemaDeclarationRef, undefined);
}
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -253,17 +222,7 @@ const makeServerSettings = Effect.gen(function* () {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return Ref.get(schemaDeclarationRef).pipe(
Effect.map((schemaDeclaration) =>
schemaDeclaration
? {
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
...sparseSettings,
}
: sparseSettings,
),
Effect.flatMap(encodeServerSettingsDocument),
Effect.map((encoded) => `${encoded}\n`),
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+38 -71
View File
@@ -14,81 +14,47 @@ import {
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalSessionStatus,
TerminalWriteInput,
} from "@t3tools/contracts";
import { PtyProcess } from "./PTY";
import { Effect, Schema, ServiceMap } from "effect";
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
"TerminalCwdError",
{
cwd: Schema.String,
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
if (this.reason === "notDirectory") {
return `Terminal cwd is not a directory: ${this.cwd}`;
}
if (this.reason === "notFound") {
return `Terminal cwd does not exist: ${this.cwd}`;
}
const causeMessage =
this.cause && typeof this.cause === "object" && "message" in this.cause
? this.cause.message
: undefined;
return causeMessage
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
: `Failed to access terminal cwd: ${this.cwd}`;
}
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
export interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
cols: number;
rows: number;
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runtimeEnv: Record<string, string> | null;
}
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
"TerminalHistoryError",
{
operation: Schema.Literals(["read", "truncate", "migrate"]),
threadId: Schema.String,
terminalId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
export interface ShellCandidate {
shell: string;
args?: string[];
}
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
"TerminalSessionLookupError",
{
threadId: Schema.String,
terminalId: Schema.String,
},
) {
override get message() {
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
export interface TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number;
}
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
"TerminalNotRunningError",
{
threadId: Schema.String,
terminalId: Schema.String,
},
) {
override get message() {
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
}
export const TerminalError = Schema.Union([
TerminalCwdError,
TerminalHistoryError,
TerminalSessionLookupError,
TerminalNotRunningError,
]);
export type TerminalError = typeof TerminalError.Type;
/**
* TerminalManagerShape - Service API for terminal session lifecycle operations.
*/
@@ -135,13 +101,14 @@ export interface TerminalManagerShape {
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Subscribe to terminal runtime events with a direct callback.
*
* Returns an unsubscribe function.
* Subscribe to terminal runtime events.
*/
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
/**
* Dispose all managed terminal resources.
*/
readonly dispose: Effect.Effect<void>;
}
/**
+100
View File
@@ -0,0 +1,100 @@
import fs from "node:fs/promises";
import { type WorkspaceAvailabilityState } from "@t3tools/contracts";
import { Effect, Schema } from "effect";
const WORKSPACE_PATH_CACHE_TTL_MS = 1_000;
type CachedWorkspacePathState = {
readonly expiresAt: number;
readonly state: WorkspaceAvailabilityState;
};
const workspacePathStateCache = new Map<string, CachedWorkspacePathState>();
export class WorkspacePathError extends Schema.TaggedErrorClass<WorkspacePathError>()(
"WorkspacePathError",
{
operation: Schema.String,
path: Schema.String,
state: Schema.Literals(["missing", "not_directory", "inaccessible"]),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
switch (this.state) {
case "missing":
return `Workspace folder is missing: ${this.path}`;
case "not_directory":
return `Workspace path is not a folder: ${this.path}`;
case "inaccessible":
default:
return `Workspace folder is inaccessible: ${this.path}`;
}
}
}
export function clearWorkspacePathStateCache(path?: string): void {
if (path) {
workspacePathStateCache.delete(path);
return;
}
workspacePathStateCache.clear();
}
export async function inspectWorkspacePathState(path: string): Promise<WorkspaceAvailabilityState> {
const cached = workspacePathStateCache.get(path);
const now = Date.now();
if (cached && cached.expiresAt > now) {
return cached.state;
}
let state: WorkspaceAvailabilityState;
try {
const stat = await fs.stat(path);
state = stat.isDirectory() ? "available" : "not_directory";
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
state = code === "ENOENT" ? "missing" : "inaccessible";
}
workspacePathStateCache.set(path, {
expiresAt: now + WORKSPACE_PATH_CACHE_TTL_MS,
state,
});
return state;
}
export const getWorkspacePathState = (path: string) =>
Effect.promise(() => inspectWorkspacePathState(path));
export const assertWorkspaceDirectory = (path: string, operation: string) =>
getWorkspacePathState(path).pipe(
Effect.flatMap((state) =>
state === "available"
? Effect.succeed(path)
: Effect.fail(
new WorkspacePathError({
operation,
path,
state,
}),
),
),
);
export function resolveWorkspaceUnavailableReason(
state: WorkspaceAvailabilityState,
): string | null {
switch (state) {
case "missing":
return "Workspace folder is missing.";
case "not_directory":
return "Workspace path is not a folder.";
case "inaccessible":
return "Workspace folder is inaccessible.";
case "available":
default:
return null;
}
}
+15 -22
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
@@ -74,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
@@ -90,19 +90,20 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
private activeSubscriptions = 0;
private readonly listeners = new Set<(event: TerminalEvent) => void>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
emitEvent(event: TerminalEvent): void {
Effect.runSync(PubSub.publish(this.eventPubSub, event));
for (const listener of this.listeners) {
listener(event);
}
}
subscriptionCount(): number {
return this.activeSubscriptions;
return this.listeners.size;
}
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
@@ -209,15 +210,13 @@ class MockTerminalManager implements TerminalManagerShape {
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
Effect.sync(() => {
this.activeSubscriptions += 1;
const fiber = Effect.runFork(
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
);
this.listeners.add(listener);
return () => {
this.activeSubscriptions -= 1;
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
this.listeners.delete(listener);
};
});
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
}
// ---------------------------------------------------------------------------
@@ -1455,25 +1454,19 @@ describe("WebSocket Server", () => {
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
});
it("shuts down cleanly for injected terminal managers", async () => {
it("detaches terminal event listener on stop for injected manager", async () => {
const terminalManager = new MockTerminalManager();
server = await createTestServer({
cwd: "/test",
terminalManager,
});
expect(terminalManager.subscriptionCount()).toBe(1);
await closeTestServer();
server = null;
expect(() =>
terminalManager.emitEvent({
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "after shutdown\n",
}),
).not.toThrow();
expect(terminalManager.subscriptionCount()).toBe(0);
});
it("returns validation errors for invalid terminal open params", async () => {
+36 -3
View File
@@ -79,6 +79,7 @@ import { expandHomePath } from "./os-jank.ts";
import { makeServerPushBus } from "./wsServer/pushBus.ts";
import { makeServerReadiness } from "./wsServer/readiness.ts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
import { assertWorkspaceDirectory, WorkspacePathError } from "./workspacePaths.ts";
/**
* ServerShape - Service API for server lifecycle control.
@@ -233,6 +234,22 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
message: Schema.String,
}) {}
function formatOperationalError(cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
if (
Schema.is(RouteRequestError)(error) ||
Schema.is(WorkspacePathError)(error) ||
(typeof error === "object" &&
error !== null &&
"message" in error &&
typeof error.message === "string" &&
error.message.trim().length > 0)
) {
return (error as { message: string }).message;
}
return Cause.pretty(cause);
}
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
@@ -719,9 +736,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
);
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
@@ -768,6 +785,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.projects.searchEntries");
return yield* Effect.tryPromise({
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
@@ -779,6 +797,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsWriteFile: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.projects.writeFile");
const target = yield* resolveWorkspaceWritePath({
workspaceRoot: body.cwd,
relativePath: body.relativePath,
@@ -807,21 +826,25 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.shellOpenInEditor: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.shell.openInEditor");
return yield* openInEditor(body);
}
case WS_METHODS.gitStatus: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.status");
return yield* gitManager.status(body);
}
case WS_METHODS.gitPull: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.pull");
return yield* git.pullCurrentBranch(body.cwd);
}
case WS_METHODS.gitRunStackedAction: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.runStackedAction");
return yield* gitManager.runStackedAction(body, {
actionId: body.actionId,
progressReporter: {
@@ -833,46 +856,55 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitResolvePullRequest: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.resolvePullRequest");
return yield* gitManager.resolvePullRequest(body);
}
case WS_METHODS.gitPreparePullRequestThread: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.preparePullRequestThread");
return yield* gitManager.preparePullRequestThread(body);
}
case WS_METHODS.gitListBranches: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.listBranches");
return yield* git.listBranches(body);
}
case WS_METHODS.gitCreateWorktree: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.createWorktree");
return yield* git.createWorktree(body);
}
case WS_METHODS.gitRemoveWorktree: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.removeWorktree");
return yield* git.removeWorktree(body);
}
case WS_METHODS.gitCreateBranch: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.createBranch");
return yield* git.createBranch(body);
}
case WS_METHODS.gitCheckout: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.checkout");
return yield* Effect.scoped(git.checkoutBranch(body));
}
case WS_METHODS.gitInit: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.init");
return yield* git.initRepo(body);
}
case WS_METHODS.terminalOpen: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.terminal.open");
return yield* terminalManager.open(body);
}
@@ -893,6 +925,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.terminalRestart: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.terminal.restart");
return yield* terminalManager.restart(body);
}
@@ -973,7 +1006,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
error: { message: Cause.pretty(result.cause) },
error: { message: formatOperationalError(result.cause) },
});
}
+8 -1
View File
@@ -13,6 +13,7 @@ import {
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import { isProjectWorkspaceAvailable, isThreadWorkspaceAvailable } from "../workspaceAvailability";
const envModeItems = [
{ value: "local", label: "Local" },
@@ -46,7 +47,13 @@ export default function BranchToolbar({
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const branchCwd = serverThread
? isThreadWorkspaceAvailable(serverThread)
? serverThread.effectiveCwd
: null
: activeProject && isProjectWorkspaceAvailable(activeProject)
? activeProject.cwd
: null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode = resolveEffectiveEnvMode({
activeWorktreePath,
@@ -397,6 +397,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
style={style}
onClick={() => selectBranch(branch)}
>
+23 -183
View File
@@ -2,11 +2,8 @@
import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_WS_CHANNELS,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
type ServerConfig,
@@ -60,8 +57,6 @@ interface TestFixture {
let fixture: TestFixture;
const wsRequests: WsRequestEnvelope["body"][] = [];
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
let wsClient: { send: (message: string) => void } | null = null;
let pushSequence = 1;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
@@ -122,7 +117,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
@@ -237,6 +232,7 @@ function createSnapshotForTargetUser(options: {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -260,6 +256,9 @@ function createSnapshotForTargetUser(options: {
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -318,6 +317,9 @@ function addThreadToSnapshot(
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -341,79 +343,6 @@ function addThreadToSnapshot(
};
}
function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
return {
sequence,
eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: NOW_ISO,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.created",
payload: {
threadId,
projectId: PROJECT_ID,
title: "New thread",
modelSelection: {
provider: "codex",
model: "gpt-5",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
},
};
}
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
if (!wsClient) {
throw new Error("WebSocket client not connected");
}
wsClient.send(
JSON.stringify({
type: "push",
sequence: pushSequence++,
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
}),
);
}
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
let client: { send: (message: string) => void } | null = null;
await vi.waitFor(
() => {
client = wsClient;
expect(client).toBeTruthy();
},
{ timeout: 8_000, interval: 16 },
);
if (!client) {
throw new Error("WebSocket client not connected");
}
return client;
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await waitForWsClient();
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
sendOrchestrationDomainEvent(
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
}
function createDraftOnlySnapshot(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-target" as MessageId,
@@ -578,12 +507,10 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const worker = setupWorker(
wsLink.addEventListener("connection", ({ client }) => {
wsClient = client;
pushSequence = 1;
client.send(
JSON.stringify({
type: "push",
sequence: pushSequence++,
sequence: 1,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
@@ -955,7 +882,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
useStore.setState({
projects: [],
threads: [],
bootstrapComplete: false,
threadsHydrated: false,
});
});
@@ -1121,19 +1048,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
);
it("shows an explicit empty state for projects without threads in the sidebar", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
});
try {
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd for draft threads without a worktree path", async () => {
setDraftThreadWithoutWorktree();
@@ -1853,87 +1767,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("hides the archive action when the pointer leaves a thread row", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-hover-test" as MessageId,
targetText: "archive hover target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
const archiveButton = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
"Unable to find archive button.",
);
const archiveAction = archiveButton.parentElement;
expect(
archiveAction,
"Archive button should render inside a visibility wrapper.",
).not.toBeNull();
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
await threadRow.hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("1");
},
{ timeout: 4_000, interval: 16 },
);
await page.getByTestId("composer-editor").hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
},
{ timeout: 4_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("shows the confirm archive action after clicking the archive button", async () => {
localStorage.setItem(
"t3code:client-settings:v1",
JSON.stringify({
...DEFAULT_CLIENT_SETTINGS,
confirmThreadArchive: true,
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-confirm-test" as MessageId,
targetText: "archive confirm target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
await threadRow.hover();
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
await expect.element(archiveButton).toBeInTheDocument();
await archiveButton.click();
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
await expect.element(confirmButton).toBeInTheDocument();
await expect.element(confirmButton).toBeVisible();
} finally {
localStorage.removeItem("t3code:client-settings:v1");
await mounted.cleanup();
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1961,16 +1794,21 @@ describe("ChatView timeline estimator parity (full app)", () => {
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the steady-state promotion path: the server emits
// `thread.created`, the client materializes the thread incrementally,
// and the draft is cleared by live batch effects.
await promoteDraftThreadViaDomainEvent(newThreadId);
// Simulate the snapshot sync arriving from the server after the draft
// thread has been promoted to a server thread (thread.create + turn.start
// succeeded). The snapshot now includes the new thread, and the sync
// should clear the draft without disrupting the route.
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
// Clear the draft now that the server thread exists (mirrors EventRouter behavior).
useComposerDraftStore.getState().clearDraftThread(newThreadId);
// The route should still be on the new thread — not redirected away.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after server thread promotion clears the draft.",
"New thread should remain selected after snapshot sync clears the draft.",
);
// The empty thread view and composer should still be visible.
@@ -2292,7 +2130,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
await promoteDraftThreadViaDomainEvent(promotedThreadId);
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
mounted.router,
+3 -297
View File
@@ -1,14 +1,7 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
waitForStartedServerThread,
} from "./ChatView.logic";
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
@@ -74,290 +67,3 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
turnId: TurnId;
state: "running" | "completed";
requestedAt: string;
startedAt: string | null;
completedAt: string | null;
} | null;
}) => ({
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
session: null,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:00.000Z",
latestTurn: input?.latestTurn
? {
...input.latestTurn,
assistantMessageId: null,
}
: null,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
useStore.setState((state) => ({
...state,
projects: [],
threads: [],
bootstrapComplete: true,
}));
});
describe("waitForStartedServerThread", () => {
it("resolves immediately when the thread is already started", async () => {
const threadId = ThreadId.makeUnsafe("thread-started");
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
});
it("waits for the thread to start via subscription updates", async () => {
const threadId = ThreadId.makeUnsafe("thread-wait");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(promise).resolves.toBe(true);
});
it("handles the thread starting between the initial read and subscription setup", async () => {
const threadId = ThreadId.makeUnsafe("thread-race");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const originalSubscribe = useStore.subscribe.bind(useStore);
let raced = false;
vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
if (!raced) {
raced = true;
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-race"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
}
return originalSubscribe(listener);
});
await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true);
});
it("returns false after the timeout when the thread never starts", async () => {
vi.useFakeTimers();
const threadId = ThreadId.makeUnsafe("thread-timeout");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
await vi.advanceTimersByTimeAsync(500);
await expect(promise).resolves.toBe(false);
});
});
describe("hasServerAcknowledgedLocalDispatch", () => {
const projectId = ProjectId.makeUnsafe("project-1");
const previousLatestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed" as const,
requestedAt: "2026-03-29T00:00:00.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: "2026-03-29T00:00:10.000Z",
assistantMessageId: null,
};
const previousSession = {
provider: "codex" as const,
status: "ready" as const,
createdAt: "2026-03-29T00:00:00.000Z",
updatedAt: "2026-03-29T00:00:10.000Z",
orchestrationStatus: "idle" as const,
};
it("does not clear local dispatch before server state changes", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: previousSession,
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(false);
});
it("clears local dispatch when a new turn is already settled", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: {
...previousLatestTurn,
turnId: TurnId.makeUnsafe("turn-2"),
requestedAt: "2026-03-29T00:01:00.000Z",
startedAt: "2026-03-29T00:01:01.000Z",
completedAt: "2026-03-29T00:01:30.000Z",
},
session: {
...previousSession,
updatedAt: "2026-03-29T00:01:30.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
it("clears local dispatch when the session changes without an observed running phase", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: {
...previousSession,
updatedAt: "2026-03-29T00:00:11.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
});
+8 -116
View File
@@ -1,9 +1,8 @@
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -35,8 +34,12 @@ export function buildLocalDraftThread(
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
effectiveCwd: draftThread.worktreePath ?? null,
effectiveCwdSource: draftThread.worktreePath ? "worktree" : null,
effectiveCwdState: "available",
turnDiffSummaries: [],
activities: [],
proposedPlans: [],
@@ -75,6 +78,8 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
@@ -159,116 +164,3 @@ export function buildExpiredTerminalContextToastCopy(
description: "Re-add it if you want that terminal output included.",
};
}
export function threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
);
}
export async function waitForStartedServerThread(
threadId: ThreadId,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId);
const thread = getThread();
if (threadHasStarted(thread)) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
unsubscribe();
resolve(result);
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) {
return;
}
finish(true);
});
if (threadHasStarted(getThread())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, timeoutMs);
});
}
export interface LocalDispatchSnapshot {
startedAt: string;
preparingWorktree: boolean;
latestTurnTurnId: TurnId | null;
latestTurnRequestedAt: string | null;
latestTurnStartedAt: string | null;
latestTurnCompletedAt: string | null;
sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null;
sessionUpdatedAt: string | null;
}
export function createLocalDispatchSnapshot(
activeThread: Thread | undefined,
options?: { preparingWorktree?: boolean },
): LocalDispatchSnapshot {
const latestTurn = activeThread?.latestTurn ?? null;
const session = activeThread?.session ?? null;
return {
startedAt: new Date().toISOString(),
preparingWorktree: Boolean(options?.preparingWorktree),
latestTurnTurnId: latestTurn?.turnId ?? null,
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
latestTurnStartedAt: latestTurn?.startedAt ?? null,
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
sessionOrchestrationStatus: session?.orchestrationStatus ?? null,
sessionUpdatedAt: session?.updatedAt ?? null,
};
}
export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
latestTurn: Thread["latestTurn"] | null;
session: Thread["session"] | null;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
threadError: string | null | undefined;
}): boolean {
if (!input.localDispatch) {
return false;
}
if (
input.phase === "running" ||
input.hasPendingApproval ||
input.hasPendingUserInput ||
Boolean(input.threadError)
) {
return true;
}
const latestTurn = input.latestTurn ?? null;
const session = input.session ?? null;
return (
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
);
}
+253 -244
View File
@@ -20,7 +20,6 @@ import {
OrchestrationThreadActivity,
ProviderInteractionMode,
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { truncate } from "@t3tools/shared/String";
@@ -43,7 +42,6 @@ import {
replaceTextRange,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -66,8 +64,6 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
import { useProjectById, useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -80,12 +76,8 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
type SessionPhase,
type Thread,
type TurnDiffSummary,
} from "../types";
import { LRUCache } from "../lib/lruCache";
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -115,7 +107,6 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
@@ -176,20 +167,22 @@ import {
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
waitForStartedServerThread,
SendPhase,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import {
isProjectWorkspaceAvailable,
isThreadWorkspaceAvailable,
workspaceUnavailableReason,
} from "../workspaceAvailability";
import { useThreadActions } from "../hooks/useThreadActions";
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -202,81 +195,6 @@ const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500;
const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024;
const threadPlanCatalogCache = new LRUCache<{
proposedPlans: Thread["proposedPlans"];
entry: ThreadPlanCatalogEntry;
}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES);
function estimateThreadPlanCatalogEntrySize(thread: Thread): number {
return Math.max(
64,
thread.id.length +
thread.proposedPlans.reduce(
(total, plan) =>
total +
plan.id.length +
plan.planMarkdown.length +
plan.updatedAt.length +
(plan.turnId?.length ?? 0),
0,
),
);
}
function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry {
const cached = threadPlanCatalogCache.get(thread.id);
if (cached && cached.proposedPlans === thread.proposedPlans) {
return cached.entry;
}
const entry: ThreadPlanCatalogEntry = {
id: thread.id,
proposedPlans: thread.proposedPlans,
};
threadPlanCatalogCache.set(
thread.id,
{
proposedPlans: thread.proposedPlans,
entry,
},
estimateThreadPlanCatalogEntrySize(thread),
);
return entry;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
const selector = useMemo(() => {
let previousThreads: Array<Thread | undefined> | null = null;
let previousEntries: ThreadPlanCatalogEntry[] = [];
return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => {
const nextThreads = threadIds.map((threadId) =>
state.threads.find((thread) => thread.id === threadId),
);
const cachedThreads = previousThreads;
if (
cachedThreads &&
nextThreads.length === cachedThreads.length &&
nextThreads.every((thread, index) => thread === cachedThreads[index])
) {
return previousEntries;
}
previousThreads = nextThreads;
previousEntries = nextThreads.flatMap((thread) =>
thread ? [toThreadPlanCatalogEntry(thread)] : [],
);
return previousEntries;
};
}, [threadIds]);
return useStore(selector);
}
function formatOutgoingPrompt(params: {
provider: ProviderKind;
model: string | null;
@@ -332,82 +250,15 @@ interface PendingPullRequestSetupRequest {
scriptId: string;
}
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
phase: SessionPhase;
activePendingApproval: ApprovalRequestId | null;
activePendingUserInput: ApprovalRequestId | null;
threadError: string | null | undefined;
}) {
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
const beginLocalDispatch = useCallback(
(options?: { preparingWorktree?: boolean }) => {
const preparingWorktree = Boolean(options?.preparingWorktree);
setLocalDispatch((current) => {
if (current) {
return current.preparingWorktree === preparingWorktree
? current
: { ...current, preparingWorktree };
}
return createLocalDispatchSnapshot(input.activeThread, options);
});
},
[input.activeThread],
);
const resetLocalDispatch = useCallback(() => {
setLocalDispatch(null);
}, []);
const serverAcknowledgedLocalDispatch = useMemo(
() =>
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: input.phase,
latestTurn: input.activeLatestTurn,
session: input.activeThread?.session ?? null,
hasPendingApproval: input.activePendingApproval !== null,
hasPendingUserInput: input.activePendingUserInput !== null,
threadError: input.threadError,
}),
[
input.activeLatestTurn,
input.activePendingApproval,
input.activePendingUserInput,
input.activeThread?.session,
input.phase,
input.threadError,
localDispatch,
],
);
useEffect(() => {
if (!serverAcknowledgedLocalDispatch) {
return;
}
resetLocalDispatch();
}, [resetLocalDispatch, serverAcknowledgedLocalDispatch]);
return {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt: localDispatch?.startedAt ?? null,
isPreparingWorktree: localDispatch?.preparingWorktree ?? false,
isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch,
};
}
export default function ChatView({ threadId }: ChatViewProps) {
const serverThread = useThreadById(threadId);
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[threadId],
);
const settings = useSettings();
const { confirmAndDeleteThread } = useThreadActions();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
);
@@ -485,6 +336,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
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[]>([]);
@@ -619,7 +472,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
);
const fallbackDraftProject = useProjectById(draftThread?.projectId);
const serverThread = threads.find((t) => t.id === threadId);
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
const localDraftThread = useMemo(
() =>
@@ -647,25 +501,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
const threadIds: ThreadId[] = [];
if (activeThread?.id) {
threadIds.push(activeThread.id);
}
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
threadIds.push(sourceThreadId);
}
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = useProjectById(activeThread?.projectId);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
const projectWorkspaceAvailable = activeProject
? isProjectWorkspaceAvailable(activeProject)
: false;
const threadWorkspaceAvailable = activeThread ? isThreadWorkspaceAvailable(activeThread) : false;
const missingProjectWorkspace = activeProject !== undefined && !projectWorkspaceAvailable;
const missingWorktreeWorkspace =
activeThread?.effectiveCwdSource === "worktree" &&
activeThread.effectiveCwd !== null &&
!threadWorkspaceAvailable &&
projectWorkspaceAvailable;
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -760,28 +611,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
useEffect(() => {
if (!serverThread?.id) return;
if (!activeThread?.id) return;
if (!latestTurnSettled) return;
if (!activeLatestTurn?.completedAt) return;
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnCompletedAt)) return;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
markThreadVisited(serverThread.id);
markThreadVisited(activeThread.id);
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
latestTurnSettled,
markThreadVisited,
serverThread?.id,
]);
const sessionProvider = activeThread?.session?.provider ?? null;
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
const threadProvider =
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
const hasThreadStarted = threadHasStarted(activeThread);
const hasThreadStarted = Boolean(
activeThread &&
(activeThread.latestTurn !== null ||
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -824,6 +680,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
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),
@@ -886,12 +751,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const sidebarProposedPlan = useMemo(
() =>
findSidebarProposedPlan({
threads: threadPlanCatalog,
threads,
latestTurn: activeLatestTurn,
latestTurnSettled,
threadId: activeThread?.id ?? null,
}),
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
);
const activePlan = useMemo(
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -903,27 +768,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
latestTurnSettled &&
hasActionableProposedPlan(activeProposedPlan);
const activePendingApproval = pendingApprovals[0] ?? null;
const {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt,
isPreparingWorktree,
isSendBusy,
} = useLocalDispatchState({
activeThread,
activeLatestTurn,
phase,
activePendingApproval: activePendingApproval?.requestId ?? null,
activePendingUserInput: activePendingUserInput?.requestId ?? null,
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
localDispatchStartedAt,
);
const isComposerApprovalState = activePendingApproval !== null;
const hasComposerHeader =
isComposerApprovalState ||
@@ -1152,15 +996,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!completionSummary) return null;
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
worktreePath: activeThread?.worktreePath ?? null,
})
: null;
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnStartedAt)) return null;
if (Number.isNaN(turnCompletedAt)) return null;
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message") continue;
if (timelineEntry.message.role !== "assistant") continue;
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue;
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}, [
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
completionSummary,
latestTurnSettled,
timelineEntries,
]);
const gitCwd = threadWorkspaceAvailable ? (activeThread?.effectiveCwd ?? null) : null;
const composerTriggerKind = composerTrigger?.kind ?? null;
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
const isPathTrigger = composerTriggerKind === "path";
@@ -1170,7 +1035,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd, threadWorkspaceAvailable));
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const modelOptionsByProvider = useMemo(
@@ -1208,7 +1073,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
projectSearchEntriesQueryOptions({
cwd: gitCwd,
query: effectivePathQuery,
enabled: isPathTrigger,
enabled: isPathTrigger && threadWorkspaceAvailable,
limit: 80,
}),
);
@@ -1306,8 +1171,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: activeThreadWorktreePath,
});
}, [activeProjectCwd, activeThreadWorktreePath]);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const isGitRepo = threadWorkspaceAvailable && (branchesQuery.data?.isRepo ?? true);
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -1376,7 +1240,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
if (threads.some((thread) => thread.id === targetThreadId)) {
setStoreThreadError(targetThreadId, error);
return;
}
@@ -1390,8 +1254,52 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[setStoreThreadError],
[setStoreThreadError, threads],
);
const relinkProjectWorkspace = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeProject) return;
const nextWorkspaceRoot = await api.dialogs.pickFolder();
if (!nextWorkspaceRoot) {
return;
}
await api.orchestration.dispatchCommand({
type: "project.meta.update",
commandId: newCommandId(),
projectId: activeProject.id,
workspaceRoot: nextWorkspaceRoot,
});
}, [activeProject]);
const useProjectRootForThread = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeThread) return;
if (activeThread.session && activeThread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: activeThread.id,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
branch: null,
worktreePath: null,
});
}, [activeThread]);
const removeActiveProject = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeProject) return;
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: newCommandId(),
projectId: activeProject.id,
});
}, [activeProject]);
const focusComposer = useCallback(() => {
composerEditorRef.current?.focusAtEnd();
@@ -1557,7 +1465,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
? {
threadId: activeThreadId,
terminalId: targetTerminalId,
@@ -2166,14 +2074,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
resetLocalDispatch();
setSendPhase("idle");
setSendStartedAt(null);
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [resetLocalDispatch, threadId]);
}, [threadId]);
useEffect(() => {
let cancelled = false;
@@ -2306,6 +2215,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;
@@ -2643,7 +2583,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2717,7 +2657,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
beginSendPhase("preparing-worktree");
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2829,7 +2769,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2886,7 +2826,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetLocalDispatch();
resetSendPhase();
}
};
@@ -3085,7 +3025,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -3154,19 +3094,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetLocalDispatch();
resetSendPhase();
}
},
[
activeThread,
activeProposedPlan,
beginLocalDispatch,
beginSendPhase,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetLocalDispatch,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
@@ -3208,10 +3148,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
const finish = () => {
sendInFlightRef.current = false;
resetLocalDispatch();
resetSendPhase();
};
await api.orchestration
@@ -3246,10 +3186,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt,
});
})
.then(() => {
return waitForStartedServerThread(nextThreadId);
})
.then(() => {
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
@@ -3265,6 +3204,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
@@ -3277,17 +3222,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject,
activeProposedPlan,
activeThread,
beginLocalDispatch,
beginSendPhase,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetLocalDispatch,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
syncServerReadModel,
selectedModel,
]);
@@ -3677,6 +3623,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
}
const headerWorkspaceUnavailableReason = missingProjectWorkspace
? workspaceUnavailableReason({
state: activeProject?.workspaceState ?? "available",
kind: "project",
})
: missingWorktreeWorkspace
? workspaceUnavailableReason({
state: activeThread.effectiveCwdState,
kind: "worktree",
})
: null;
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
{/* Top bar */}
@@ -3691,14 +3649,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
isGitRepo={isGitRepo}
workspaceUnavailableReason={headerWorkspaceUnavailableReason}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
activeProjectScripts={projectWorkspaceAvailable ? activeProject?.scripts : undefined}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalAvailable={activeProject !== undefined && threadWorkspaceAvailable}
terminalOpen={terminalState.terminalOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
@@ -3721,6 +3680,52 @@ export default function ChatView({ threadId }: ChatViewProps) {
error={activeThread.error}
onDismiss={() => setThreadError(activeThread.id, null)}
/>
{missingProjectWorkspace && activeProject && (
<div className="border-b border-amber-200/70 bg-amber-50 px-3 py-3 text-amber-950 sm:px-5 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100">
<div className="flex flex-wrap items-center gap-3">
<div className="flex-1 text-sm">
<div className="font-medium">Project folder is missing</div>
<div className="text-xs text-amber-900/80 dark:text-amber-200/80">
{workspaceUnavailableReason({
state: activeProject.workspaceState,
kind: "project",
})}
</div>
</div>
<Button size="sm" variant="outline" onClick={() => void relinkProjectWorkspace()}>
Relink project
</Button>
<Button size="sm" variant="outline" onClick={() => void removeActiveProject()}>
Remove project
</Button>
</div>
</div>
)}
{missingWorktreeWorkspace && activeThread && (
<div className="border-b border-amber-200/70 bg-amber-50 px-3 py-3 text-amber-950 sm:px-5 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100">
<div className="flex flex-wrap items-center gap-3">
<div className="flex-1 text-sm">
<div className="font-medium">Worktree is missing</div>
<div className="text-xs text-amber-900/80 dark:text-amber-200/80">
{workspaceUnavailableReason({
state: activeThread.effectiveCwdState,
kind: "worktree",
})}
</div>
</div>
<Button size="sm" variant="outline" onClick={() => void useProjectRootForThread()}>
Use project root
</Button>
<Button
size="sm"
variant="outline"
onClick={() => void confirmAndDeleteThread(activeThread.id)}
>
Delete thread
</Button>
</div>
</div>
)}
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 min-w-0 flex-1">
{/* Chat column */}
@@ -3764,7 +3769,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={
projectWorkspaceAvailable ? (activeProject?.cwd ?? undefined) : undefined
}
/>
</div>
@@ -4316,7 +4323,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={
projectWorkspaceAvailable ? (activeProject?.cwd ?? undefined) : undefined
}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
@@ -4332,14 +4341,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* end horizontal flex container */}
{(() => {
if (!terminalState.terminalOpen || !activeProject) {
if (!terminalState.terminalOpen || !activeProject || !threadWorkspaceAvailable || !gitCwd) {
return null;
}
return (
<ThreadTerminalDrawer
key={activeThread.id}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
cwd={gitCwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
@@ -76,6 +76,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -99,6 +100,9 @@ function createMinimalSnapshot(): OrchestrationReadModel {
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -323,7 +327,7 @@ describe("Keybindings update toast", () => {
useStore.setState({
projects: [],
threads: [],
bootstrapComplete: false,
threadsHydrated: false,
});
});
+8 -137
View File
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import {
createThreadJumpHintVisibilityController,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -9,7 +8,6 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -17,9 +15,8 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -30,7 +27,7 @@ import {
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): OrchestrationLatestTurn {
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
return {
turnId: "turn-1" as never,
state: "completed",
@@ -55,68 +52,6 @@ describe("hasUnseenCompletion", () => {
});
});
describe("createThreadJumpHintVisibilityController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delays showing jump hints until the configured delay elapses", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
expect(visibilityChanges).toEqual([]);
vi.advanceTimersByTime(1);
expect(visibilityChanges).toEqual([true]);
});
it("hides immediately when the modifiers are released", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
controller.sync(false);
expect(visibilityChanges).toEqual([true, false]);
});
it("cancels a pending reveal when the modifier is released early", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
controller.sync(false);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
expect(visibilityChanges).toEqual([]);
});
});
describe("shouldClearThreadSelectionOnMouseDown", () => {
it("preserves selection for thread items", () => {
const child = {
@@ -164,50 +99,6 @@ describe("resolveSidebarNewThreadEnvMode", () => {
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
{ id: ProjectId.makeUnsafe("project-3"), name: "Three" },
],
preferredIds: [
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-missing"),
ProjectId.makeUnsafe("project-1"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("does not duplicate items when preferred ids repeat", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
],
preferredIds: [
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
});
describe("resolveAdjacentThreadId", () => {
it("resolves adjacent thread ids in ordered sidebar traversal", () => {
const threads = [
@@ -280,27 +171,6 @@ describe("getVisibleSidebarThreadIds", () => {
ThreadId.makeUnsafe("thread-6"),
]);
});
it("skips threads from collapsed projects whose thread panels are not shown", () => {
expect(
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
});
});
describe("isContextMenuPointerDown", () => {
@@ -559,9 +429,6 @@ describe("getVisibleThreadsForProject", () => {
ThreadId.makeUnsafe("thread-6"),
ThreadId.makeUnsafe("thread-8"),
]);
expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-7"),
]);
});
it("returns all threads when the list is expanded", () => {
@@ -582,7 +449,6 @@ describe("getVisibleThreadsForProject", () => {
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
expect(result.hiddenThreads).toEqual([]);
});
});
@@ -592,11 +458,13 @@ function makeProject(overrides: Partial<Project> = {}): Project {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
...defaultModelSelection,
},
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
@@ -627,6 +495,9 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
turnDiffSummaries: [],
activities: [],
...overrides,
+12 -147
View File
@@ -1,4 +1,3 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
@@ -9,7 +8,6 @@ import {
} from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
@@ -17,10 +15,7 @@ type SidebarProject = {
createdAt?: string | undefined;
updatedAt?: string | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
latestUserMessageAt?: string | null;
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
export type ThreadTraversalDirection = "previous" | "next";
@@ -48,95 +43,8 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
> & {
lastVisitedAt?: string | undefined;
};
export interface ThreadJumpHintVisibilityController {
sync: (shouldShow: boolean) => void;
dispose: () => void;
}
export function createThreadJumpHintVisibilityController(input: {
delayMs: number;
onVisibilityChange: (visible: boolean) => void;
setTimeoutFn?: typeof globalThis.setTimeout;
clearTimeoutFn?: typeof globalThis.clearTimeout;
}): ThreadJumpHintVisibilityController {
const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
let isVisible = false;
let timeoutId: NodeJS.Timeout | null = null;
const clearPendingShow = () => {
if (timeoutId === null) {
return;
}
clearTimeoutFn(timeoutId);
timeoutId = null;
};
return {
sync: (shouldShow) => {
if (!shouldShow) {
clearPendingShow();
if (isVisible) {
isVisible = false;
input.onVisibilityChange(false);
}
return;
}
if (isVisible || timeoutId !== null) {
return;
}
timeoutId = setTimeoutFn(() => {
timeoutId = null;
isVisible = true;
input.onVisibilityChange(true);
}, input.delayMs);
},
dispose: () => {
clearPendingShow();
},
};
}
export function useThreadJumpHintVisibility(): {
showThreadJumpHints: boolean;
updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
} {
const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
React.useEffect(() => {
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
setShowThreadJumpHints(visible);
},
setTimeoutFn: window.setTimeout.bind(window),
clearTimeoutFn: window.clearTimeout.bind(window),
});
controllerRef.current = controller;
return () => {
controller.dispose();
controllerRef.current = null;
};
}, []);
const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
controllerRef.current?.sync(shouldShow);
}, []);
return {
showThreadJumpHints,
updateThreadJumpHintsVisibility,
};
}
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -161,46 +69,15 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
getId: (item: TItem) => TId;
}): TItem[] {
const { getId, items, preferredIds } = input;
if (preferredIds.length === 0) {
return [...items];
}
const itemsById = new Map(items.map((item) => [getId(item), item] as const));
const preferredIdSet = new Set(preferredIds);
const emittedPreferredIds = new Set<TId>();
const ordered = preferredIds.flatMap((id) => {
if (emittedPreferredIds.has(id)) {
return [];
}
const item = itemsById.get(id);
if (!item) {
return [];
}
emittedPreferredIds.add(id);
return [item];
});
const remaining = items.filter((item) => !preferredIdSet.has(getId(item)));
return [...ordered, ...remaining];
}
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.renderedThreads.map((thread) => thread.id),
);
}
@@ -360,15 +237,14 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
threads: readonly T[];
activeThreadId: T["id"] | undefined;
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
visibleThreads: T[];
hiddenThreads: T[];
visibleThreads: Thread[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
@@ -376,7 +252,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
hiddenThreads: [],
visibleThreads: [...threads],
};
}
@@ -385,7 +260,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -394,7 +268,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!activeThread) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -403,7 +276,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
return {
hasHiddenThreads: true,
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
@@ -415,13 +287,9 @@ function toSortableTimestamp(iso: string | undefined): number | null {
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
if (thread.latestUserMessageAt) {
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
}
let latestUserMessageTimestamp: number | null = null;
for (const message of thread.messages ?? []) {
for (const message of thread.messages) {
if (message.role !== "user") continue;
const messageTimestamp = toSortableTimestamp(message.createdAt);
if (messageTimestamp === null) continue;
@@ -449,7 +317,7 @@ function getThreadSortTimestamp(
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
@@ -462,7 +330,7 @@ export function sortThreadsForSidebar<
}
export function getFallbackThreadIdAfterDelete<
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
>(input: {
threads: readonly T[];
deletedThreadId: T["id"];
@@ -506,10 +374,7 @@ export function getProjectSortTimestamp(
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<
TProject extends SidebarProject,
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
+148 -316
View File
@@ -21,7 +21,6 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { useShallow } from "zustand/react/shallow";
import {
DndContext,
type DragCancelEvent,
@@ -56,7 +55,6 @@ import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import {
resolveShortcutCommand,
shortcutLabelForCommand,
@@ -71,7 +69,6 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useThreadActions } from "../hooks/useThreadActions";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
@@ -116,16 +113,14 @@ import {
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
useThreadJumpHintVisibility,
} from "./Sidebar.logic";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import type { Project, Thread } from "../types";
import { isProjectWorkspaceAvailable, isThreadWorkspaceAvailable } from "../workspaceAvailability";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -142,80 +137,6 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = {
duration: 180,
easing: "ease-out",
} as const;
type SidebarThreadSnapshot = Pick<
Thread,
| "activities"
| "archivedAt"
| "branch"
| "createdAt"
| "id"
| "interactionMode"
| "latestTurn"
| "projectId"
| "proposedPlans"
| "session"
| "title"
| "updatedAt"
| "worktreePath"
> & {
lastVisitedAt?: string | undefined;
latestUserMessageAt: string | null;
};
type SidebarProjectSnapshot = Project & {
expanded: boolean;
};
const sidebarThreadSnapshotCache = new WeakMap<
Thread,
{ lastVisitedAt?: string | undefined; snapshot: SidebarThreadSnapshot }
>();
function getLatestUserMessageAt(thread: Thread): string | null {
let latestUserMessageAt: string | null = null;
for (const message of thread.messages) {
if (message.role !== "user") {
continue;
}
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
latestUserMessageAt = message.createdAt;
}
}
return latestUserMessageAt;
}
function toSidebarThreadSnapshot(
thread: Thread,
lastVisitedAt: string | undefined,
): SidebarThreadSnapshot {
const cached = sidebarThreadSnapshotCache.get(thread);
if (cached && cached.lastVisitedAt === lastVisitedAt) {
return cached.snapshot;
}
const snapshot: SidebarThreadSnapshot = {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
interactionMode: thread.interactionMode,
session: thread.session,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
latestTurn: thread.latestTurn,
lastVisitedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
activities: thread.activities,
proposedPlans: thread.proposedPlans,
latestUserMessageAt: getLatestUserMessageAt(thread),
};
sidebarThreadSnapshotCache.set(thread, { lastVisitedAt, snapshot });
return snapshot;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
@@ -231,44 +152,6 @@ interface PrStatusIndicator {
type ThreadPr = GitStatusResult["pr"];
function ThreadStatusLabel({
status,
compact = false,
}: {
status: NonNullable<ReturnType<typeof resolveThreadStatusPill>>;
compact?: boolean;
}) {
if (compact) {
return (
<span
title={status.label}
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="sr-only">{status.label}</span>
</span>
);
}
return (
<span
title={status.label}
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
</span>
);
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
@@ -439,17 +322,10 @@ function SortableProjectItem({
export default function Sidebar() {
const projects = useStore((store) => store.projects);
const serverThreads = useStore((store) => store.threads);
const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore(
useShallow((store) => ({
projectExpandedById: store.projectExpandedById,
projectOrder: store.projectOrder,
threadLastVisitedAtById: store.threadLastVisitedAtById,
})),
);
const markThreadUnread = useUiStateStore((store) => store.markThreadUnread);
const toggleProject = useUiStateStore((store) => store.toggleProject);
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
const threads = useStore((store) => store.threads);
const markThreadUnread = useStore((store) => store.markThreadUnread);
const toggleProject = useStore((store) => store.toggleProject);
const reorderProjects = useStore((store) => store.reorderProjects);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
@@ -481,14 +357,14 @@ export default function Sidebar() {
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [hoveredThreadId, setHoveredThreadId] = useState<ThreadId | null>(null);
const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState<ThreadId | null>(null);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
const [showThreadJumpHints, setShowThreadJumpHints] = useState(false);
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<ThreadId, HTMLButtonElement>());
const dragInProgressRef = useRef(false);
const suppressProjectClickAfterDragRef = useRef(false);
const suppressProjectClickForContextMenuRef = useRef(false);
@@ -503,28 +379,6 @@ export default function Sidebar() {
const platform = navigator.platform;
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
preferredIds: projectOrder,
getId: (project) => project.id,
});
}, [projectOrder, projects]);
const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(
() =>
orderedProjects.map((project) => ({
...project,
expanded: projectExpandedById[project.id] ?? true,
})),
[orderedProjects, projectExpandedById],
);
const threads = useMemo(
() =>
serverThreads.map((thread) =>
toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]),
),
[serverThreads, threadLastVisitedAtById],
);
const projectCwdById = useMemo(
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
@@ -547,15 +401,16 @@ export default function Sidebar() {
threads.map((thread) => ({
threadId: thread.id,
branch: thread.branch,
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
cwd: thread.effectiveCwd,
enabled: isThreadWorkspaceAvailable(thread),
})),
[projectCwdById, threads],
[threads],
);
const threadGitStatusCwds = useMemo(
() => [
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.filter((target) => target.enabled && target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
@@ -564,7 +419,7 @@ export default function Sidebar() {
);
const threadGitStatusQueries = useQueries({
queries: threadGitStatusCwds.map((cwd) => ({
...gitStatusQueryOptions(cwd),
...gitStatusQueryOptions(cwd, true),
staleTime: 30_000,
refetchInterval: 60_000,
})),
@@ -859,7 +714,7 @@ export default function Sidebar() {
}
if (clicked === "mark-unread") {
markThreadUnread(threadId, thread.latestTurn?.completedAt);
markThreadUnread(threadId);
return;
}
if (clicked === "copy-path") {
@@ -921,8 +776,7 @@ export default function Sidebar() {
if (clicked === "mark-unread") {
for (const id of ids) {
const thread = threads.find((candidate) => candidate.id === id);
markThreadUnread(id, thread?.latestTurn?.completedAt);
markThreadUnread(id);
}
clearSelection();
return;
@@ -953,7 +807,6 @@ export default function Sidebar() {
markThreadUnread,
removeFromSelection,
selectedThreadIds,
threads,
],
);
@@ -1096,12 +949,12 @@ export default function Sidebar() {
dragInProgressRef.current = false;
const { active, over } = event;
if (!over || active.id === over.id) return;
const activeProject = sidebarProjects.find((project) => project.id === active.id);
const overProject = sidebarProjects.find((project) => project.id === over.id);
const activeProject = projects.find((project) => project.id === active.id);
const overProject = projects.find((project) => project.id === over.id);
if (!activeProject || !overProject) return;
reorderProjects(activeProject.id, overProject.id);
},
[appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects],
[appSettings.sidebarProjectSortOrder, projects, reorderProjects],
);
const handleProjectDragStart = useCallback(
@@ -1161,9 +1014,8 @@ export default function Sidebar() {
[threads],
);
const sortedProjects = useMemo(
() =>
sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads],
() => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, projects, visibleThreads],
);
const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
const renderedProjects = useMemo(
@@ -1173,18 +1025,14 @@ export default function Sidebar() {
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const threadStatuses = new Map(
projectThreads.map((thread) => [
thread.id,
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) =>
resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
}),
]),
);
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
),
);
const activeThreadId = routeThreadId ?? undefined;
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
@@ -1193,35 +1041,25 @@ export default function Sidebar() {
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const {
hasHiddenThreads,
hiddenThreads,
visibleThreads: visibleProjectThreads,
} = getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const hiddenThreadStatus = resolveProjectStatusIndicator(
hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const { hasHiddenThreads, visibleThreads: visibleProjectThreads } =
getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = pinnedCollapsedThread
? [pinnedCollapsedThread]
: visibleProjectThreads;
const showEmptyThreadState = project.expanded && projectThreads.length === 0;
return {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
};
@@ -1234,22 +1072,23 @@ export default function Sidebar() {
visibleThreads,
],
);
const visibleSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const threadJumpCommandById = useMemo(() => {
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
let visibleThreadIndex = 0;
for (const renderedProject of renderedProjects) {
for (const thread of renderedProject.renderedThreads) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(thread.id, jumpCommand);
visibleThreadIndex += 1;
}
mapping.set(threadId, jumpCommand);
}
return mapping;
}, [visibleSidebarThreadIds]);
}, [renderedProjects]);
const threadJumpThreadIds = useMemo(
() => [...threadJumpCommandById.keys()],
[threadJumpCommandById],
@@ -1264,7 +1103,10 @@ export default function Sidebar() {
}
return mapping;
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
const orderedSidebarThreadIds = visibleSidebarThreadIds;
const orderedSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
useEffect(() => {
const getShortcutContext = () => ({
@@ -1273,7 +1115,7 @@ export default function Sidebar() {
});
const onWindowKeyDown = (event: KeyboardEvent) => {
updateThreadJumpHintsVisibility(
setShowThreadJumpHints(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1321,7 +1163,7 @@ export default function Sidebar() {
};
const onWindowKeyUp = (event: KeyboardEvent) => {
updateThreadJumpHintsVisibility(
setShowThreadJumpHints(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1330,7 +1172,7 @@ export default function Sidebar() {
};
const onWindowBlur = () => {
updateThreadJumpHintsVisibility(false);
setShowThreadJumpHints(false);
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1350,7 +1192,6 @@ export default function Sidebar() {
routeTerminalOpen,
routeThreadId,
threadJumpThreadIds,
updateThreadJumpHintsVisibility,
]);
function renderProjectItem(
@@ -1359,63 +1200,54 @@ export default function Sidebar() {
) {
const {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
} = renderedProject;
const projectWorkspaceAvailable = isProjectWorkspaceAvailable(project);
const renderThreadRow = (thread: (typeof projectThreads)[number]) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const threadWorkspaceAvailable = isThreadWorkspaceAvailable(thread);
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = threadStatuses.get(thread.id) ?? null;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseLeave={() => {
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
onMouseEnter={() => {
setHoveredThreadId(thread.id);
}}
onBlurCapture={(event) => {
const currentTarget = event.currentTarget;
requestAnimationFrame(() => {
if (currentTarget.contains(document.activeElement)) {
return;
}
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
});
onMouseLeave={() => {
setHoveredThreadId((current) => (current === thread.id ? null : current));
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
}}
>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
data-testid={`thread-row-${thread.id}`}
className={`${resolveThreadRowClassName({
isActive,
isSelected,
})} relative isolate`}
})} relative ${threadWorkspaceAvailable ? "" : "opacity-60"}`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
@@ -1426,6 +1258,7 @@ export default function Sidebar() {
}}
onContextMenu={(event) => {
event.preventDefault();
setHoveredThreadId((current) => (current === thread.id ? null : current));
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
@@ -1462,7 +1295,18 @@ export default function Sidebar() {
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
@@ -1512,18 +1356,10 @@ export default function Sidebar() {
</span>
)}
<div className="flex min-w-12 justify-end">
{isConfirmingArchive ? (
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
<button
ref={(element) => {
if (element) {
confirmArchiveButtonRefs.current.set(thread.id, element);
} else {
confirmArchiveButtonRefs.current.delete(thread.id);
}
}}
type="button"
data-thread-selection-safe
data-testid={`thread-archive-confirm-${thread.id}`}
aria-label={`Confirm archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
onPointerDown={(event) => {
@@ -1535,84 +1371,80 @@ export default function Sidebar() {
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
setHoveredThreadId((current) => (current === thread.id ? null : current));
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : !isThreadRunning ? (
) : hoveredThreadId === thread.id && !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
});
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
) : (
<Tooltip>
<TooltipTrigger
render={
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setHoveredThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : null}
<span className={threadMetaClassName}>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</span>
) : (
<>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</>
)}
</div>
</div>
</SidebarMenuSubButton>
@@ -1628,7 +1460,7 @@ export default function Sidebar() {
size="sm"
className={`gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground ${
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
}`}
} ${projectWorkspaceAvailable ? "" : "opacity-60"}`}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}
onPointerDownCapture={handleProjectTitlePointerDownCapture}
@@ -1707,16 +1539,6 @@ export default function Sidebar() {
ref={attachThreadListAutoAnimateRef}
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
>
{shouldShowThreadPanel && showEmptyThreadState ? (
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
<div
data-thread-selection-safe
className="flex h-6 w-full translate-x-0 items-center px-2 text-left text-[10px] text-muted-foreground/60"
>
<span>No threads yet</span>
</div>
</SidebarMenuSubItem>
) : null}
{shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))}
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
@@ -1730,10 +1552,7 @@ export default function Sidebar() {
expandThreadListForProject(project.id);
}}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />}
<span>Show more</span>
</span>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
@@ -2044,6 +1863,7 @@ export default function Sidebar() {
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
@@ -2094,6 +1914,18 @@ export default function Sidebar() {
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
@@ -50,7 +50,6 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
<div key={`dir:${node.path}`}>
<button
type="button"
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
+16 -7
View File
@@ -19,6 +19,7 @@ interface ChatHeaderProps {
activeThreadTitle: string;
activeProjectName: string | undefined;
isGitRepo: boolean;
workspaceUnavailableReason?: string | null;
openInCwd: string | null;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
@@ -43,6 +44,7 @@ export const ChatHeader = memo(function ChatHeader({
activeThreadTitle,
activeProjectName,
isGitRepo,
workspaceUnavailableReason,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -76,11 +78,16 @@ export const ChatHeader = memo(function ChatHeader({
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
{activeProjectName && !isGitRepo && (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
</Badge>
)}
{activeProjectName &&
(workspaceUnavailableReason ? (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
Workspace Missing
</Badge>
) : !isGitRepo ? (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
</Badge>
) : null)}
</div>
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
{activeProjectScripts && (
@@ -120,7 +127,8 @@ export const ChatHeader = memo(function ChatHeader({
/>
<TooltipPopup side="bottom">
{!terminalAvailable
? "Terminal is unavailable until this thread has an active project."
? (workspaceUnavailableReason ??
"Terminal is unavailable until this thread has an active project.")
: terminalToggleShortcutLabel
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
@@ -144,7 +152,8 @@ export const ChatHeader = memo(function ChatHeader({
/>
<TooltipPopup side="bottom">
{!isGitRepo
? "Diff panel is unavailable because this project is not a git repository."
? (workspaceUnavailableReason ??
"Diff panel is unavailable because this project is not a git repository.")
: diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
@@ -1,5 +1,5 @@
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
import { memo, useLayoutEffect, useRef } from "react";
import { memo } from "react";
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
import { BotIcon } from "lucide-react";
import { cn } from "~/lib/utils";
@@ -41,19 +41,8 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
const listRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (!props.activeItemId || !listRef.current) return;
const el = listRef.current.querySelector<HTMLElement>(
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
);
el?.scrollIntoView({ block: "nearest" });
}, [props.activeItemId]);
return (
<Command
autoHighlight={false}
mode="none"
onItemHighlighted={(highlightedValue) => {
props.onHighlightedItemChange(
@@ -61,10 +50,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div
ref={listRef}
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
<CommandList className="max-h-64">
{props.items.map((item) => (
<ComposerCommandMenuItem
@@ -72,7 +58,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
@@ -95,20 +80,15 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
item: ComposerCommandItem;
resolvedTheme: "light" | "dark";
isActive: boolean;
onHighlight: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
return (
<CommandItem
value={props.item.id}
data-composer-item-id={props.item.id}
className={cn(
"cursor-pointer select-none gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
props.isActive && "bg-accent! text-accent-foreground!",
"cursor-pointer select-none gap-2",
props.isActive && "bg-accent text-accent-foreground",
)}
onMouseMove={() => {
if (!props.isActive) props.onHighlight(props.item.id);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -264,14 +264,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
rowVirtualizer.measure();
}, [rowVirtualizer, timelineWidthPx]);
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const itemIntersectsViewport =
item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
if (itemIntersectsViewport) {
return false;
}
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
@@ -488,7 +483,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
@@ -22,7 +22,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
@@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
@@ -110,19 +110,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
},
];
function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {
return {
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models,
};
}
async function mountPicker(props: {
provider: ProviderKind;
model: string;
@@ -254,93 +241,6 @@ describe("ProviderModelPicker", () => {
}
});
it("only shows codex spark when the server reports it for the account", async () => {
const providersWithoutSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const providersWithSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "GPT-5.3 Codex Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const hidden = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithoutSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("GPT-5.3 Codex");
expect(text).not.toContain("GPT-5.3 Codex Spark");
});
} finally {
await hidden.cleanup();
}
const visible = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark");
});
} finally {
await visible.cleanup();
}
});
it("dispatches the canonical slug when a model is selected", async () => {
const mounted = await mountPicker({
provider: "claudeAgent",
@@ -35,7 +35,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -61,7 +61,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -71,41 +71,6 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
describe("getComposerProviderState", () => {
it("returns codex defaults when no codex draft options exist", () => {
const state = getComposerProviderState({
@@ -191,7 +156,6 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: false,
},
});
});
@@ -304,116 +268,7 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
fastMode: false,
},
});
});
it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => {
// Regression: normalizeClaudeModelOptionsWithCapabilities used to strip
// fastMode: false, which meant deepMerge could never clear a previous true.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: false,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => {
// Regression: thinking: true (the default) used to be stripped, which
// meant deepMerge could never clear a previous thinking: false.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
thinking: true,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default context window explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toMatchObject({
effort: "high",
contextWindow: "200k",
});
});
it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => {
// Regression: the default contextWindow must survive normalization so
// deepMerge can clear an older non-default 1m selection.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k");
});
it("omits contextWindow when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "1m",
},
},
});
expect(state.modelOptionsForDispatch).toBeUndefined();
});
it("omits fastMode when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: true,
},
},
});
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
});
});
@@ -6,12 +6,12 @@ import {
} from "@t3tools/contracts";
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
import type { ReactNode } from "react";
import { getProviderModelCapabilities } from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
import {
getProviderModelCapabilities,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
} from "@t3tools/shared/model";
} from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
export type ComposerProviderStateInput = {
provider: ProviderKind;
@@ -12,19 +12,14 @@ import {
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ClaudeSettings,
ClientSettingsSchema,
CodexSettings,
PROVIDER_DISPLAY_NAMES,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
ServerSettings,
ThreadId,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { getSchemaDescription } from "@t3tools/shared/schemaJson";
import { Equal } from "effect";
import { APP_VERSION } from "../../branding";
import {
@@ -86,51 +81,6 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
function requireSchemaDescription(
schema: Parameters<typeof getSchemaDescription>[0],
label: string,
) {
const description = getSchemaDescription(schema);
if (!description) {
throw new Error(`Missing schema description for ${label}`);
}
return description;
}
const SETTINGS_DESCRIPTIONS = {
timestampFormat: requireSchemaDescription(
ClientSettingsSchema.fields.timestampFormat,
"ClientSettings.timestampFormat",
),
diffWordWrap: requireSchemaDescription(
ClientSettingsSchema.fields.diffWordWrap,
"ClientSettings.diffWordWrap",
),
confirmThreadArchive: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadArchive,
"ClientSettings.confirmThreadArchive",
),
confirmThreadDelete: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadDelete,
"ClientSettings.confirmThreadDelete",
),
enableAssistantStreaming: requireSchemaDescription(
ServerSettings.fields.enableAssistantStreaming,
"ServerSettings.enableAssistantStreaming",
),
defaultThreadEnvMode: requireSchemaDescription(
ServerSettings.fields.defaultThreadEnvMode,
"ServerSettings.defaultThreadEnvMode",
),
textGenerationModelSelection: requireSchemaDescription(
ServerSettings.fields.textGenerationModelSelection,
"ServerSettings.textGenerationModelSelection",
),
codexBinaryPath: requireSchemaDescription(CodexSettings.fields.binaryPath, "Codex.binaryPath"),
codexHomePath: requireSchemaDescription(CodexSettings.fields.homePath, "Codex.homePath"),
claudeBinaryPath: requireSchemaDescription(ClaudeSettings.fields.binaryPath, "Claude.binaryPath"),
} as const;
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
type InstallProviderSettings = {
@@ -148,16 +98,16 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
provider: "codex",
title: "Codex",
binaryPlaceholder: "Codex binary path",
binaryDescription: SETTINGS_DESCRIPTIONS.codexBinaryPath,
binaryDescription: "Path to the Codex binary",
homePathKey: "codexHomePath",
homePlaceholder: "CODEX_HOME",
homeDescription: SETTINGS_DESCRIPTIONS.codexHomePath,
homeDescription: "Optional custom Codex home and config directory.",
},
{
provider: "claudeAgent",
title: "Claude",
binaryPlaceholder: "Claude binary path",
binaryDescription: SETTINGS_DESCRIPTIONS.claudeBinaryPath,
binaryDescription: "Path to the Claude binary",
},
] as const;
@@ -196,14 +146,13 @@ function getProviderSummary(provider: ServerProvider | undefined) {
detail: provider.message ?? "CLI not detected on PATH.",
};
}
if (provider.auth.status === "authenticated") {
const authLabel = provider.auth.label ?? provider.auth.type;
if (provider.authStatus === "authenticated") {
return {
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
headline: "Authenticated",
detail: provider.message ?? null,
};
}
if (provider.auth.status === "unauthenticated") {
if (provider.authStatus === "unauthenticated") {
return {
headline: "Not authenticated",
detail: provider.message ?? null,
@@ -824,7 +773,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Time format"
description={SETTINGS_DESCRIPTIONS.timestampFormat}
description="System default follows your browser or OS clock preference."
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
<SettingResetButton
@@ -866,7 +815,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Diff line wrapping"
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
description="Set the default wrap state when the diff panel opens."
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
<SettingResetButton
@@ -890,7 +839,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Assistant output"
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
description="Show token-by-token output while a response is in progress."
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
@@ -917,7 +866,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="New threads"
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
description="Pick the default workspace mode for newly created draft threads."
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
<SettingResetButton
@@ -958,7 +907,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Archive confirmation"
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
description="Require a second click on the inline archive action before a thread is archived."
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
<SettingResetButton
@@ -984,7 +933,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Delete confirmation"
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
description="Ask before deleting a thread and its chat history."
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
<SettingResetButton
@@ -1010,7 +959,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Text generation model"
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
resetAction={
isGitWritingModelDirty ? (
<SettingResetButton
+1 -1
View File
@@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti
return (
<AutocompletePrimitive.Item
className={cn(
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
className,
)}
data-slot="autocomplete-item"
+1 -1
View File
@@ -195,7 +195,7 @@ function ComboboxItem({
return (
<ComboboxPrimitive.Item
className={cn(
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
data-slot="combobox-item"
-53
View File
@@ -9,8 +9,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
COMPOSER_DRAFT_STORAGE_KEY,
clearPromotedDraftThread,
clearPromotedDraftThreads,
type ComposerImageAttachment,
useComposerDraftStore,
} from "./composerDraftStore";
@@ -551,57 +549,6 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears a promoted draft by thread id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("does not clear composer drafts for existing server threads during promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears promoted drafts from an iterable of server thread ids", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
store.setProjectDraftThreadId(otherProjectId, otherThreadId);
store.setPrompt(otherThreadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
expect(
useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,
).toBe(otherThreadId);
expect(useComposerDraftStore.getState().draftsByThreadId[otherThreadId]?.prompt).toBe(
"keep me",
);
});
it("keeps existing server-thread composer drafts during iterable promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
+11 -14
View File
@@ -2195,21 +2195,18 @@ export function useEffectiveComposerModelState(input: {
}
/**
* Clear a draft thread once the server has materialized the same thread id.
* Clear draft threads that have been promoted to server threads.
*
* Use the single-thread helper for live `thread.created` events and the
* iterable helper for bootstrap/recovery paths that discover multiple server
* threads at once.
* Call this after a snapshot sync so the route guard in `_chat.$threadId`
* sees the server thread before the draft is removed — avoids a redirect
* to `/` caused by a gap where neither draft nor server thread exists.
*/
export function clearPromotedDraftThread(threadId: ThreadId): void {
if (!useComposerDraftStore.getState().getDraftThread(threadId)) {
return;
}
useComposerDraftStore.getState().clearDraftThread(threadId);
}
export function clearPromotedDraftThreads(serverThreadIds: Iterable<ThreadId>): void {
for (const threadId of serverThreadIds) {
clearPromotedDraftThread(threadId);
export function clearPromotedDraftThreads(serverThreadIds: ReadonlySet<ThreadId>): void {
const store = useComposerDraftStore.getState();
const draftThreadIds = Object.keys(store.draftThreadsByThreadId) as ThreadId[];
for (const draftId of draftThreadIds) {
if (serverThreadIds.has(draftId)) {
store.clearDraftThread(draftId);
}
}
}
+8 -16
View File
@@ -1,37 +1,29 @@
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useCallback } from "react";
import {
type DraftThreadEnvMode,
type DraftThreadState,
useComposerDraftStore,
} from "../composerDraftStore";
import { newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { useStore } from "../store";
import { useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const navigate = useNavigate();
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const activeThread = useThreadById(routeThreadId);
const activeDraftThread = useComposerDraftStore((store) =>
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projectIds,
preferredIds: projectOrder,
getId: (projectId) => projectId,
});
}, [projectIds, projectOrder]);
const activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
const handleNewThread = useCallback(
(
@@ -119,8 +111,8 @@ export function useHandleNewThread() {
return {
activeDraftThread,
activeThread,
defaultProjectId: orderedProjects[0] ?? null,
handleNewThread,
projects,
routeThreadId,
};
}
+13 -6
View File
@@ -14,8 +14,11 @@ import { useTerminalStateStore } from "../terminalStateStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
import { isProjectWorkspaceAvailable } from "../workspaceAvailability";
export function useThreadActions() {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const appSettings = useSettings();
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
@@ -35,7 +38,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
@@ -51,7 +54,7 @@ export function useThreadActions() {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId],
[handleNewThread, routeThreadId, threads],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
@@ -68,7 +71,6 @@ export function useThreadActions() {
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
if (!api) return;
const { projects, threads } = useStore.getState();
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
@@ -81,7 +83,10 @@ export function useThreadActions() {
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const canDeleteWorktree =
orphanedWorktreePath !== null &&
threadProject !== undefined &&
isProjectWorkspaceAvailable(threadProject);
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
@@ -170,8 +175,10 @@ export function useThreadActions() {
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
@@ -179,7 +186,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
@@ -196,7 +203,7 @@ export function useThreadActions() {
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread],
[appSettings.confirmThreadDelete, deleteThread, threads],
);
return {
+10 -9
View File
@@ -26,7 +26,7 @@ export function invalidateGitQueries(queryClient: QueryClient) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function gitStatusQueryOptions(cwd: string | null) {
export function gitStatusQueryOptions(cwd: string | null, enabled = true) {
return queryOptions({
queryKey: gitQueryKeys.status(cwd),
queryFn: async () => {
@@ -34,15 +34,15 @@ export function gitStatusQueryOptions(cwd: string | null) {
if (!cwd) throw new Error("Git status is unavailable.");
return api.git.status({ cwd });
},
enabled: cwd !== null,
enabled: enabled && cwd !== null,
staleTime: GIT_STATUS_STALE_TIME_MS,
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
});
}
export function gitBranchesQueryOptions(cwd: string | null) {
export function gitBranchesQueryOptions(cwd: string | null, enabled = true) {
return queryOptions({
queryKey: gitQueryKeys.branches(cwd),
queryFn: async () => {
@@ -50,10 +50,10 @@ export function gitBranchesQueryOptions(cwd: string | null) {
if (!cwd) throw new Error("Git branches are unavailable.");
return api.git.listBranches({ cwd });
},
enabled: cwd !== null,
enabled: enabled && cwd !== null,
staleTime: GIT_BRANCHES_STALE_TIME_MS,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
});
}
@@ -61,6 +61,7 @@ export function gitBranchesQueryOptions(cwd: string | null) {
export function gitResolvePullRequestQueryOptions(input: {
cwd: string | null;
reference: string | null;
enabled?: boolean;
}) {
return queryOptions({
queryKey: ["git", "pull-request", input.cwd, input.reference] as const,
@@ -71,7 +72,7 @@ export function gitResolvePullRequestQueryOptions(input: {
}
return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
},
enabled: input.cwd !== null && input.reference !== null,
enabled: (input.enabled ?? true) && input.cwd !== null && input.reference !== null,
staleTime: 30_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
+2
View File
@@ -39,5 +39,7 @@ export function projectSearchEntriesQueryOptions(input: {
enabled: (input.enabled ?? true) && input.cwd !== null && input.query.length > 0,
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
}
@@ -1,108 +0,0 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects";
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
describe("deriveOrchestrationBatchEffects", () => {
it("targets draft promotion and terminal cleanup from thread lifecycle events", () => {
const createdThreadId = ThreadId.makeUnsafe("thread-created");
const deletedThreadId = ThreadId.makeUnsafe("thread-deleted");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.created", {
threadId: createdThreadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Created thread",
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
}),
makeEvent("thread.deleted", {
threadId: deletedThreadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]);
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]);
expect(effects.needsProviderInvalidation).toBe(false);
});
it("keeps only the final lifecycle outcome for a thread within one batch", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.deleted", {
threadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
makeEvent("thread.created", {
threadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Recreated thread",
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
}),
makeEvent("thread.turn-diff-completed", {
threadId,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:03.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([threadId]);
expect(effects.clearDeletedThreadIds).toEqual([]);
expect(effects.removeTerminalStateThreadIds).toEqual([]);
expect(effects.needsProviderInvalidation).toBe(true);
});
});
-76
View File
@@ -1,76 +0,0 @@
import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
export interface OrchestrationBatchEffects {
clearPromotedDraftThreadIds: ThreadId[];
clearDeletedThreadIds: ThreadId[];
removeTerminalStateThreadIds: ThreadId[];
needsProviderInvalidation: boolean;
}
export function deriveOrchestrationBatchEffects(
events: readonly OrchestrationEvent[],
): OrchestrationBatchEffects {
const threadLifecycleEffects = new Map<
ThreadId,
{
clearPromotedDraft: boolean;
clearDeletedThread: boolean;
removeTerminalState: boolean;
}
>();
let needsProviderInvalidation = false;
for (const event of events) {
switch (event.type) {
case "thread.turn-diff-completed":
case "thread.reverted": {
needsProviderInvalidation = true;
break;
}
case "thread.created": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: true,
clearDeletedThread: false,
removeTerminalState: false,
});
break;
}
case "thread.deleted": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: false,
clearDeletedThread: true,
removeTerminalState: true,
});
break;
}
default: {
break;
}
}
}
const clearPromotedDraftThreadIds: ThreadId[] = [];
const clearDeletedThreadIds: ThreadId[] = [];
const removeTerminalStateThreadIds: ThreadId[] = [];
for (const [threadId, effect] of threadLifecycleEffects) {
if (effect.clearPromotedDraft) {
clearPromotedDraftThreadIds.push(threadId);
}
if (effect.clearDeletedThread) {
clearDeletedThreadIds.push(threadId);
}
if (effect.removeTerminalState) {
removeTerminalStateThreadIds.push(threadId);
}
}
return {
clearPromotedDraftThreadIds,
clearDeletedThreadIds,
removeTerminalStateThreadIds,
needsProviderInvalidation,
};
}
-100
View File
@@ -1,100 +0,0 @@
import { describe, expect, it } from "vitest";
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
describe("createOrchestrationRecoveryCoordinator", () => {
it("defers live events until bootstrap completes and then requests replay", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true);
expect(coordinator.classifyDomainEvent(4)).toBe("defer");
expect(coordinator.completeSnapshotRecovery(2)).toBe(true);
expect(coordinator.getState()).toMatchObject({
latestSequence: 2,
highestObservedSequence: 4,
bootstrapped: true,
pendingReplay: false,
inFlight: null,
});
});
it("classifies sequence gaps as recovery-only replay work", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(5)).toBe("recover");
expect(coordinator.beginReplayRecovery("sequence-gap")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "replay",
reason: "sequence-gap",
});
});
it("tracks live event batches without entering recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(4)).toBe("apply");
expect(coordinator.markEventBatchApplied([{ sequence: 4 }])).toEqual([{ sequence: 4 }]);
expect(coordinator.getState()).toMatchObject({
latestSequence: 4,
highestObservedSequence: 4,
bootstrapped: true,
inFlight: null,
});
});
it("requests another replay when deferred events arrive during replay recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.classifyDomainEvent(7);
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
expect(coordinator.completeReplayRecovery()).toBe(true);
});
it("does not immediately replay again when replay returns no new events", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
expect(coordinator.completeReplayRecovery()).toBe(false);
expect(coordinator.getState()).toMatchObject({
latestSequence: 3,
highestObservedSequence: 5,
pendingReplay: false,
inFlight: null,
});
});
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.failReplayRecovery();
expect(coordinator.getState()).toMatchObject({
bootstrapped: false,
inFlight: null,
});
expect(coordinator.beginSnapshotRecovery("replay-failed")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "snapshot",
reason: "replay-failed",
});
});
});
-136
View File
@@ -1,136 +0,0 @@
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
export interface OrchestrationRecoveryPhase {
kind: "snapshot" | "replay";
reason: OrchestrationRecoveryReason;
}
export interface OrchestrationRecoveryState {
latestSequence: number;
highestObservedSequence: number;
bootstrapped: boolean;
pendingReplay: boolean;
inFlight: OrchestrationRecoveryPhase | null;
}
type SequencedEvent = Readonly<{ sequence: number }>;
export function createOrchestrationRecoveryCoordinator() {
let state: OrchestrationRecoveryState = {
latestSequence: 0,
highestObservedSequence: 0,
bootstrapped: false,
pendingReplay: false,
inFlight: null,
};
let replayStartSequence: number | null = null;
const snapshotState = (): OrchestrationRecoveryState => ({
...state,
...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),
});
const observeSequence = (sequence: number) => {
state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);
};
const shouldReplayAfterRecovery = (): boolean => {
const shouldReplay =
state.pendingReplay || state.highestObservedSequence > state.latestSequence;
state.pendingReplay = false;
return shouldReplay;
};
return {
getState(): OrchestrationRecoveryState {
return snapshotState();
},
classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {
observeSequence(sequence);
if (sequence <= state.latestSequence) {
return "ignore";
}
if (!state.bootstrapped || state.inFlight) {
state.pendingReplay = true;
return "defer";
}
if (sequence !== state.latestSequence + 1) {
state.pendingReplay = true;
return "recover";
}
return "apply";
},
markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
if (nextEvents.length === 0) {
return [];
}
state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
return nextEvents;
},
beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {
if (state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.inFlight = { kind: "snapshot", reason };
return true;
},
completeSnapshotRecovery(snapshotSequence: number): boolean {
state.latestSequence = Math.max(state.latestSequence, snapshotSequence);
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
state.bootstrapped = true;
state.inFlight = null;
return shouldReplayAfterRecovery();
},
failSnapshotRecovery(): void {
state.inFlight = null;
},
beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {
if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.pendingReplay = false;
replayStartSequence = state.latestSequence;
state.inFlight = { kind: "replay", reason };
return true;
},
completeReplayRecovery(): boolean {
const replayMadeProgress =
replayStartSequence !== null && state.latestSequence > replayStartSequence;
replayStartSequence = null;
state.inFlight = null;
if (!replayMadeProgress) {
state.pendingReplay = false;
return false;
}
return shouldReplayAfterRecovery();
},
failReplayRecovery(): void {
replayStartSequence = null;
state.bootstrapped = false;
state.inFlight = null;
},
};
}
+36 -1
View File
@@ -1,11 +1,13 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -67,3 +69,36 @@ export function getDefaultServerModel(
DEFAULT_MODEL_BY_PROVIDER[provider]
);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
+10 -2
View File
@@ -1,8 +1,11 @@
import { createElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter, RouterHistory } from "@tanstack/react-router";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { StoreProvider } from "./store";
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
export function getRouter(history: RouterHistory) {
const queryClient = new QueryClient();
@@ -13,7 +16,12 @@ export function getRouter(history: RouterHistory) {
context: {
queryClient,
},
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
Wrap: ({ children }) =>
createElement(
QueryClientProvider,
{ client: queryClient },
createElement(StoreProvider, null, children),
),
});
}
+62 -146
View File
@@ -1,4 +1,4 @@
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import {
Outlet,
createRootRouteWithContext,
@@ -17,13 +17,8 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import {
clearPromotedDraftThread,
clearPromotedDraftThreads,
useComposerDraftStore,
} from "../composerDraftStore";
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
@@ -31,8 +26,7 @@ import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
import { gitQueryKeys } from "../lib/gitReactQuery";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -142,13 +136,8 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
const syncProjects = useUiStateStore((store) => store.syncProjects);
const syncThreads = useUiStateStore((store) => store.syncThreads);
const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
const removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
@@ -164,40 +153,60 @@ function EventRouter() {
const api = readNativeApi();
if (!api) return;
let disposed = false;
const recovery = createOrchestrationRecoveryCoordinator();
let latestSequence = 0;
let syncing = false;
let pending = false;
let needsProviderInvalidation = false;
const reconcileSnapshotDerivedState = () => {
const threads = useStore.getState().threads;
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
clearPromotedDraftThreads(threads.map((thread) => thread.id));
const flushSnapshotSync = async (): Promise<void> => {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id)));
const draftThreadIds = Object.keys(
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
snapshotThreads: snapshot.threads,
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
await Promise.all([
queryClient.invalidateQueries({ queryKey: gitQueryKeys.all }),
queryClient.invalidateQueries({ queryKey: projectQueryKeys.all }),
]);
if (pending) {
pending = false;
await flushSnapshotSync();
}
};
const queryInvalidationThrottler = new Throttler(
const syncSnapshot = async () => {
if (syncing) {
pending = true;
return;
}
syncing = true;
pending = false;
try {
await flushSnapshotSync();
} catch {
// Keep prior state and wait for next domain event to trigger a resync.
}
syncing = false;
};
const domainEventFlushThrottler = new Throttler(
() => {
if (!needsProviderInvalidation) {
return;
if (needsProviderInvalidation) {
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
}
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
void syncSnapshot();
},
{
wait: 100,
@@ -206,113 +215,15 @@ function EventRouter() {
},
);
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
}
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
const needsProjectUiSync = nextEvents.some(
(event) =>
event.type === "project.created" ||
event.type === "project.meta-updated" ||
event.type === "project.deleted",
);
if (batchEffects.needsProviderInvalidation) {
needsProviderInvalidation = true;
void queryInvalidationThrottler.maybeExecute();
}
applyOrchestrationEvents(nextEvents);
if (needsProjectUiSync) {
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
}
const needsThreadUiSync = nextEvents.some(
(event) => event.type === "thread.created" || event.type === "thread.deleted",
);
if (needsThreadUiSync) {
const threads = useStore.getState().threads;
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
}
const draftStore = useComposerDraftStore.getState();
for (const threadId of batchEffects.clearPromotedDraftThreadIds) {
clearPromotedDraftThread(threadId);
}
for (const threadId of batchEffects.clearDeletedThreadIds) {
draftStore.clearDraftThread(threadId);
clearThreadUi(threadId);
}
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
removeTerminalState(threadId);
}
};
const recoverFromSequenceGap = async (): Promise<void> => {
if (!recovery.beginReplayRecovery("sequence-gap")) {
return;
}
try {
const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
if (!disposed) {
applyEventBatch(events);
}
} catch {
recovery.failReplayRecovery();
void fallbackToSnapshotRecovery();
return;
}
if (!disposed && recovery.completeReplayRecovery()) {
void recoverFromSequenceGap();
}
};
const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise<void> => {
if (!recovery.beginSnapshotRecovery(reason)) {
return;
}
try {
const snapshot = await api.orchestration.getSnapshot();
if (!disposed) {
syncServerReadModel(snapshot);
reconcileSnapshotDerivedState();
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void recoverFromSequenceGap();
}
}
} catch {
// Keep prior state and wait for welcome or a later replay attempt.
recovery.failSnapshotRecovery();
}
};
const bootstrapFromSnapshot = async (): Promise<void> => {
await runSnapshotRecovery("bootstrap");
};
const fallbackToSnapshotRecovery = async (): Promise<void> => {
await runSnapshotRecovery("replay-failed");
};
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
applyEventBatch([event]);
if (event.sequence <= latestSequence) {
return;
}
if (action === "recover") {
void recoverFromSequenceGap();
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
needsProviderInvalidation = true;
}
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -331,7 +242,7 @@ function EventRouter() {
// Migrate old localStorage settings to server on first connect
migrateLocalSettingsToServer();
void (async () => {
await bootstrapFromSnapshot();
await syncSnapshot();
if (disposed) {
return;
}
@@ -355,6 +266,14 @@ function EventRouter() {
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
})().catch(() => undefined);
});
const handleWorkspaceRefresh = () => {
if (document.visibilityState === "hidden") {
return;
}
void syncSnapshot();
};
window.addEventListener("focus", handleWorkspaceRefresh);
document.addEventListener("visibilitychange", handleWorkspaceRefresh);
// onServerConfigUpdated replays the latest cached value synchronously
// during subscribe. Skip the toast for that replay so effect re-runs
// don't produce duplicate toasts.
@@ -413,24 +332,21 @@ function EventRouter() {
return () => {
disposed = true;
needsProviderInvalidation = false;
queryInvalidationThrottler.cancel();
domainEventFlushThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
window.removeEventListener("focus", handleWorkspaceRefresh);
document.removeEventListener("visibilitychange", handleWorkspaceRefresh);
unsubServerConfigUpdated();
unsubProvidersUpdated();
};
}, [
applyOrchestrationEvents,
navigate,
queryClient,
removeTerminalState,
removeOrphanedTerminalStates,
clearThreadUi,
setProjectExpanded,
syncProjects,
syncServerReadModel,
syncThreads,
]);
return null;
+4 -4
View File
@@ -161,7 +161,7 @@ const DiffPanelInlineSidebar = (props: {
};
function ChatThreadRouteView() {
const bootstrapComplete = useStore((store) => store.bootstrapComplete);
const threadsHydrated = useStore((store) => store.threadsHydrated);
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
@@ -202,7 +202,7 @@ function ChatThreadRouteView() {
}, [diffOpen]);
useEffect(() => {
if (!bootstrapComplete) {
if (!threadsHydrated) {
return;
}
@@ -210,9 +210,9 @@ function ChatThreadRouteView() {
void navigate({ to: "/", replace: true });
return;
}
}, [bootstrapComplete, navigate, routeThreadExists, threadId]);
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
if (!bootstrapComplete || !routeThreadExists) {
if (!threadsHydrated || !routeThreadExists) {
return null;
}
+11 -14
View File
@@ -17,7 +17,7 @@ const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size);
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } =
const { activeDraftThread, activeThread, handleNewThread, projects, routeThreadId } =
useHandleNewThread();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
@@ -38,7 +38,7 @@ function ChatRouteGlobalShortcuts() {
return;
}
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId;
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
if (!projectId) return;
const command = resolveShortcutCommand(event, keybindings, {
@@ -59,17 +59,14 @@ function ChatRouteGlobalShortcuts() {
return;
}
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
return;
}
if (command !== "chat.new") return;
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -82,7 +79,7 @@ function ChatRouteGlobalShortcuts() {
clearSelection,
handleNewThread,
keybindings,
defaultProjectId,
projects,
selectedThreadIdsSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
-32
View File
@@ -8,7 +8,6 @@ import {
import { describe, expect, it } from "vitest";
import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
PROVIDER_OPTIONS,
@@ -965,37 +964,6 @@ describe("deriveTimelineEntries", () => {
},
});
});
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
const entries = deriveTimelineEntries(
[
{
id: MessageId.makeUnsafe("assistant-earlier"),
role: "assistant",
text: "progress update",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-final"),
role: "assistant",
text: "final answer",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
],
[],
[],
);
expect(
deriveCompletionDividerBeforeEntryId(entries, {
assistantMessageId: MessageId.makeUnsafe("assistant-final"),
startedAt: "2026-02-23T00:00:00.000Z",
completedAt: "2026-02-23T00:00:02.000Z",
}),
).toBe("assistant-final");
});
});
describe("deriveWorkLogEntries context window handling", () => {
-47
View File
@@ -852,53 +852,6 @@ export function deriveTimelineEntries(
);
}
export function deriveCompletionDividerBeforeEntryId(
timelineEntries: ReadonlyArray<TimelineEntry>,
latestTurn: Pick<
OrchestrationLatestTurn,
"assistantMessageId" | "startedAt" | "completedAt"
> | null,
): string | null {
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
return null;
}
if (latestTurn.assistantMessageId) {
const exactMatch = timelineEntries.find(
(timelineEntry) =>
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
timelineEntry.message.id === latestTurn.assistantMessageId,
);
if (exactMatch) {
return exactMatch.id;
}
}
const turnStartedAt = Date.parse(latestTurn.startedAt);
const turnCompletedAt = Date.parse(latestTurn.completedAt);
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
return null;
}
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
continue;
}
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
continue;
}
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<TurnId, number> {
+109 -489
View File
@@ -1,22 +1,13 @@
import {
CheckpointRef,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
applyOrchestrationEvent,
applyOrchestrationEvents,
syncServerReadModel,
type AppState,
} from "./store";
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -42,6 +33,9 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
...overrides,
};
}
@@ -53,45 +47,20 @@ function makeState(thread: Thread): AppState {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
expanded: true,
scripts: [],
},
],
threads: [thread],
bootstrapComplete: true,
threadsHydrated: true,
};
}
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
return {
id: ThreadId.makeUnsafe("thread-1"),
@@ -105,6 +74,9 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
interactionMode: DEFAULT_INTERACTION_MODE,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
@@ -128,6 +100,7 @@ function makeReadModel(thread: OrchestrationReadModel["threads"][number]): Orche
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -149,6 +122,7 @@ function makeReadModelProject(
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -161,18 +135,100 @@ function makeReadModelProject(
};
}
describe("store read model sync", () => {
it("marks bootstrap complete after snapshot sync", () => {
const initialState: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-25T12:28:00.000Z",
startedAt: "2026-02-25T12:28:30.000Z",
completedAt: latestTurnCompletedAt,
assistantMessageId: null,
},
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({})));
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next.bootstrapComplete).toBe(true);
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
Date.parse(latestTurnCompletedAt),
);
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next).toEqual(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const state: AppState = {
projects: [
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project3,
name: "Project 3",
cwd: "/tmp/project-3",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
};
const next = reorderProjects(state, project1, project3);
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
});
});
describe("store read model sync", () => {
it("preserves claude model slugs without an active session", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
@@ -243,7 +299,7 @@ describe("store read model sync", () => {
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
});
it("replaces projects using snapshot order during recovery", () => {
it("preserves the current project order when syncing incoming read model updates", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
@@ -253,25 +309,29 @@ describe("store read model sync", () => {
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
threadsHydrated: true,
};
const readModel: OrchestrationReadModel = {
snapshotSequence: 2,
@@ -298,446 +358,6 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
});
});
describe("incremental orchestration updates", () => {
it("does not mark bootstrap complete for incremental events", () => {
const state: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.meta-updated", {
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Updated title",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.bootstrapComplete).toBe(false);
});
it("preserves state identity for no-op project and thread deletes", () => {
const thread = makeThread();
const state = makeState(thread);
const nextAfterProjectDelete = applyOrchestrationEvent(
state,
makeEvent("project.deleted", {
projectId: ProjectId.makeUnsafe("project-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
const nextAfterThreadDelete = applyOrchestrationEvent(
state,
makeEvent("thread.deleted", {
threadId: ThreadId.makeUnsafe("thread-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(nextAfterProjectDelete).toBe(state);
expect(nextAfterThreadDelete).toBe(state);
});
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const state: AppState = {
projects: [
{
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
state,
makeEvent("project.created", {
projectId: recreatedProjectId,
title: "Project Recreated",
workspaceRoot: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe(recreatedProjectId);
expect(next.projects[0]?.cwd).toBe("/tmp/project");
expect(next.projects[0]?.name).toBe("Project Recreated");
});
it("updates only the affected thread for message events", () => {
const thread1 = makeThread({
id: ThreadId.makeUnsafe("thread-1"),
messages: [
{
id: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: "hello",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
],
});
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
const state: AppState = {
...makeState(thread1),
threads: [thread1, thread2],
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: thread1.id,
messageId: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: " world",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: true,
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
expect(next.threads[0]?.latestTurn?.state).toBe("running");
expect(next.threads[1]).toBe(thread2);
});
it("applies replay batches in sequence and updates session state", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "running",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: null,
assistantMessageId: null,
},
});
const state = makeState(thread);
const next = applyOrchestrationEvents(state, [
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:00:02.000Z",
},
},
{ sequence: 2 },
),
makeEvent(
"thread.message-sent",
{
threadId: thread.id,
messageId: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
},
{ sequence: 3 },
),
]);
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
});
it("does not regress latestTurn when an older turn diff completes late", () => {
const state = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "running",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:03.000Z",
completedAt: null,
assistantMessageId: null,
},
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.turn-diff-completed", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:04.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
});
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
const turnId = TurnId.makeUnsafe("turn-1");
const state = makeState(
makeThread({
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
},
turnDiffSummaries: [
{
turnId,
completedAt: "2026-02-27T00:00:02.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: MessageId.makeUnsafe("assistant-real"),
role: "assistant",
text: "final answer",
turnId,
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
});
it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
const state = makeState(
makeThread({
messages: [
{
id: MessageId.makeUnsafe("user-1"),
role: "user",
text: "first",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "first reply",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:01.000Z",
completedAt: "2026-02-27T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("user-2"),
role: "user",
text: "second",
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
streaming: false,
},
],
proposedPlans: [
{
id: "plan-1",
turnId: TurnId.makeUnsafe("turn-1"),
planMarkdown: "plan 1",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
},
{
id: "plan-2",
turnId: TurnId.makeUnsafe("turn-2"),
planMarkdown: "plan 2",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
},
],
activities: [
{
id: EventId.makeUnsafe("activity-1"),
tone: "info",
kind: "step",
summary: "one",
payload: {},
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
},
{
id: EventId.makeUnsafe("activity-2"),
tone: "info",
kind: "step",
summary: "two",
payload: {},
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
},
],
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.reverted", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
}),
);
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant-1",
]);
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
EventId.makeUnsafe("activity-1"),
]);
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
TurnId.makeUnsafe("turn-1"),
]);
});
it("clears pending source proposed plans after revert before a new session-set event", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "completed",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:03.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant-2"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
},
pendingSourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
});
const reverted = applyOrchestrationEvent(
makeState(thread),
makeEvent("thread.reverted", {
threadId: thread.id,
turnCount: 1,
}),
);
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
const next = applyOrchestrationEvent(
reverted,
makeEvent("thread.session-set", {
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-3"),
lastError: null,
updatedAt: "2026-02-27T00:00:04.000Z",
},
}),
);
expect(next.threads[0]?.latestTurn).toMatchObject({
turnId: TurnId.makeUnsafe("turn-3"),
state: "running",
});
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
});
});
+312 -788
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
import { type ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { selectProjectById, selectThreadById, useStore } from "./store";
import { type Project, type Thread } from "./types";
export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined {
const selector = useMemo(() => selectProjectById(projectId), [projectId]);
return useStore(selector);
}
export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined {
const selector = useMemo(() => selectThreadById(threadId), [threadId]);
return useStore(selector);
}
-10
View File
@@ -485,7 +485,6 @@ interface TerminalStateStoreState {
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
}
@@ -531,15 +530,6 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
),
clearTerminalState: (threadId) =>
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
removeTerminalState: (threadId) =>
set((state) => {
if (state.terminalStateByThreadId[threadId] === undefined) {
return state;
}
const next = { ...state.terminalStateByThreadId };
delete next[threadId];
return { terminalStateByThreadId: next };
}),
removeOrphanedTerminalStates: (activeThreadIds) =>
set((state) => {
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
+8 -2
View File
@@ -13,6 +13,8 @@ import type {
CheckpointRef,
ProviderInteractionMode,
RuntimeMode,
WorkspaceAvailabilityState,
ThreadEffectiveCwdSource,
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
@@ -45,7 +47,6 @@ export interface ChatMessage {
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
turnId?: TurnId | null;
createdAt: string;
completedAt?: string | undefined;
streaming: boolean;
@@ -82,7 +83,9 @@ export interface Project {
id: ProjectId;
name: string;
cwd: string;
workspaceState: WorkspaceAvailabilityState;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
@@ -104,9 +107,12 @@ export interface Thread {
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"];
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
effectiveCwd: string | null;
effectiveCwdSource: ThreadEffectiveCwdSource | null;
effectiveCwdState: WorkspaceAvailabilityState;
turnDiffSummaries: TurnDiffSummary[];
activities: OrchestrationThreadActivity[];
}
-192
View File
@@ -1,192 +0,0 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
clearThreadUi,
markThreadUnread,
reorderProjects,
setProjectExpanded,
syncProjects,
syncThreads,
type UiState,
} from "./uiStateStore";
function makeUiState(overrides: Partial<UiState> = {}): UiState {
return {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
...overrides,
};
}
describe("uiStateStore pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt);
expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z");
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, null);
expect(next).toBe(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectOrder: [project1, project2, project3],
});
const next = reorderProjects(initialState, project1, project3);
expect(next.projectOrder).toEqual([project2, project3, project1]);
});
it("syncProjects preserves current project order during snapshot recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
[project2]: false,
},
projectOrder: [project2, project1],
});
const next = syncProjects(initialState, [
{ id: project1, cwd: "/tmp/project-1" },
{ id: project2, cwd: "/tmp/project-2" },
{ id: project3, cwd: "/tmp/project-3" },
]);
expect(next.projectOrder).toEqual([project2, project1, project3]);
expect(next.projectExpandedById[project2]).toBe(false);
});
it("syncProjects preserves manual order when a project is recreated with the same cwd", () => {
const oldProject1 = ProjectId.makeUnsafe("project-1");
const oldProject2 = ProjectId.makeUnsafe("project-2");
const recreatedProject2 = ProjectId.makeUnsafe("project-2b");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[oldProject1]: true,
[oldProject2]: false,
},
projectOrder: [oldProject2, oldProject1],
}),
[
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: oldProject2, cwd: "/tmp/project-2" },
],
);
const next = syncProjects(initialState, [
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: recreatedProject2, cwd: "/tmp/project-2" },
]);
expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]);
expect(next.projectExpandedById[recreatedProject2]).toBe(false);
});
it("syncProjects returns a new state when only project cwd changes", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[project1]: false,
},
projectOrder: [project1],
}),
[{ id: project1, cwd: "/tmp/project-1" }],
);
const next = syncProjects(initialState, [{ id: project1, cwd: "/tmp/project-1-renamed" }]);
expect(next).not.toBe(initialState);
expect(next.projectOrder).toEqual([project1]);
expect(next.projectExpandedById[project1]).toBe(false);
});
it("syncThreads prunes missing thread UI state", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const thread2 = ThreadId.makeUnsafe("thread-2");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
[thread2]: "2026-02-25T12:36:00.000Z",
},
});
const next = syncThreads(initialState, [{ id: thread1 }]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("syncThreads seeds visit state for unseen snapshot threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState();
const next = syncThreads(initialState, [
{
id: thread1,
seedVisitedAt: "2026-02-25T12:35:00.000Z",
},
]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("setProjectExpanded updates expansion without touching order", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
},
projectOrder: [project1],
});
const next = setProjectExpanded(initialState, project1, false);
expect(next.projectExpandedById[project1]).toBe(false);
expect(next.projectOrder).toEqual([project1]);
});
it("clearThreadUi removes visit state for deleted threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
},
});
const next = clearThreadUi(initialState, thread1);
expect(next.threadLastVisitedAtById).toEqual({});
});
});
-417
View File
@@ -1,417 +0,0 @@
import { Debouncer } from "@tanstack/react-pacer";
import { type ProjectId, type ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
}
export interface UiProjectState {
projectExpandedById: Record<string, boolean>;
projectOrder: ProjectId[];
}
export interface UiThreadState {
threadLastVisitedAtById: Record<string, string>;
}
export interface UiState extends UiProjectState, UiThreadState {}
export interface SyncProjectInput {
id: ProjectId;
cwd: string;
}
export interface SyncThreadInput {
id: ThreadId;
seedVisitedAt?: string | undefined;
}
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
};
const persistedExpandedProjectCwds = new Set<string>();
const persistedProjectOrderCwds: string[] = [];
const currentProjectCwdById = new Map<ProjectId, string>();
let legacyKeysCleanedUp = false;
function readPersistedState(): UiState {
if (typeof window === "undefined") {
return initialState;
}
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) {
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
const legacyRaw = window.localStorage.getItem(legacyKey);
if (!legacyRaw) {
continue;
}
hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState);
return initialState;
}
return initialState;
}
hydratePersistedProjectState(JSON.parse(raw) as PersistedUiState);
return initialState;
} catch {
return initialState;
}
}
function hydratePersistedProjectState(parsed: PersistedUiState): void {
persistedExpandedProjectCwds.clear();
persistedProjectOrderCwds.length = 0;
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
for (const cwd of parsed.projectOrderCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
persistedProjectOrderCwds.push(cwd);
}
}
}
function persistState(state: UiState): void {
if (typeof window === "undefined") {
return;
}
try {
const expandedProjectCwds = Object.entries(state.projectExpandedById)
.filter(([, expanded]) => expanded)
.flatMap(([projectId]) => {
const cwd = currentProjectCwdById.get(projectId as ProjectId);
return cwd ? [cwd] : [];
});
const projectOrderCwds = state.projectOrder.flatMap((projectId) => {
const cwd = currentProjectCwdById.get(projectId);
return cwd ? [cwd] : [];
});
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
expandedProjectCwds,
projectOrderCwds,
} satisfies PersistedUiState),
);
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 });
function recordsEqual<T>(left: Record<string, T>, right: Record<string, T>): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) {
return false;
}
for (const [key, value] of leftEntries) {
if (right[key] !== value) {
return false;
}
}
return true;
}
function projectOrdersEqual(left: readonly ProjectId[], right: readonly ProjectId[]): boolean {
return (
left.length === right.length && left.every((projectId, index) => projectId === right[index])
);
}
export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState {
const previousProjectCwdById = new Map(currentProjectCwdById);
const previousProjectIdByCwd = new Map(
[...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const),
);
currentProjectCwdById.clear();
for (const project of projects) {
currentProjectCwdById.set(project.id, project.cwd);
}
const cwdMappingChanged =
previousProjectCwdById.size !== currentProjectCwdById.size ||
projects.some((project) => previousProjectCwdById.get(project.id) !== project.cwd);
const nextExpandedById: Record<string, boolean> = {};
const previousExpandedById = state.projectExpandedById;
const persistedOrderByCwd = new Map(
persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),
);
const mappedProjects = projects.map((project, index) => {
const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd);
const expanded =
previousExpandedById[project.id] ??
(previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true);
nextExpandedById[project.id] = expanded;
return {
id: project.id,
cwd: project.cwd,
incomingIndex: index,
};
});
const nextProjectOrder =
state.projectOrder.length > 0
? (() => {
const nextProjectIdByCwd = new Map(
mappedProjects.map((project) => [project.cwd, project.id] as const),
);
const usedProjectIds = new Set<ProjectId>();
const orderedProjectIds: ProjectId[] = [];
for (const projectId of state.projectOrder) {
const matchedProjectId =
(projectId in nextExpandedById ? projectId : undefined) ??
(() => {
const previousCwd = previousProjectCwdById.get(projectId);
return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined;
})();
if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) {
continue;
}
usedProjectIds.add(matchedProjectId);
orderedProjectIds.push(matchedProjectId);
}
for (const project of mappedProjects) {
if (usedProjectIds.has(project.id)) {
continue;
}
orderedProjectIds.push(project.id);
}
return orderedProjectIds;
})()
: mappedProjects
.map((project) => ({
id: project.id,
incomingIndex: project.incomingIndex,
orderIndex:
persistedOrderByCwd.get(project.cwd) ??
persistedProjectOrderCwds.length + project.incomingIndex,
}))
.toSorted((left, right) => {
const byOrder = left.orderIndex - right.orderIndex;
if (byOrder !== 0) {
return byOrder;
}
return left.incomingIndex - right.incomingIndex;
})
.map((project) => project.id);
if (
recordsEqual(state.projectExpandedById, nextExpandedById) &&
projectOrdersEqual(state.projectOrder, nextProjectOrder) &&
!cwdMappingChanged
) {
return state;
}
return {
...state,
projectExpandedById: nextExpandedById,
projectOrder: nextProjectOrder,
};
}
export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState {
const retainedThreadIds = new Set(threads.map((thread) => thread.id));
const nextThreadLastVisitedAtById = Object.fromEntries(
Object.entries(state.threadLastVisitedAtById).filter(([threadId]) =>
retainedThreadIds.has(threadId as ThreadId),
),
);
for (const thread of threads) {
if (
nextThreadLastVisitedAtById[thread.id] === undefined &&
thread.seedVisitedAt !== undefined &&
thread.seedVisitedAt.length > 0
) {
nextThreadLastVisitedAtById[thread.id] = thread.seedVisitedAt;
}
}
if (recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById)) {
return state;
}
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function markThreadVisited(state: UiState, threadId: ThreadId, visitedAt?: string): UiState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
const previousVisitedAt = state.threadLastVisitedAtById[threadId];
const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: at,
},
};
}
export function markThreadUnread(
state: UiState,
threadId: ThreadId,
latestTurnCompletedAt: string | null | undefined,
): UiState {
if (!latestTurnCompletedAt) {
return state;
}
const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return state;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: unreadVisitedAt,
},
};
}
export function clearThreadUi(state: UiState, threadId: ThreadId): UiState {
if (!(threadId in state.threadLastVisitedAtById)) {
return state;
}
const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById };
delete nextThreadLastVisitedAtById[threadId];
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function toggleProject(state: UiState, projectId: ProjectId): UiState {
const expanded = state.projectExpandedById[projectId] ?? true;
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: !expanded,
},
};
}
export function setProjectExpanded(
state: UiState,
projectId: ProjectId,
expanded: boolean,
): UiState {
if ((state.projectExpandedById[projectId] ?? true) === expanded) {
return state;
}
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: expanded,
},
};
}
export function reorderProjects(
state: UiState,
draggedProjectId: ProjectId,
targetProjectId: ProjectId,
): UiState {
if (draggedProjectId === targetProjectId) {
return state;
}
const draggedIndex = state.projectOrder.findIndex((projectId) => projectId === draggedProjectId);
const targetIndex = state.projectOrder.findIndex((projectId) => projectId === targetProjectId);
if (draggedIndex < 0 || targetIndex < 0) {
return state;
}
const projectOrder = [...state.projectOrder];
const [draggedProject] = projectOrder.splice(draggedIndex, 1);
if (!draggedProject) {
return state;
}
projectOrder.splice(targetIndex, 0, draggedProject);
return {
...state,
projectOrder,
};
}
interface UiStateStore extends UiState {
syncProjects: (projects: readonly SyncProjectInput[]) => void;
syncThreads: (threads: readonly SyncThreadInput[]) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId, latestTurnCompletedAt: string | null | undefined) => void;
clearThreadUi: (threadId: ThreadId) => void;
toggleProject: (projectId: ProjectId) => void;
setProjectExpanded: (projectId: ProjectId, expanded: boolean) => void;
reorderProjects: (draggedProjectId: ProjectId, targetProjectId: ProjectId) => void;
}
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
syncProjects: (projects) => set((state) => syncProjects(state, projects)),
syncThreads: (threads) => set((state) => syncThreads(state, threads)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
reorderProjects: (draggedProjectId, targetProjectId) =>
set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
}));
useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}
+35
View File
@@ -0,0 +1,35 @@
import type { Project, Thread } from "./types";
export function isWorkspaceStateAvailable(
state: Project["workspaceState"] | Thread["effectiveCwdState"],
): boolean {
return state === "available";
}
export function isProjectWorkspaceAvailable(project: Pick<Project, "workspaceState">): boolean {
return isWorkspaceStateAvailable(project.workspaceState);
}
export function isThreadWorkspaceAvailable(thread: Pick<Thread, "effectiveCwdState">): boolean {
return isWorkspaceStateAvailable(thread.effectiveCwdState);
}
export function workspaceUnavailableReason(input: {
state: Project["workspaceState"] | Thread["effectiveCwdState"];
kind: "project" | "worktree";
}): string | null {
if (input.state === "available") {
return null;
}
const subject = input.kind === "project" ? "Project folder" : "Worktree";
switch (input.state) {
case "missing":
return `${subject} is missing.`;
case "not_directory":
return `${subject} path is not a folder.`;
case "inaccessible":
default:
return `${subject} is inaccessible.`;
}
}
+3
View File
@@ -27,6 +27,9 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
...overrides,
};
}
+1 -1
View File
@@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
-2
View File
@@ -17,8 +17,6 @@ This document covers how to run desktop releases from one tag, first without sig
- 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.
- Refreshes the marketing-site JSON Schemas for `settings.json` and `keybindings.json` at `/schemas/settings.json` and `/schemas/keybindings.json`.
- Commits immutable versioned JSON Schema copies at `/schemas/settings/<version>.json` and `/schemas/keybindings/<version>.json`.
## Desktop auto-update notes
+6 -6
View File
@@ -130,12 +130,12 @@ export interface NativeApi {
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalClearInput) => Promise<void>;
restart: (input: TerminalRestartInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
+16 -36
View File
@@ -46,53 +46,33 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
),
Schema.Literal(".run"),
]).annotate({
description: "Command identifier for running a project script, formatted as `script.<id>.run`.",
});
]);
export const KeybindingCommand = Schema.Union([
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
SCRIPT_RUN_COMMAND_PATTERN,
]).annotate({
description: "Command invoked when the keybinding is triggered.",
});
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;
const KeybindingValue = TrimmedString.annotate({
description:
"Keyboard shortcut string such as `mod+j`, `ctrl+k`, or `shift+space`, using the T3 Code keybinding syntax.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH));
const KeybindingValue = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
const KeybindingWhen = TrimmedString.annotate({
description:
"Optional context expression controlling when the keybinding is active, such as `terminalFocus` or `!terminalFocus`.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH));
const KeybindingWhen = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
export const KeybindingRule = Schema.Struct({
key: KeybindingValue.pipe(
Schema.annotate({
description: "Keyboard shortcut to listen for.",
}),
),
command: KeybindingCommand.pipe(
Schema.annotate({
description: "Command to execute when the shortcut matches.",
}),
),
when: Schema.optional(KeybindingWhen).pipe(
Schema.annotate({
description: "Optional expression limiting when the shortcut is active.",
}),
),
}).annotate({
description: "Single keybinding rule entry in `keybindings.json`.",
key: KeybindingValue,
command: KeybindingCommand,
when: Schema.optional(KeybindingWhen),
});
export type KeybindingRule = typeof KeybindingRule.Type;
export const KeybindingsConfig = Schema.Array(KeybindingRule)
.check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT))
.annotate({
description: "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
});
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
export const KeybindingShortcut = Schema.Struct({
+6 -37
View File
@@ -9,47 +9,16 @@ export type ClaudeCodeEffort = (typeof CLAUDE_CODE_EFFORT_OPTIONS)[number];
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeCodeEffort;
export const CodexModelOptions = Schema.Struct({
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Codex fast mode when the selected model supports it.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Codex models.",
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
});
export type CodexModelOptions = typeof CodexModelOptions.Type;
export const ClaudeModelOptions = Schema.Struct({
thinking: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether Claude should enable extended thinking for the selected model.",
}),
),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Claude fast mode when the selected model supports it.",
}),
),
contextWindow: Schema.optional(Schema.String).pipe(
Schema.annotate({
description:
"Optional Claude context window preset to request for the selected model, if supported.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Claude models.",
thinking: Schema.optional(Schema.Boolean),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
+28 -37
View File
@@ -46,50 +46,20 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const CodexModelSelection = Schema.Struct({
provider: Schema.Literal("codex").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.annotate({
description: "The Codex model slug to use for text generation.",
}),
),
options: Schema.optionalKey(CodexModelOptions).pipe(
Schema.annotate({
description: "Optional Codex-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Codex provider.",
provider: Schema.Literal("codex"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(CodexModelOptions),
});
export type CodexModelSelection = typeof CodexModelSelection.Type;
export const ClaudeModelSelection = Schema.Struct({
provider: Schema.Literal("claudeAgent").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.annotate({
description: "The Claude model slug to use for text generation.",
}),
),
options: Schema.optionalKey(ClaudeModelOptions).pipe(
Schema.annotate({
description: "Optional Claude-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Claude provider.",
provider: Schema.Literal("claudeAgent"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(ClaudeModelOptions),
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]).annotate({
description: "Selects which provider and model T3 Code should use for text generation.",
});
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
export type ModelSelection = typeof ModelSelection.Type;
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
@@ -171,10 +141,24 @@ export const ProjectScript = Schema.Struct({
});
export type ProjectScript = typeof ProjectScript.Type;
export const WorkspaceAvailabilityState = Schema.Literals([
"available",
"missing",
"not_directory",
"inaccessible",
]);
export type WorkspaceAvailabilityState = typeof WorkspaceAvailabilityState.Type;
export const ThreadEffectiveCwdSource = Schema.Literals(["project", "worktree"]);
export type ThreadEffectiveCwdSource = typeof ThreadEffectiveCwdSource.Type;
export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
workspaceState: WorkspaceAvailabilityState.pipe(
Schema.withDecodingDefault(() => "available" as const),
),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -311,6 +295,13 @@ export const OrchestrationThread = Schema.Struct({
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
effectiveCwd: Schema.NullOr(TrimmedNonEmptyString).pipe(Schema.withDecodingDefault(() => null)),
effectiveCwdSource: Schema.NullOr(ThreadEffectiveCwdSource).pipe(
Schema.withDecodingDefault(() => null),
),
effectiveCwdState: WorkspaceAvailabilityState.pipe(
Schema.withDecodingDefault(() => "available" as const),
),
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
+1 -8
View File
@@ -35,13 +35,6 @@ export const ServerProviderAuthStatus = Schema.Literals([
]);
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
export const ServerProviderAuth = Schema.Struct({
status: ServerProviderAuthStatus,
type: Schema.optional(TrimmedNonEmptyString),
label: Schema.optional(TrimmedNonEmptyString),
});
export type ServerProviderAuth = typeof ServerProviderAuth.Type;
export const ServerProviderModel = Schema.Struct({
slug: TrimmedNonEmptyString,
name: TrimmedNonEmptyString,
@@ -56,7 +49,7 @@ export const ServerProvider = Schema.Struct({
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
status: ServerProviderState,
auth: ServerProviderAuth,
authStatus: ServerProviderAuthStatus,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
models: Schema.Array(ServerProviderModel),
+8
View File
@@ -0,0 +1,8 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
describe("DEFAULT_CLIENT_SETTINGS", () => {
it("includes archive confirmation with a false default", () => {
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
});
});
+28 -81
View File
@@ -23,32 +23,17 @@ export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
const makeTrimmedStringSetting = (description: string) =>
Schema.String.annotate({ description }).pipe(
Schema.decodeTo(TrimmedString, SchemaTransformation.passthrough()),
);
export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.annotate({
description: "Require a second click on the inline archive action before a thread is archived.",
}).pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.annotate({
description: "Ask before deleting a thread and its chat history.",
}).pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.annotate({
description: "Set the default wrap state when the diff panel opens.",
}).pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.annotate({
description: "Choose how projects are ordered in the sidebar.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
sidebarThreadSortOrder: SidebarThreadSortOrder.annotate({
description: "Choose how threads are ordered inside the selected project.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
timestampFormat: TimestampFormat.annotate({
description: "System default follows your browser or OS clock preference.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
}).annotate({
description: "Client-only settings persisted locally in the browser.",
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -56,13 +41,11 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]).annotate({
description: "Pick the default workspace mode for newly created draft threads.",
});
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
const makeBinaryPathSetting = (fallback: string, description: string) =>
makeTrimmedStringSetting(description).pipe(
const makeBinaryPathSetting = (fallback: string) =>
TrimmedString.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
@@ -74,51 +57,26 @@ const makeBinaryPathSetting = (fallback: string, description: string) =>
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the Codex provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex", "Path to the Codex binary"),
homePath: makeTrimmedStringSetting("Optional custom Codex home and config directory.").pipe(
Schema.withDecodingDefault(() => ""),
),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Codex model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Codex provider.",
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the Claude provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude", "Path to the Claude binary"),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Claude model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Claude provider.",
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude"),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.annotate({
description: "Show token-by-token output while a response is in progress.",
}).pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.annotate({
description: "Pick the default workspace mode for newly created draft threads.",
}).pipe(Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode)),
textGenerationModelSelection: ModelSelection.annotate({
description:
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
}).pipe(
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
@@ -127,19 +85,9 @@ export const ServerSettings = Schema.Struct({
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.annotate({
description: "Configuration for the Codex provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.annotate({
description: "Configuration for the Claude provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
})
.annotate({
description: "Provider-specific server configuration.",
})
.pipe(Schema.withDecodingDefault(() => ({}))),
}).annotate({
description: "Server-authoritative settings persisted in `settings.json`.",
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
@@ -164,7 +112,6 @@ const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
});
const ModelSelectionPatch = Schema.Union([
+2 -2
View File
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
export const TerminalThreadInput = Schema.Struct({
threadId: TrimmedNonEmptyStringSchema,
});
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
const TerminalSessionInput = Schema.Struct({
...TerminalThreadInput.fields,
@@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({
terminalId: Schema.optional(TerminalIdSchema),
deleteHistory: Schema.optional(Schema.Boolean),
});
export type TerminalCloseInput = typeof TerminalCloseInput.Type;
export type TerminalCloseInput = Schema.Codec.Encoded<typeof TerminalCloseInput>;
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
-4
View File
@@ -28,10 +28,6 @@
"types": "./src/DrainableWorker.ts",
"import": "./src/DrainableWorker.ts"
},
"./KeyedCoalescingWorker": {
"types": "./src/KeyedCoalescingWorker.ts",
"import": "./src/KeyedCoalescingWorker.ts"
},
"./schemaJson": {
"types": "./src/schemaJson.ts",
"import": "./src/schemaJson.ts"
@@ -1,96 +0,0 @@
import { it } from "@effect/vitest";
import { describe, expect } from "vitest";
import { Deferred, Effect } from "effect";
import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker";
describe("makeKeyedCoalescingWorker", () => {
it.live("waits for latest work enqueued during active processing before draining the key", () =>
Effect.scoped(
Effect.gen(function* () {
const processed: string[] = [];
const firstStarted = yield* Deferred.make<void>();
const releaseFirst = yield* Deferred.make<void>();
const secondStarted = yield* Deferred.make<void>();
const releaseSecond = yield* Deferred.make<void>();
const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
merge: (_current, next) => next,
process: (key, value) =>
Effect.gen(function* () {
processed.push(`${key}:${value}`);
if (value === "first") {
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseFirst);
}
if (value === "second") {
yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseSecond);
}
}),
});
yield* worker.enqueue("terminal-1", "first");
yield* Deferred.await(firstStarted);
const drained = yield* Deferred.make<void>();
yield* Effect.forkChild(
worker
.drainKey("terminal-1")
.pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
);
yield* worker.enqueue("terminal-1", "second");
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
expect(yield* Deferred.isDone(drained)).toBe(false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
it.live("requeues pending work for a key after a processor failure and keeps draining", () =>
Effect.scoped(
Effect.gen(function* () {
const processed: string[] = [];
const firstStarted = yield* Deferred.make<void>();
const releaseFailure = yield* Deferred.make<void>();
const secondProcessed = yield* Deferred.make<void>();
const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
merge: (_current, next) => next,
process: (key, value) =>
Effect.gen(function* () {
processed.push(`${key}:${value}`);
if (value === "first") {
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseFailure);
yield* Effect.fail("boom");
}
if (value === "second") {
yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
}
}),
});
yield* worker.enqueue("terminal-1", "first");
yield* Deferred.await(firstStarted);
yield* worker.enqueue("terminal-1", "second");
yield* Deferred.succeed(releaseFailure, undefined);
yield* Deferred.await(secondProcessed);
yield* worker.drainKey("terminal-1");
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
});
@@ -1,140 +0,0 @@
/**
* KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.
*
* Enqueues for an active or already-queued key are merged atomically instead of
* creating duplicate queued items. `drainKey()` resolves only when that key has
* no queued, pending, or active work left.
*
* @module KeyedCoalescingWorker
*/
import type { Scope } from "effect";
import { Effect, TxQueue, TxRef } from "effect";
export interface KeyedCoalescingWorker<K, V> {
readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
readonly drainKey: (key: K) => Effect.Effect<void>;
}
interface KeyedCoalescingWorkerState<K, V> {
readonly latestByKey: Map<K, V>;
readonly queuedKeys: Set<K>;
readonly activeKeys: Set<K>;
}
export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
readonly merge: (current: V, next: V) => V;
readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
Effect.gen(function* () {
const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
latestByKey: new Map(),
queuedKeys: new Set(),
activeKeys: new Set(),
});
const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>
options.process(key, value).pipe(
Effect.flatMap(() =>
TxRef.modify(stateRef, (state) => {
const nextValue = state.latestByKey.get(key);
if (nextValue === undefined) {
const activeKeys = new Set(state.activeKeys);
activeKeys.delete(key);
return [null, { ...state, activeKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
latestByKey.delete(key);
return [nextValue, { ...state, latestByKey }] as const;
}).pipe(Effect.tx),
),
Effect.flatMap((nextValue) =>
nextValue === null ? Effect.void : processKey(key, nextValue),
),
);
const cleanupFailedKey = (key: K): Effect.Effect<void> =>
TxRef.modify(stateRef, (state) => {
const activeKeys = new Set(state.activeKeys);
activeKeys.delete(key);
if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.add(key);
return [true, { ...state, activeKeys, queuedKeys }] as const;
}
return [false, { ...state, activeKeys }] as const;
}).pipe(
Effect.tx,
Effect.flatMap((shouldRequeue) =>
shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
),
);
yield* TxQueue.take(queue).pipe(
Effect.flatMap((key) =>
TxRef.modify(stateRef, (state) => {
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.delete(key);
const value = state.latestByKey.get(key);
if (value === undefined) {
return [null, { ...state, queuedKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
latestByKey.delete(key);
const activeKeys = new Set(state.activeKeys);
activeKeys.add(key);
return [
{ key, value } as const,
{ ...state, latestByKey, queuedKeys, activeKeys },
] as const;
}).pipe(Effect.tx),
),
Effect.flatMap((item) =>
item === null
? Effect.void
: processKey(item.key, item.value).pipe(
Effect.catchCause(() => cleanupFailedKey(item.key)),
),
),
Effect.forever,
Effect.forkScoped,
);
const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
TxRef.modify(stateRef, (state) => {
const latestByKey = new Map(state.latestByKey);
const existing = latestByKey.get(key);
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
return [false, { ...state, latestByKey }] as const;
}
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.add(key);
return [true, { ...state, latestByKey, queuedKeys }] as const;
}).pipe(
Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
Effect.tx,
Effect.asVoid,
);
const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
TxRef.get(stateRef).pipe(
Effect.tap((state) =>
state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
? Effect.txRetry
: Effect.void,
),
Effect.asVoid,
Effect.tx,
);
return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
});
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more