Compare commits

..
Author SHA1 Message Date
Cursor Agent b416bef800 Remove dead-code utility functions from json-schema.ts
Remove five exported functions (asJsonSchemaRecord, getJsonSchemaProperty,
getNullableJsonSchemaBranch, getJsonSchemaAnyOfBranches, setJsonSchemaDescription)
that are never imported by any other file in the codebase.
2026-03-31 05:42:33 +00:00
Julius Marminge c3097ba5d7 Move schema descriptions into contracts
- Inline settings and keybinding schema descriptions in shared contracts
- Simplify schema generation scripts to emit the updated docs
2026-03-30 22:31:33 -07:00
Julius Marminge 32f1d4c34f Merge remote-tracking branch 'origin/main' into t3code/server-settings-schema 2026-03-30 15:49:59 -07:00
Julius Marminge 80475e854c Skip unchanged versioned schema writes
- Avoid writing versioned schema snapshots when the latest schema content did not change
- Add coverage for keybindings, server settings, and release version updates
2026-03-30 15:44:56 -07:00
Julius Marminge aeaf31ff6d Rename published schema artifacts to .json
- Move server settings and keybindings schema URLs to shorter `.json` paths
- Update release tooling, docs, and tests to match the new schema locations
2026-03-30 15:39:49 -07:00
Julius Marminge 8b9cf23ec7 Sync settings descriptions with schema metadata
- Centralize settings copy in schema annotations
- Reuse schema descriptions in the settings UI
- Refresh generated server settings schema output
2026-03-30 15:33:18 -07:00
Julius Marminge 68ff6d8578 Format marketing schema enums consistently
- Reflow schema arrays and required lists
- Keep published server settings and keybindings schemas normalized
2026-03-30 15:29:07 -07:00
Julius Marminge 8f5078c6d5 Annotate settings and keybinding schemas with docs
- Add schema descriptions for editor tooling and generated JSON schemas
- Update published keybindings and server settings schema docs
2026-03-30 15:27:37 -07:00
Julius Marminge 48fc85e7fe Bump Effect catalog dependencies (#1594) 2026-03-30 22:08:25 +00:00
Julius Marminge f1793ad2eb Generate and preserve keybindings schemas
- Add marketing JSON Schema artifacts for keybindings
- Reuse shared JSON schema writer for server settings and keybindings
- Preserve top-level `$schema` when rewriting settings
2026-03-30 14:46:42 -07:00
Julius Marminge 805c68dd0e Use Node executable for release smoke manifest merge
- Run the manifest merge script with `process.execPath` instead of `bun`
- Keeps the smoke test aligned with the current Node runtime
2026-03-30 14:33:33 -07:00
Julius Marminge e835adeb16 Publish server settings schema with release versions
- Generate the marketing schema and versioned copies during release version bumps
- Move JSON Schema export helper into shared utilities
- Update release smoke coverage and schema generation tests
2026-03-30 14:24:19 -07:00
0ea639196a Refactor web orchestration sync to incremental events and isolated recovery (#1560)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-30 12:51:49 -07:00
Utkarsh Patil 6f51725732 refactor(web): remove redundant add-project cancel button (#1302) 2026-03-30 10:31:38 -07:00
Julius Marminge 8622b952ca Refactor terminal manager onto Effect runtime (#1525) 2026-03-30 10:19:11 -07:00
Julius Marminge f47c1f1046 Update README.md (#1565) 2026-03-30 05:37:28 +00:00
Julius Marminge 145ddfc408 Document T3 Code install methods (#1564) 2026-03-29 22:33:05 -07:00
Ivor 0bb787b90d Clarify provider setup in README (#1406) 2026-03-29 22:09:23 -07:00
72 changed files with 7958 additions and 2823 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: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: bun 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: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: bun 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: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
run: bun 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 bun.lock; then
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
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 bun.lock
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 commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
+23
View File
@@ -15,6 +15,29 @@ 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
+28 -4
View File
@@ -2,18 +2,42 @@
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## How to use
## Installation
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
> 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
```bash
npx t3
```
You can also just install the desktop app. It's cooler.
### Desktop app
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
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
```
## Some notes
@@ -0,0 +1,69 @@
{
"$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`."
}
]
}
@@ -0,0 +1,69 @@
{
"$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
@@ -0,0 +1,302 @@
{
"$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": "Show token-by-token output while a response is in progress."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Pick the default workspace mode for newly created draft 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": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
{
"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 binary"
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional custom Codex home and config directory."
},
{
"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 binary"
},
{
"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
}
@@ -0,0 +1,302 @@
{
"$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
}
@@ -13,6 +13,7 @@ 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";
@@ -27,7 +28,6 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -5,6 +5,7 @@ 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";
@@ -26,7 +27,6 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
-9
View File
@@ -14,15 +14,6 @@ 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;
+3 -13
View File
@@ -34,7 +34,6 @@ import {
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
@@ -44,7 +43,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -418,16 +417,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
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,
}),
);
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -676,7 +666,7 @@ const makeKeybindings = Effect.gen(function* () {
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
+46
View File
@@ -216,4 +216,50 @@ 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())),
);
});
+31 -2
View File
@@ -39,7 +39,7 @@ import {
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
@@ -101,6 +101,9 @@ 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"];
@@ -177,6 +180,7 @@ 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));
@@ -207,10 +211,25 @@ 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);
}
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -232,7 +251,17 @@ const makeServerSettings = Effect.gen(function* () {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
return Ref.get(schemaDeclarationRef).pipe(
Effect.map((schemaDeclaration) =>
schemaDeclaration
? {
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
...sparseSettings,
}
: sparseSettings,
),
Effect.flatMap(encodeServerSettingsDocument),
Effect.map((encoded) => `${encoded}\n`),
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
+71 -38
View File
@@ -14,47 +14,81 @@ import {
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalSessionStatus,
TerminalWriteInput,
} from "@t3tools/contracts";
import { PtyProcess } from "./PTY";
import { Effect, Schema, ServiceMap } from "effect";
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 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 interface ShellCandidate {
shell: string;
args?: string[];
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 TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number;
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 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.
*/
@@ -101,14 +135,13 @@ export interface TerminalManagerShape {
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Subscribe to terminal runtime events.
* Subscribe to terminal runtime events with a direct callback.
*
* Returns an unsubscribe function.
*/
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
/**
* Dispose all managed terminal resources.
*/
readonly dispose: Effect.Effect<void>;
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
}
/**
+21 -14
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, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
@@ -90,20 +90,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
private activeSubscriptions = 0;
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
emitEvent(event: TerminalEvent): void {
for (const listener of this.listeners) {
listener(event);
}
Effect.runSync(PubSub.publish(this.eventPubSub, event));
}
subscriptionCount(): number {
return this.listeners.size;
return this.activeSubscriptions;
}
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
@@ -210,13 +209,15 @@ class MockTerminalManager implements TerminalManagerShape {
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
Effect.sync(() => {
this.listeners.add(listener);
this.activeSubscriptions += 1;
const fiber = Effect.runFork(
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
);
return () => {
this.listeners.delete(listener);
this.activeSubscriptions -= 1;
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
};
});
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
}
// ---------------------------------------------------------------------------
@@ -1454,19 +1455,25 @@ describe("WebSocket Server", () => {
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
});
it("detaches terminal event listener on stop for injected manager", async () => {
it("shuts down cleanly for injected terminal managers", async () => {
const terminalManager = new MockTerminalManager();
server = await createTestServer({
cwd: "/test",
terminalManager,
});
expect(terminalManager.subscriptionCount()).toBe(1);
await closeTestServer();
server = null;
expect(terminalManager.subscriptionCount()).toBe(0);
expect(() =>
terminalManager.emitEvent({
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "after shutdown\n",
}),
).not.toThrow();
});
it("returns validation errors for invalid terminal open params", async () => {
+2 -2
View File
@@ -719,9 +719,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
+88 -45
View File
@@ -2,8 +2,11 @@
import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_WS_CHANNELS,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
type ServerConfig,
@@ -57,6 +60,8 @@ 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 {
@@ -336,6 +341,79 @@ 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,
@@ -500,10 +578,12 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const worker = setupWorker(
wsLink.addEventListener("connection", ({ client }) => {
wsClient = client;
pushSequence = 1;
client.send(
JSON.stringify({
type: "push",
sequence: 1,
sequence: pushSequence++,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
@@ -875,7 +955,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
bootstrapComplete: false,
});
});
@@ -1773,36 +1853,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("restores the connecting composer state without showing the stop button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-connecting-state" as MessageId,
targetText: "connecting state target",
sessionStatus: "starting",
}),
});
try {
const connectingButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Connecting"]'),
"Unable to find connecting send button.",
);
expect(connectingButton.disabled).toBe(true);
expect(
document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
).toBeNull();
const composerEditor = await waitForElement(
() => document.querySelector<HTMLElement>('[contenteditable="false"]'),
"Unable to find disabled composer editor.",
);
expect(composerEditor).toBeTruthy();
} finally {
await mounted.cleanup();
}
});
it("hides the archive action when the pointer leaves a thread row", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1911,21 +1961,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// 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);
// 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);
// 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 snapshot sync clears the draft.",
"New thread should remain selected after server thread promotion clears the draft.",
);
// The empty thread view and composer should still be visible.
@@ -2247,9 +2292,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
await promoteDraftThreadViaDomainEvent(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
mounted.router,
+297 -3
View File
@@ -1,7 +1,14 @@
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
import {
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
waitForStartedServerThread,
} from "./ChatView.logic";
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
@@ -67,3 +74,290 @@ 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);
});
});
+116 -3
View File
@@ -1,8 +1,9 @@
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } 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,
@@ -34,7 +35,6 @@ export function buildLocalDraftThread(
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
@@ -159,3 +159,116 @@ 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)
);
}
+317 -193
View File
@@ -20,6 +20,7 @@ import {
OrchestrationThreadActivity,
ProviderInteractionMode,
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { truncate } from "@t3tools/shared/String";
@@ -42,6 +43,7 @@ import {
replaceTextRange,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -64,6 +66,8 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
import { useProjectById, useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -76,8 +80,12 @@ 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";
@@ -168,13 +176,18 @@ import {
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
waitForStartedServerThread,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -189,6 +202,81 @@ 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;
@@ -244,19 +332,81 @@ 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 beginThreadSend = useStore((store) => store.beginThreadSend);
const clearThreadSend = useStore((store) => store.clearThreadSend);
const markThreadSendSettled = useStore((store) => store.markThreadSendSettled);
const moveThreadSend = useStore((store) => store.moveThreadSend);
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
const pendingThreadSend = useStore((store) => store.pendingThreadSendById[threadId] ?? null);
const setThreadSendPhase = useStore((store) => store.setThreadSendPhase);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const serverThread = useThreadById(threadId);
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 setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
@@ -330,10 +480,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
optimisticUserMessagesRef.current = optimisticUserMessages;
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
@@ -467,8 +619,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
);
const serverThread = threads.find((t) => t.id === threadId);
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
const fallbackDraftProject = useProjectById(draftThread?.projectId);
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
const localDraftThread = useMemo(
() =>
@@ -496,12 +647,25 @@ 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 = projects.find((p) => p.id === activeThread?.projectId);
const activeProject = useProjectById(activeThread?.projectId);
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -596,33 +760,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
useEffect(() => {
if (!activeThread?.id) return;
if (!serverThread?.id) return;
if (!latestTurnSettled) return;
if (!activeLatestTurn?.completedAt) return;
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnCompletedAt)) return;
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
markThreadVisited(activeThread.id);
markThreadVisited(serverThread.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 = Boolean(
activeThread &&
(activeThread.latestTurn !== null ||
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const hasThreadStarted = threadHasStarted(activeThread);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -665,19 +824,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const activeSendStartedAt = pendingThreadSend?.startedAt ?? null;
const isSendBusy = pendingThreadSend !== null;
const isPreparingWorktree =
pendingThreadSend?.phase === "preparing-worktree" && createWorktreeMutation.isPending;
const isConnecting = phase === "connecting";
const showConnectingState = isConnecting && !isSendBusy;
const isWorking = phase === "running" || isSendBusy || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
activeSendStartedAt,
);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -740,12 +886,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const sidebarProposedPlan = useMemo(
() =>
findSidebarProposedPlan({
threads,
threads: threadPlanCatalog,
latestTurn: activeLatestTurn,
latestTurnSettled,
threadId: activeThread?.id ?? null,
}),
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
);
const activePlan = useMemo(
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -757,6 +903,27 @@ 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 ||
@@ -985,35 +1152,9 @@ 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;
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,
]);
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
@@ -1143,6 +1284,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
null,
[composerHighlightedItemId, composerMenuItems],
);
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
@@ -1232,7 +1376,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
if (threads.some((thread) => thread.id === targetThreadId)) {
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
setStoreThreadError(targetThreadId, error);
return;
}
@@ -1246,7 +1390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[setStoreThreadError, threads],
[setStoreThreadError],
);
const focusComposer = useCallback(() => {
@@ -1413,7 +1557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
? {
threadId: activeThreadId,
terminalId: targetTerminalId,
@@ -1982,16 +2126,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts]);
useEffect(() => {
optimisticUserMessagesRef.current = optimisticUserMessages;
}, [optimisticUserMessages]);
useEffect(() => {
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
}, [activeComposerMenuItem, composerMenuItems, composerMenuOpen]);
useEffect(() => {
if (!activeThread?.id) return;
if (activeThread.messages.length === 0) {
@@ -2032,14 +2166,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
sendInFlightRef.current = false;
resetLocalDispatch();
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [threadId]);
}, [resetLocalDispatch, threadId]);
useEffect(() => {
let cancelled = false;
@@ -2163,14 +2297,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
: "local";
useEffect(() => {
if (phase !== "running" && !isSendBusy) return;
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [isSendBusy, phase]);
}, [phase]);
useEffect(() => {
if (!activeThreadId) return;
@@ -2390,7 +2524,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy) {
if (phase === "running" || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -2423,13 +2557,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
setIsRevertingCheckpoint(false);
},
[activeThread, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
);
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || sendInFlightRef.current) return;
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -2508,13 +2642,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
const sendStartedAt = new Date().toISOString();
sendInFlightRef.current = true;
beginThreadSend(
threadIdForSend,
baseBranchForWorktree ? "preparing-worktree" : "sending-turn",
sendStartedAt,
);
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2585,9 +2714,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
try {
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2662,8 +2792,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
let shouldRunSetupScript = false;
if (isServerThread) {
shouldRunSetupScript = true;
} else if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
} else {
if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
}
if (shouldRunSetupScript) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
@@ -2697,9 +2829,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
if (baseBranchForWorktree) {
setThreadSendPhase(threadIdForSend, "sending-turn");
}
beginLocalDispatch({ preparingWorktree: false });
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2718,8 +2848,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
markThreadSendSettled(threadIdForSend);
} catch (err: unknown) {
})().catch(async (err: unknown) => {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
@@ -2754,9 +2883,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadIdForSend,
err instanceof Error ? err.message : "Failed to send message.",
);
clearThreadSend(threadIdForSend);
}
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetLocalDispatch();
}
};
const onInterrupt = async () => {
@@ -2926,7 +3057,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
interactionMode: "default" | "plan";
}) => {
const api = readNativeApi();
if (!api || !activeThread || !isServerThread || isSendBusy || sendInFlightRef.current) {
if (
!api ||
!activeThread ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return;
}
@@ -2947,7 +3085,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginThreadSend(threadIdForSend, "sending-turn", new Date().toISOString());
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -2999,7 +3137,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
: {}),
createdAt: messageCreatedAt,
});
markThreadSendSettled(threadIdForSend);
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
@@ -3007,33 +3144,34 @@ export default function ChatView({ threadId }: ChatViewProps) {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
}
sendInFlightRef.current = false;
} catch (err) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
clearThreadSend(threadIdForSend);
setThreadError(
threadIdForSend,
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetLocalDispatch();
}
sendInFlightRef.current = false;
},
[
activeThread,
activeProposedPlan,
beginLocalDispatch,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
setComposerDraftInteractionMode,
setThreadError,
selectedModel,
@@ -3049,6 +3187,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
!activeProposedPlan ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return;
@@ -3069,10 +3208,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginThreadSend(activeThread.id, "sending-turn", createdAt);
beginLocalDispatch({ preparingWorktree: false });
const finish = () => {
sendInFlightRef.current = false;
resetLocalDispatch();
};
try {
await api.orchestration.dispatchCommand({
await api.orchestration
.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: nextThreadId,
@@ -3084,76 +3227,67 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
createdAt,
});
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
moveThreadSend(activeThread.id, nextThreadId);
markThreadSendSettled(nextThreadId);
const snapshot = await api.orchestration.getSnapshot();
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
await navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
} catch (err) {
clearThreadSend(activeThread.id);
clearThreadSend(nextThreadId);
await api.orchestration
.dispatchCommand({
type: "thread.delete",
})
.then(() => {
return api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
}
sendInFlightRef.current = false;
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
})
.then(() => {
return waitForStartedServerThread(nextThreadId);
})
.then(() => {
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
})
.catch(async (err) => {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: nextThreadId,
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
})
.then(finish, finish);
}, [
activeProject,
activeProposedPlan,
activeThread,
beginLocalDispatch,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
moveThreadSend,
syncServerReadModel,
selectedModel,
]);
@@ -3820,7 +3954,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={showConnectingState || isComposerApprovalState}
disabled={isConnecting || isComposerApprovalState}
/>
</div>
@@ -4045,13 +4179,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-full px-4 sm:h-8"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
>
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Refine"}
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
</Button>
) : (
<div className="flex items-center">
@@ -4059,13 +4189,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
>
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Implement"}
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
</Button>
<Menu>
<MenuTrigger
@@ -4075,7 +4201,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
variant="default"
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
aria-label="Implementation actions"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
/>
}
>
@@ -4083,7 +4209,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -4097,21 +4223,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={
isSendBusy ||
showConnectingState ||
!composerSendState.hasSendableContent
isSendBusy || isConnecting || !composerSendState.hasSendableContent
}
aria-label={
isPreparingWorktree
? "Preparing worktree"
: showConnectingState
? "Connecting"
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
}
>
{showConnectingState || isSendBusy ? (
{isConnecting || isSendBusy ? (
<svg
width="14"
height="14"
@@ -323,7 +323,7 @@ describe("Keybindings update toast", () => {
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
bootstrapComplete: false,
});
});
+47 -3
View File
@@ -9,6 +9,7 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -18,7 +19,7 @@ import {
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -29,7 +30,7 @@ import {
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
}): OrchestrationLatestTurn {
return {
turnId: "turn-1" as never,
state: "completed",
@@ -163,6 +164,50 @@ 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 = [
@@ -552,7 +597,6 @@ function makeProject(overrides: Partial<Project> = {}): Project {
model: "gpt-5.4",
...defaultModelSelection,
},
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
+52 -12
View File
@@ -17,7 +17,10 @@ type SidebarProject = {
createdAt?: string | undefined;
updatedAt?: string | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
latestUserMessageAt?: string | null;
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
};
export type ThreadTraversalDirection = "previous" | "next";
@@ -45,8 +48,10 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
> & {
lastVisitedAt?: string | undefined;
};
export interface ThreadJumpHintVisibilityController {
sync: (shouldShow: boolean) => void;
@@ -156,6 +161,34 @@ 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;
@@ -327,15 +360,15 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
threads: readonly T[];
activeThreadId: T["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
hiddenThreads: Thread[];
visibleThreads: Thread[];
visibleThreads: T[];
hiddenThreads: T[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
@@ -382,9 +415,13 @@ 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;
@@ -412,7 +449,7 @@ function getThreadSortTimestamp(
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
@@ -425,7 +462,7 @@ export function sortThreadsForSidebar<
}
export function getFallbackThreadIdAfterDelete<
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(input: {
threads: readonly T[];
deletedThreadId: T["id"];
@@ -469,7 +506,10 @@ export function getProjectSortTimestamp(
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
export function sortProjectsForSidebar<
TProject extends SidebarProject,
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
+121 -24
View File
@@ -21,6 +21,7 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { useShallow } from "zustand/react/shallow";
import {
DndContext,
type DragCancelEvent,
@@ -55,6 +56,7 @@ 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,
@@ -114,6 +116,7 @@ import {
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
@@ -122,6 +125,7 @@ import {
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import type { Project, Thread } from "../types";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -138,6 +142,80 @@ 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;
@@ -361,10 +439,17 @@ function SortableProjectItem({
export default function Sidebar() {
const projects = useStore((store) => store.projects);
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 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 clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
@@ -418,6 +503,28 @@ 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],
@@ -752,7 +859,7 @@ export default function Sidebar() {
}
if (clicked === "mark-unread") {
markThreadUnread(threadId);
markThreadUnread(threadId, thread.latestTurn?.completedAt);
return;
}
if (clicked === "copy-path") {
@@ -814,7 +921,8 @@ export default function Sidebar() {
if (clicked === "mark-unread") {
for (const id of ids) {
markThreadUnread(id);
const thread = threads.find((candidate) => candidate.id === id);
markThreadUnread(id, thread?.latestTurn?.completedAt);
}
clearSelection();
return;
@@ -845,6 +953,7 @@ export default function Sidebar() {
markThreadUnread,
removeFromSelection,
selectedThreadIds,
threads,
],
);
@@ -987,12 +1096,12 @@ export default function Sidebar() {
dragInProgressRef.current = false;
const { active, over } = event;
if (!over || active.id === over.id) return;
const activeProject = projects.find((project) => project.id === active.id);
const overProject = projects.find((project) => project.id === over.id);
const activeProject = sidebarProjects.find((project) => project.id === active.id);
const overProject = sidebarProjects.find((project) => project.id === over.id);
if (!activeProject || !overProject) return;
reorderProjects(activeProject.id, overProject.id);
},
[appSettings.sidebarProjectSortOrder, projects, reorderProjects],
[appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects],
);
const handleProjectDragStart = useCallback(
@@ -1052,8 +1161,9 @@ export default function Sidebar() {
[threads],
);
const sortedProjects = useMemo(
() => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, projects, visibleThreads],
() =>
sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads],
);
const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
const renderedProjects = useMemo(
@@ -1934,7 +2044,6 @@ export default function Sidebar() {
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
@@ -1985,18 +2094,6 @@ 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>
)}
@@ -549,10 +549,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
<span>
{(() => {
const elapsed = row.createdAt ? formatWorkingTimer(row.createdAt, nowIso) : null;
return elapsed ? `Working for ${elapsed}` : "Working...";
})()}
{row.createdAt
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
: "Working..."}
</span>
</div>
</div>
@@ -644,9 +643,6 @@ function formatWorkingTimer(startIso: string, endIso: string): string | null {
}
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
if (elapsedSeconds < 1) {
return null;
}
if (elapsedSeconds < 60) {
return `${elapsedSeconds}s`;
}
@@ -12,14 +12,19 @@ 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 {
@@ -81,6 +86,51 @@ 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 = {
@@ -98,16 +148,16 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
provider: "codex",
title: "Codex",
binaryPlaceholder: "Codex binary path",
binaryDescription: "Path to the Codex binary",
binaryDescription: SETTINGS_DESCRIPTIONS.codexBinaryPath,
homePathKey: "codexHomePath",
homePlaceholder: "CODEX_HOME",
homeDescription: "Optional custom Codex home and config directory.",
homeDescription: SETTINGS_DESCRIPTIONS.codexHomePath,
},
{
provider: "claudeAgent",
title: "Claude",
binaryPlaceholder: "Claude binary path",
binaryDescription: "Path to the Claude binary",
binaryDescription: SETTINGS_DESCRIPTIONS.claudeBinaryPath,
},
] as const;
@@ -774,7 +824,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Time format"
description="System default follows your browser or OS clock preference."
description={SETTINGS_DESCRIPTIONS.timestampFormat}
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
<SettingResetButton
@@ -816,7 +866,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Diff line wrapping"
description="Set the default wrap state when the diff panel opens."
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
<SettingResetButton
@@ -840,7 +890,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Assistant output"
description="Show token-by-token output while a response is in progress."
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
@@ -867,7 +917,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="New threads"
description="Pick the default workspace mode for newly created draft threads."
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
<SettingResetButton
@@ -908,7 +958,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Archive confirmation"
description="Require a second click on the inline archive action before a thread is archived."
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
<SettingResetButton
@@ -934,7 +984,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Delete confirmation"
description="Ask before deleting a thread and its chat history."
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
<SettingResetButton
@@ -960,7 +1010,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Text generation model"
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
resetAction={
isGitWritingModelDirty ? (
<SettingResetButton
+53
View File
@@ -9,6 +9,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
COMPOSER_DRAFT_STORAGE_KEY,
clearPromotedDraftThread,
clearPromotedDraftThreads,
type ComposerImageAttachment,
useComposerDraftStore,
} from "./composerDraftStore";
@@ -549,6 +551,57 @@ 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, {
+14 -11
View File
@@ -2195,18 +2195,21 @@ export function useEffectiveComposerModelState(input: {
}
/**
* Clear draft threads that have been promoted to server threads.
* Clear a draft thread once the server has materialized the same thread id.
*
* 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.
* 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.
*/
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);
}
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);
}
}
+16 -8
View File
@@ -1,29 +1,37 @@
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback } from "react";
import { useCallback, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
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 projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
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 activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projectIds,
preferredIds: projectOrder,
getId: (projectId) => projectId,
});
}, [projectIds, projectOrder]);
const handleNewThread = useCallback(
(
@@ -111,8 +119,8 @@ export function useHandleNewThread() {
return {
activeDraftThread,
activeThread,
defaultProjectId: orderedProjects[0] ?? null,
handleNewThread,
projects,
routeThreadId,
};
}
+5 -8
View File
@@ -16,8 +16,6 @@ import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
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(
@@ -37,7 +35,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
const thread = useStore.getState().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.");
@@ -53,7 +51,7 @@ export function useThreadActions() {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId, threads],
[handleNewThread, routeThreadId],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
@@ -70,6 +68,7 @@ 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);
@@ -171,10 +170,8 @@ export function useThreadActions() {
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
@@ -182,7 +179,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
@@ -199,7 +196,7 @@ export function useThreadActions() {
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread, threads],
[appSettings.confirmThreadDelete, deleteThread],
);
return {
@@ -0,0 +1,108 @@
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
@@ -0,0 +1,76 @@
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
@@ -0,0 +1,100 @@
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
@@ -0,0 +1,136 @@
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;
},
};
}
+2 -10
View File
@@ -1,11 +1,8 @@
import { createElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter } from "@tanstack/react-router";
import { createRouter, RouterHistory } 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();
@@ -16,12 +13,7 @@ export function getRouter(history: RouterHistory) {
context: {
queryClient,
},
Wrap: ({ children }) =>
createElement(
QueryClientProvider,
{ client: queryClient },
createElement(StoreProvider, null, children),
),
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
});
}
+146 -47
View File
@@ -1,4 +1,4 @@
import { ThreadId } from "@t3tools/contracts";
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
import {
Outlet,
createRootRouteWithContext,
@@ -17,8 +17,13 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
import {
clearPromotedDraftThread,
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";
@@ -26,6 +31,8 @@ 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";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -135,8 +142,13 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
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 removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
@@ -152,56 +164,40 @@ function EventRouter() {
const api = readNativeApi();
if (!api) return;
let disposed = false;
let latestSequence = 0;
let syncing = false;
let pending = false;
const recovery = createOrchestrationRecoveryCoordinator();
let needsProviderInvalidation = false;
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 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 draftThreadIds = Object.keys(
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: snapshot.threads,
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
if (pending) {
pending = false;
await flushSnapshotSync();
}
};
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(
const queryInvalidationThrottler = new Throttler(
() => {
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 });
if (!needsProviderInvalidation) {
return;
}
void syncSnapshot();
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 });
},
{
wait: 100,
@@ -210,15 +206,113 @@ function EventRouter() {
},
);
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
if (event.sequence <= latestSequence) {
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
}
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
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]);
return;
}
if (action === "recover") {
void recoverFromSequenceGap();
}
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -237,7 +331,7 @@ function EventRouter() {
// Migrate old localStorage settings to server on first connect
migrateLocalSettingsToServer();
void (async () => {
await syncSnapshot();
await bootstrapFromSnapshot();
if (disposed) {
return;
}
@@ -319,7 +413,7 @@ function EventRouter() {
return () => {
disposed = true;
needsProviderInvalidation = false;
domainEventFlushThrottler.cancel();
queryInvalidationThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
@@ -327,11 +421,16 @@ function EventRouter() {
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 threadsHydrated = useStore((store) => store.threadsHydrated);
const bootstrapComplete = useStore((store) => store.bootstrapComplete);
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
@@ -202,7 +202,7 @@ function ChatThreadRouteView() {
}, [diffOpen]);
useEffect(() => {
if (!threadsHydrated) {
if (!bootstrapComplete) {
return;
}
@@ -210,9 +210,9 @@ function ChatThreadRouteView() {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
}, [bootstrapComplete, navigate, routeThreadExists, threadId]);
if (!threadsHydrated || !routeThreadExists) {
if (!bootstrapComplete || !routeThreadExists) {
return null;
}
+14 -11
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, handleNewThread, projects, routeThreadId } =
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, 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 ?? projects[0]?.id;
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId;
if (!projectId) return;
const command = resolveShortcutCommand(event, keybindings, {
@@ -59,14 +59,17 @@ function ChatRouteGlobalShortcuts() {
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"),
});
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;
}
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -79,7 +82,7 @@ function ChatRouteGlobalShortcuts() {
clearSelection,
handleNewThread,
keybindings,
projects,
defaultProjectId,
selectedThreadIdsSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
+32
View File
@@ -8,6 +8,7 @@ import {
import { describe, expect, it } from "vitest";
import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
PROVIDER_OPTIONS,
@@ -964,6 +965,37 @@ 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,6 +852,53 @@ 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> {
+452 -215
View File
@@ -1,19 +1,19 @@
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 {
beginThreadSend,
clearThreadSend,
markThreadUnread,
markThreadSendSettled,
reorderProjects,
setThreadSendPhase,
applyOrchestrationEvent,
applyOrchestrationEvents,
syncServerReadModel,
type AppState,
} from "./store";
@@ -48,7 +48,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
function makeState(thread: Thread): AppState {
return {
pendingThreadSendById: {},
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
@@ -58,15 +57,41 @@ function makeState(thread: Thread): AppState {
provider: "codex",
model: "gpt-5-codex",
},
expanded: true,
scripts: [],
},
],
threads: [thread],
threadsHydrated: true,
bootstrapComplete: 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"),
@@ -136,98 +161,18 @@ function makeReadModelProject(
};
}
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 = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
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 = {
pendingThreadSendById: {},
projects: [
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project3,
name: "Project 3",
cwd: "/tmp/project-3",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
describe("store read model sync", () => {
it("marks bootstrap complete after snapshot sync", () => {
const initialState: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = reorderProjects(state, project1, project3);
const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({})));
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
expect(next.bootstrapComplete).toBe(true);
});
});
describe("store read model sync", () => {
it("preserves claude model slugs without an active session", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
@@ -298,12 +243,11 @@ describe("store read model sync", () => {
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
});
it("preserves the current project order when syncing incoming read model updates", () => {
it("replaces projects using snapshot order during recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState: AppState = {
pendingThreadSendById: {},
projects: [
{
id: project2,
@@ -313,7 +257,6 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
@@ -324,12 +267,11 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
bootstrapComplete: true,
};
const readModel: OrchestrationReadModel = {
snapshotSequence: 2,
@@ -356,151 +298,446 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
});
});
it("keeps pending sends until the server catches up to the send", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
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",
}),
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:00:59.000Z",
startedAt: "2026-02-27T00:01:01.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
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.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
});
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("does not clear pending sends when the turn appears before the request settles", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
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("clears pending sends once the server session starts running", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
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 = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
const next = applyOrchestrationEvents(state, [
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId,
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:01:02.000Z",
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.pendingThreadSendById[threadId]).toBeUndefined();
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
});
it("clears settled pending sends once the turn has caught up", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = markThreadSendSettled(
beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
),
threadId,
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 = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
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"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
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: [],
},
],
}),
);
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
});
});
describe("store pending thread send helpers", () => {
it("updates and clears pending thread send state", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const startedState = beginThreadSend(
makeState(makeThread()),
threadId,
"preparing-worktree",
"2026-02-27T00:01:00.000Z",
const next = applyOrchestrationEvent(
state,
makeEvent("thread.reverted", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
}),
);
const sendingState = setThreadSendPhase(startedState, threadId, "sending-turn");
const settledState = markThreadSendSettled(sendingState, threadId);
const clearedState = clearThreadSend(settledState, threadId);
expect(startedState.pendingThreadSendById[threadId]?.phase).toBe("preparing-worktree");
expect(startedState.pendingThreadSendById[threadId]?.requestSettled).toBe(false);
expect(sendingState.pendingThreadSendById[threadId]?.phase).toBe("sending-turn");
expect(settledState.pendingThreadSendById[threadId]?.requestSettled).toBe(true);
expect(clearedState.pendingThreadSendById[threadId]).toBeUndefined();
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();
});
});
+789 -504
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
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,6 +485,7 @@ interface TerminalStateStoreState {
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
}
@@ -530,6 +531,15 @@ 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(
+2 -9
View File
@@ -16,7 +16,6 @@ import type {
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type PendingThreadSendPhase = "preparing-worktree" | "sending-turn";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_INTERACTION_MODE: ProviderInteractionMode = "default";
@@ -46,6 +45,7 @@ export interface ChatMessage {
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
turnId?: TurnId | null;
createdAt: string;
completedAt?: string | undefined;
streaming: boolean;
@@ -83,7 +83,6 @@ export interface Project {
name: string;
cwd: string;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
@@ -105,7 +104,7 @@ export interface Thread {
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"];
branch: string | null;
worktreePath: string | null;
turnDiffSummaries: TurnDiffSummary[];
@@ -121,9 +120,3 @@ export interface ThreadSession {
lastError?: string;
orchestrationStatus: OrchestrationSessionStatus;
}
export interface PendingThreadSend {
phase: PendingThreadSendPhase;
startedAt: string;
requestSettled: boolean;
}
+192
View File
@@ -0,0 +1,192 @@
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
@@ -0,0 +1,417 @@
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();
});
}
+11 -11
View File
@@ -176,13 +176,13 @@
"vite": "^8.0.0",
},
"catalog": {
"@effect/language-service": "0.84.1",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@effect/language-service": "0.84.2",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"effect": "4.0.0-beta.42",
"effect": "4.0.0-beta.43",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
@@ -268,15 +268,15 @@
"@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],
"@effect/language-service": ["@effect/[email protected].1", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-YUqjJU24HeYgPV453cR2fDqkZ+zZKMuxGnmxWAPscWJ6gt6FB7JZohMCOczRTIOGPrQMcloJX7BjCaPu+RNhpw=="],
"@effect/language-service": ["@effect/[email protected].2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="],
"@effect/platform-node": ["@effect/[email protected]2", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.42", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42", "ioredis": "^5.7.0" } }, "sha512-kbdRML2FBa4q8U8rZQcnmLKZ5zN/z1bAA7t5D1/UsBHZqJgnfRgu1CP6kaEfb1Nie6YyaWshxTktZQryjvW/Yg=="],
"@effect/platform-node": ["@effect/[email protected]3", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43", "ioredis": "^5.7.0" } }, "sha512-Uq6E1rjaIpjHauzjwoB2HzAg3battYt2Boy8XO50GoHiWCXKE6WapYZ0/AnaBx5v5qg2sOfqpuiLsUf9ZgxOkA=="],
"@effect/platform-node-shared": ["@effect/[email protected]2", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-PC+lxLsrwob3+nBChAPrQq32olCeyApgXBvs1NrRsoArLViNT76T/68CttuCAksCZj5e1bZ1ZibLPel3vUmx2g=="],
"@effect/platform-node-shared": ["@effect/[email protected]3", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-A9q0GEb61pYcQ06Dr6gXj1nKlDI3KHsar1sk3qb1ZY+kVSR64tBAylI8zGon23KY+NPtTUj/sEIToB7jc3Qt5w=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-Ah2QfkeV+I9r5OBVJijSDnFXCv51giBXngSwhju5gefc0uWiM3G1tsYAqrNX24HlvFFEnOAZqNf/Sq1h4NqOAA=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-Ryb7x0rBjW5NHegbzvz9y2Yv4KpwZ1UiPk7/Rv+Mkux74Qkjdmotmrvy9P+M5A9TZyL2Av+GpaLTPJKsL0PG+Q=="],
"@effect/vitest": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-/11arjUnCRhIrBRvOn/nrbg5p/FadjAPvStddZlpl1VrCxtB2s0n39cbG9uTyDdf1ZrRBG73Upo1ZDF1CTWy8w=="],
"@effect/vitest": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-XN2LAwiUWPqbV2jrsYYRjrVydQ8MIgwr83MVImtUaOQco4vk43+8OHlXQMRN/u2HnGK29KT+O2yTMMBdk2Q6Sw=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -1020,7 +1020,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"effect": ["[email protected]2", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-c1UrRP+tLzyHb4Fepl8XBDJlLQLkrcMXrRBba441GQRxMbeQ/aIOSFcBwSda1iMJ5l9F0lYc3Bhe33/whrmavQ=="],
"effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
+2
View File
@@ -17,6 +17,8 @@ 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
+5 -5
View File
@@ -8,11 +8,11 @@
"scripts"
],
"catalog": {
"effect": "4.0.0-beta.42",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@effect/language-service": "0.84.1",
"effect": "4.0.0-beta.43",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@effect/language-service": "0.84.2",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"tsdown": "^0.20.3",
+6 -6
View File
@@ -130,12 +130,12 @@ export interface NativeApi {
confirm: (message: string) => Promise<boolean>;
};
terminal: {
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>;
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>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
+38 -16
View File
@@ -46,33 +46,55 @@ 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.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
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 KeybindingWhen = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_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));
export const KeybindingRule = Schema.Struct({
key: KeybindingValue,
command: KeybindingCommand,
when: Schema.optional(KeybindingWhen),
key: KeybindingValue.pipe(
Schema.flip,
Schema.annotate({
description: "Keyboard shortcut to listen for.",
}),
Schema.flip,
),
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`.",
});
export type KeybindingRule = typeof KeybindingRule.Type;
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
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 type KeybindingsConfig = typeof KeybindingsConfig.Type;
export const KeybindingShortcut = Schema.Struct({
+37 -6
View File
@@ -9,16 +9,47 @@ 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)),
fastMode: Schema.optional(Schema.Boolean),
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.",
});
export type CodexModelOptions = typeof CodexModelOptions.Type;
export const ClaudeModelOptions = Schema.Struct({
thinking: Schema.optional(Schema.Boolean),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
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.",
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
+41 -7
View File
@@ -46,20 +46,54 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const CodexModelSelection = Schema.Struct({
provider: Schema.Literal("codex"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(CodexModelOptions),
provider: Schema.Literal("codex").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.flip,
Schema.annotate({
description: "The Codex model slug to use for text generation.",
}),
Schema.flip,
),
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.",
});
export type CodexModelSelection = typeof CodexModelSelection.Type;
export const ClaudeModelSelection = Schema.Struct({
provider: Schema.Literal("claudeAgent"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(ClaudeModelOptions),
provider: Schema.Literal("claudeAgent").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.flip,
Schema.annotate({
description: "The Claude model slug to use for text generation.",
}),
Schema.flip,
),
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.",
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]).annotate({
description: "Selects which provider and model T3 Code should use for text generation.",
});
export type ModelSelection = typeof ModelSelection.Type;
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
+80 -28
View File
@@ -23,17 +23,32 @@ 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.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)),
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.",
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -41,11 +56,13 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]).annotate({
description: "Pick the default workspace mode for newly created draft threads.",
});
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
const makeBinaryPathSetting = (fallback: string) =>
TrimmedString.pipe(
const makeBinaryPathSetting = (fallback: string, description: string) =>
makeTrimmedStringSetting(description).pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
@@ -57,26 +74,51 @@ const makeBinaryPathSetting = (fallback: string) =>
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
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.",
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude"),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
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.",
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
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(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
@@ -85,9 +127,19 @@ export const ServerSettings = Schema.Struct({
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
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`.",
});
export type ServerSettings = typeof ServerSettings.Type;
+2 -2
View File
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
export const TerminalThreadInput = Schema.Struct({
threadId: TrimmedNonEmptyStringSchema,
});
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
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 = Schema.Codec.Encoded<typeof TerminalCloseInput>;
export type TerminalCloseInput = typeof TerminalCloseInput.Type;
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
+4
View File
@@ -28,6 +28,10 @@
"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"
@@ -0,0 +1,96 @@
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"]);
}),
),
);
});
@@ -0,0 +1,140 @@
/**
* 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>;
});
+67
View File
@@ -0,0 +1,67 @@
import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { encodePrettyJsonEffect, getSchemaDescription, toJsonSchemaObject } from "./schemaJson";
it.effect("encodePrettyJsonEffect writes indented JSON", () =>
Effect.gen(function* () {
const encodePrettyJson = encodePrettyJsonEffect(
Schema.Struct({
provider: Schema.String,
options: Schema.Struct({
enabled: Schema.Boolean,
}),
}),
);
const encoded = yield* encodePrettyJson({
provider: "codex",
options: {
enabled: true,
},
});
assert.strictEqual(
encoded,
`{
"provider": "codex",
"options": {
"enabled": true
}
}`,
);
}),
);
it.effect("toJsonSchemaObject hoists descriptions from wrapper nodes", () =>
Effect.sync(() => {
const schema = toJsonSchemaObject(
Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the feature is enabled.",
}).pipe(Schema.withDecodingDefault(() => false)),
name: Schema.String.annotate({
description: "Human-readable display name.",
}).check(Schema.isMinLength(1)),
}),
) as Record<string, unknown>;
const properties = schema.properties as Record<string, Record<string, unknown>>;
const enabled = properties.enabled;
const name = properties.name;
assert.isDefined(enabled);
assert.isDefined(name);
assert.strictEqual(enabled.description, "Whether the feature is enabled.");
assert.strictEqual(name.description, "Human-readable display name.");
}),
);
it.effect("getSchemaDescription reads hoisted descriptions from wrapped schemas", () =>
Effect.sync(() => {
const enabled = Schema.Boolean.annotate({
description: "Whether the feature is enabled.",
}).pipe(Schema.withDecodingDefault(() => false));
assert.strictEqual(getSchemaDescription(enabled), "Whether the feature is enabled.");
}),
);
+82
View File
@@ -36,6 +36,22 @@ export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown,
};
};
const schemaDescriptionCache = new WeakMap<object, string | undefined>();
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
export const encodePrettyJsonEffect = <S extends Schema.Top>(schema: S) =>
Schema.encodeEffect(
Schema.fromJsonString(schema).pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
),
);
export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
const squashed = Cause.squash(cause);
return Schema.isSchemaError(squashed)
@@ -43,6 +59,72 @@ export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
: Cause.pretty(cause);
};
function hoistJsonSchemaDescriptions(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(hoistJsonSchemaDescriptions);
}
if (!value || typeof value !== "object") {
return value;
}
const record = Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, hoistJsonSchemaDescriptions(entry)]),
) as Record<string, unknown>;
if (typeof record.description !== "string") {
const candidates = ["allOf", "anyOf", "oneOf"]
.flatMap((key) => (Array.isArray(record[key]) ? (record[key] as ReadonlyArray<unknown>) : []))
.filter((candidate): candidate is Record<string, unknown> => {
return !!candidate && typeof candidate === "object" && !Array.isArray(candidate);
});
const description = candidates.find(
(candidate) =>
typeof candidate.description === "string" &&
!(candidate.type === "null" && Object.keys(candidate).length <= 1),
)?.description;
if (typeof description === "string") {
record.description = description;
}
}
return record;
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export const toJsonSchemaObject = (schema: Schema.Top): unknown => {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return hoistJsonSchemaDescriptions({ ...document.schema, $defs: document.definitions });
}
return hoistJsonSchemaDescriptions(document.schema);
};
export const getSchemaDescription = (schema: Schema.Top): string | undefined => {
if (schema && typeof schema === "object") {
const cached = schemaDescriptionCache.get(schema);
if (cached !== undefined || schemaDescriptionCache.has(schema)) {
return cached;
}
}
const jsonSchema = toJsonSchemaObject(schema);
const description =
jsonSchema && typeof jsonSchema === "object" && !Array.isArray(jsonSchema)
? typeof (jsonSchema as Record<string, unknown>).description === "string"
? ((jsonSchema as Record<string, unknown>).description as string)
: undefined
: undefined;
if (schema && typeof schema === "object") {
schemaDescriptionCache.set(schema, description);
}
return description;
};
/**
* A `Getter` that parses a lenient JSON string (tolerating trailing commas
* and JS-style comments) into an unknown value.
+19
View File
@@ -0,0 +1,19 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
writeKeybindingsJsonSchemas,
} from "./lib/keybindings-schema.ts";
import {
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
writeServerSettingsJsonSchemas,
} from "./lib/server-settings-schema.ts";
const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
writeServerSettingsJsonSchemas({ rootDir });
writeKeybindingsJsonSchemas({ rootDir });
console.log(`Wrote ${SERVER_SETTINGS_SCHEMA_RELATIVE_PATH}`);
console.log(`Wrote ${KEYBINDINGS_SCHEMA_RELATIVE_PATH}`);
+76
View File
@@ -0,0 +1,76 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { type Schema } from "effect";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
const JSON_SCHEMA_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";
export function buildJsonSchemaDocument(
schema: Schema.Top,
options: {
readonly title: string;
readonly description: string;
},
): Record<string, unknown> {
const jsonSchema = toJsonSchemaObject(schema);
if (!jsonSchema || typeof jsonSchema !== "object" || Array.isArray(jsonSchema)) {
throw new Error(
`${options.title} JSON schema must be an object or array JSON schema document.`,
);
}
return {
$schema: JSON_SCHEMA_DRAFT_2020_12,
title: options.title,
description: options.description,
...jsonSchema,
};
}
function writeJsonFileIfChanged(filePath: string, document: Record<string, unknown>): boolean {
const nextContent = `${JSON.stringify(document, null, 2)}\n`;
const previousContent = (() => {
try {
return readFileSync(filePath, "utf8");
} catch {
return null;
}
})();
if (previousContent === nextContent) {
return false;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, nextContent);
return true;
}
export function writeJsonSchemaArtifacts(options: {
readonly rootDir?: string;
readonly version?: string;
readonly latestRelativePath: string;
readonly getVersionedRelativePath: (version: string) => string;
readonly document: Record<string, unknown>;
}): {
readonly changed: boolean;
} {
const rootDir = resolve(options.rootDir ?? process.cwd());
const latestChanged = writeJsonFileIfChanged(
resolve(rootDir, options.latestRelativePath),
options.document,
);
let changed = latestChanged;
if (options.version && latestChanged) {
changed =
writeJsonFileIfChanged(
resolve(rootDir, options.getVersionedRelativePath(options.version)),
options.document,
) || changed;
}
return { changed };
}
+75
View File
@@ -0,0 +1,75 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { describe, expect, it } from "vitest";
import {
buildKeybindingsJsonSchema,
getVersionedKeybindingsSchemaRelativePath,
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
writeKeybindingsJsonSchemas,
} from "./keybindings-schema";
describe("buildKeybindingsJsonSchema", () => {
it("builds a JSON schema document for keybindings.json", () => {
const schema = buildKeybindingsJsonSchema();
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
expect(schema.title).toBe("T3 Code Keybindings");
expect(schema.type).toBe("array");
expect(schema.items).toMatchObject({
description: expect.stringContaining("keybinding rule"),
type: "object",
properties: {
key: {
description: expect.stringContaining("shortcut"),
},
command: {
description: expect.stringContaining("execute"),
},
when: {
description: expect.stringContaining("active"),
},
},
});
});
it("writes latest and versioned schema files", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
try {
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(true);
const latestSchema = JSON.parse(
readFileSync(resolve(rootDir, KEYBINDINGS_SCHEMA_RELATIVE_PATH), "utf8"),
) as Record<string, unknown>;
const versionedSchema = JSON.parse(
readFileSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")), "utf8"),
) as Record<string, unknown>;
expect(latestSchema).toEqual(versionedSchema);
expect(latestSchema.title).toBe("T3 Code Keybindings");
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
try {
const latestOnly = writeKeybindingsJsonSchemas({ rootDir });
expect(latestOnly.changed).toBe(true);
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(false);
expect(existsSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")))).toBe(
false,
);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+31
View File
@@ -0,0 +1,31 @@
import { KeybindingsConfig } from "@t3tools/contracts";
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
export const KEYBINDINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/keybindings.json";
export const KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/keybindings";
export const getVersionedKeybindingsSchemaRelativePath = (version: string) =>
`${KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildKeybindingsJsonSchema(): Record<string, unknown> {
return buildJsonSchemaDocument(KeybindingsConfig, {
title: "T3 Code Keybindings",
description: "JSON Schema for the keybindings.json file consumed by T3 Code.",
});
}
export function writeKeybindingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: KEYBINDINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedKeybindingsSchemaRelativePath,
document: buildKeybindingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
@@ -0,0 +1,82 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { describe, expect, it } from "vitest";
import {
buildServerSettingsJsonSchema,
getVersionedServerSettingsSchemaRelativePath,
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
writeServerSettingsJsonSchemas,
} from "./server-settings-schema";
describe("buildServerSettingsJsonSchema", () => {
it("builds a JSON schema document for settings.json", () => {
const schema = buildServerSettingsJsonSchema();
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
expect(schema.title).toBe("T3 Code Server Settings");
expect(schema.type).toBe("object");
expect(schema.additionalProperties).toBe(false);
expect(schema.properties).toMatchObject({
$schema: {
type: "string",
},
enableAssistantStreaming: {
description: "Show token-by-token output while a response is in progress.",
},
defaultThreadEnvMode: {
description: "Pick the default workspace mode for newly created draft threads.",
},
textGenerationModelSelection: {
description:
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
},
providers: {
description: expect.stringContaining("Provider-specific"),
},
});
});
it("writes latest and versioned schema files", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
try {
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(true);
const latestSchema = JSON.parse(
readFileSync(resolve(rootDir, SERVER_SETTINGS_SCHEMA_RELATIVE_PATH), "utf8"),
) as Record<string, unknown>;
const versionedSchema = JSON.parse(
readFileSync(
resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3")),
"utf8",
),
) as Record<string, unknown>;
expect(latestSchema).toEqual(versionedSchema);
expect(latestSchema.title).toBe("T3 Code Server Settings");
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
try {
const latestOnly = writeServerSettingsJsonSchemas({ rootDir });
expect(latestOnly.changed).toBe(true);
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(false);
expect(
existsSync(resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3"))),
).toBe(false);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+55
View File
@@ -0,0 +1,55 @@
import { ServerSettings } from "@t3tools/contracts/settings";
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
export const SERVER_SETTINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/settings.json";
export const SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/settings";
export const getVersionedServerSettingsSchemaRelativePath = (version: string) =>
`${SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildServerSettingsJsonSchema(): Record<string, unknown> {
const schema = buildJsonSchemaDocument(ServerSettings, {
title: "T3 Code Server Settings",
description: "JSON Schema for the server-authoritative settings.json file consumed by T3 Code.",
});
const properties =
schema.type === "object" &&
schema.properties &&
typeof schema.properties === "object" &&
!Array.isArray(schema.properties)
? schema.properties
: null;
if (!properties) {
throw new Error("ServerSettings JSON schema must expose object properties.");
}
return {
...schema,
properties: {
$schema: {
type: "string",
description:
"Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL.",
},
...properties,
},
};
}
export function writeServerSettingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedServerSettingsSchemaRelativePath,
document: buildServerSettingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
+56 -2
View File
@@ -1,5 +1,13 @@
import { execFileSync } from "node:child_process";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -81,7 +89,7 @@ try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
process.execPath,
"bun",
[
resolve(repoRoot, "scripts/update-release-package-versions.ts"),
"9.9.9-smoke.0",
@@ -106,6 +114,52 @@ try {
"Expected bun.lock to contain the smoke version.",
);
const latestSchemaPath = resolve(tempRoot, "apps/marketing/public/schemas/settings.json");
const versionedSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/settings/9.9.9-smoke.0.json",
);
const latestKeybindingsSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/keybindings.json",
);
const versionedKeybindingsSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/keybindings/9.9.9-smoke.0.json",
);
if (!existsSync(latestSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the latest server settings schema.",
);
}
if (!existsSync(versionedSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the versioned server settings schema.",
);
}
if (!existsSync(latestKeybindingsSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the latest keybindings schema.",
);
}
if (!existsSync(versionedKeybindingsSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the versioned keybindings schema.",
);
}
const versionedSchema = readFileSync(versionedSchemaPath, "utf8");
assertContains(
versionedSchema,
'"title": "T3 Code Server Settings"',
"Expected versioned server settings schema to contain schema metadata.",
);
const versionedKeybindingsSchema = readFileSync(versionedKeybindingsSchemaPath, "utf8");
assertContains(
versionedKeybindingsSchema,
'"title": "T3 Code Keybindings"',
"Expected versioned keybindings schema to contain schema metadata.",
);
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
execFileSync(
process.execPath,
@@ -0,0 +1,101 @@
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { describe, expect, it } from "vitest";
import {
releasePackageFiles,
updateReleasePackageVersions,
} from "./update-release-package-versions";
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema";
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema";
describe("updateReleasePackageVersions", () => {
it("updates package versions and writes latest plus versioned config schemas", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
try {
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(
filePath,
`${JSON.stringify({ name: relativePath, version: "0.0.0" }, null, 2)}\n`,
);
}
const result = updateReleasePackageVersions("1.2.3", { rootDir });
expect(result.changed).toBe(true);
for (const relativePath of releasePackageFiles) {
const packageJson = JSON.parse(readFileSync(resolve(rootDir, relativePath), "utf8")) as {
version?: string;
};
expect(packageJson.version).toBe("1.2.3");
}
expect(
JSON.parse(
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/settings.json"), "utf8"),
),
).toMatchObject({ title: "T3 Code Server Settings" });
expect(
JSON.parse(
readFileSync(
resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json"),
"utf8",
),
),
).toMatchObject({ title: "T3 Code Server Settings" });
expect(
JSON.parse(
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings.json"), "utf8"),
),
).toMatchObject({ title: "T3 Code Keybindings" });
expect(
JSON.parse(
readFileSync(
resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json"),
"utf8",
),
),
).toMatchObject({ title: "T3 Code Keybindings" });
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips versioned schema snapshots when the latest schemas are unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
try {
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(
filePath,
`${JSON.stringify({ name: relativePath, version: "1.2.3" }, null, 2)}\n`,
);
}
writeServerSettingsJsonSchemas({ rootDir });
writeKeybindingsJsonSchemas({ rootDir });
const result = updateReleasePackageVersions("1.2.3", { rootDir });
expect(result.changed).toBe(false);
expect(
existsSync(resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json")),
).toBe(false);
expect(
existsSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json")),
).toBe(false);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+7 -1
View File
@@ -2,6 +2,9 @@ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema.ts";
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema.ts";
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
@@ -37,6 +40,9 @@ export function updateReleasePackageVersions(
changed = true;
}
changed = writeServerSettingsJsonSchemas({ rootDir, version }).changed || changed;
changed = writeKeybindingsJsonSchemas({ rootDir, version }).changed || changed;
return { changed };
}
@@ -99,7 +105,7 @@ if (isMain) {
);
if (!changed) {
console.log("All package.json versions already match release version.");
console.log("All release version artifacts already match the requested version.");
}
if (writeGithubOutput) {