Compare commits

...
Author SHA1 Message Date
Cursor Agent 1b6e8ab339 Fix makeTrimmedStringSetting to actually trim whitespace
The passthrough() transformation was an identity function that bypassed
TrimmedString's whitespace-trimming decode logic. This meant whitespace-only
inputs like " " would not be trimmed to empty and would not trigger the
fallback in makeBinaryPathSetting.

Fix by using TrimmedString directly (which is Schema.Trim and actively trims
on decode) instead of piping Schema.String through a passthrough to
TrimmedString.
2026-03-30 22:43:57 +00: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 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
Julius Marminge 59f23d7bfd Show archive action on hover with confirm focus (#1561) 2026-03-29 18:36:53 -07:00
Naufal PutraandJulius Marminge 4a4795e5f0 Scroll active item into view in composer menu (#1557)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:33:47 +00:00
Efroim-PropelandJulius Marminge 5b58f74e9a fix(desktop): default confirm dialog selection to "No" (#1400)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-29 18:20:56 -07:00
Julius Marmingeandcodex 32dca3b76b [codex] debounce thread jump hint pills (#1526)
Co-authored-by: codex <[email protected]>
2026-03-29 18:19:37 -07:00
Abdulelah Hajjar 6358444900 fix(web): Fix duplicate highlight in composer slash command menu (#1445) 2026-03-29 18:14:59 -07:00
Alexander VostresandJulius Marminge 792ad4b5c1 Fix model settings getting stuck (#1538)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:13:16 +00:00
Craig d41781987c fix(web): preserve scroll when collapsing large changed-files trees (#1113) 2026-03-29 17:53:21 -07:00
shivamandEwan fc6507066e fix(windows): hover-effect-fix-in-the-branch-ui (#1559)
Co-authored-by: Ewan <[email protected]>
2026-03-29 17:53:03 -07:00
bf9c828aef Make provider model lists dynamic based on auth context (#1556)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-29 17:51:05 -07:00
shivam 7b676b76de fix: show empty project thread state in sidebar (#1546) 2026-03-29 11:47:51 -07:00
Julius Marminge d5f2333173 Show hidden thread status in sidebar (#1517) 2026-03-29 11:47:17 -07:00
Alexander Vostres 40e7dbdae9 Fix for broken Codex model selection for 'Text Generation Model' (#1543) 2026-03-29 11:27:20 -07:00
94 changed files with 10079 additions and 3065 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
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
@@ -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": "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
}
@@ -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
}
+25 -2
View File
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("keeps spark enabled for api key accounts", () => {
it("disables spark for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
});
});
});
@@ -343,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
+10 -94
View File
@@ -26,6 +26,15 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -96,23 +105,6 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -162,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
killCodexChildProcess(child);
}
export function normalizeCodexModelSlug(
@@ -402,19 +331,6 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
@@ -13,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,10 +28,10 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -84,8 +85,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptions(
modelSelection.model,
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
@@ -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,10 +27,10 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -156,8 +157,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptions(
modelSelection.model,
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
-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)),
+436 -174
View File
@@ -1,15 +1,15 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import {
buildServerProvider,
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -96,28 +96,9 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getClaudeModelCapabilities(model);
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -129,7 +110,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
@@ -144,7 +125,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
@@ -165,37 +146,286 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
// ── Dynamic model capability adjustment ─────────────────────────────
/** Subscription types where the 1M context window is included in the plan. */
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
"max",
"maxplan",
"max5",
"max20",
"enterprise",
"team",
]);
function toTitleCaseWords(value: string): string {
return value
.split(/[\s_-]+/g)
.filter(Boolean)
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
.join(" ");
}
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
switch (normalized) {
case "max":
case "maxplan":
case "max5":
case "max20":
return "Max";
case "enterprise":
return "Enterprise";
case "team":
return "Team";
case "pro":
return "Pro";
case "free":
return "Free";
default:
return toTitleCaseWords(subscriptionType!);
}
}
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
if (normalized === "apikey") return "apiKey";
return undefined;
}
function claudeAuthMetadata(input: {
readonly subscriptionType: string | undefined;
readonly authMethod: string | undefined;
}): { readonly type: string; readonly label: string } | undefined {
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
return {
type: "apiKey",
label: "Claude API Key",
};
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
};
}
return undefined;
}
/**
* Adjust the built-in model list based on the user's detected subscription.
*
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
* - Other tiers (Pro, free, unknown): 200k context stays the default;
* 1M remains available as a manual option so users can still enable it.
*/
export function adjustModelsForSubscription(
baseModels: ReadonlyArray<ServerProviderModel>,
subscriptionType: string | undefined,
): ReadonlyArray<ServerProviderModel> {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
return baseModels;
}
// Flip 1M to be the default for premium users
return baseModels.map((model) => {
const caps = model.capabilities;
if (!caps || caps.contextWindowOptions.length === 0) return model;
return {
...model,
capabilities: {
...caps,
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
opt.value === "1m"
? { value: opt.value, label: opt.label, isDefault: true as const }
: { value: opt.value, label: opt.label },
),
},
};
});
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
*
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
prompt: ".",
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: [],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return { subscriptionType: init.account?.subscriptionType };
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (!abort.signal.aborted) abort.abort();
}),
),
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
};
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
@@ -208,144 +438,81 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Claude is disabled in T3 Code settings.",
},
});
}
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
@@ -354,13 +521,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
status: "error",
auth: { status: "unknown" },
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
},
);
}
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
@@ -368,7 +621,16 @@ export const ClaudeProviderLive = Layer.effect(
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkClaudeProviderStatus().pipe(
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) =>
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
});
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
+242 -202
View File
@@ -1,16 +1,25 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -29,6 +38,13 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount";
import { probeCodexAccount } from "../codexAppServer";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
@@ -152,25 +168,9 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
);
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const caps = getCodexModelCapabilities(model);
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
@@ -196,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
@@ -217,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
@@ -290,6 +290,21 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.orElseSucceed(() => false),
);
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
const probeCodexCapabilities = (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) =>
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
@@ -306,179 +321,88 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Codex is disabled in T3 Code settings.",
},
});
}
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
@@ -487,13 +411,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
},
);
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
auth: { status: "unknown" },
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const account = resolveAccount
? yield* resolveAccount({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
})
: undefined;
const resolvedModels = adjustCodexModelsForAccount(models, account);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const authType = codexAuthSubType(account);
const authLabel = codexAuthSubLabel(account);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
export const CodexProviderLive = Layer.effect(
CodexProvider,
@@ -502,8 +529,21 @@ export const CodexProviderLive = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: string) => {
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
return probeCodexCapabilities({
binaryPath,
...(homePath ? { homePath } : {}),
});
},
});
const checkProvider = checkCodexProviderStatus().pipe(
const checkProvider = checkCodexProviderStatus((input) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -173,7 +173,133 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "pro" as const,
sparkEnabled: true,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "pro");
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
true,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "plus" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "plus");
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "team" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.auth.type, "team");
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for codex api key auth", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "apiKey" as const,
planType: null,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "OpenAI API Key");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -235,7 +361,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
} finally {
process.env.PATH = previousPath;
}
@@ -249,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
@@ -264,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
@@ -287,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -313,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -338,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
@@ -366,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "ready",
enabled: true,
installed: true,
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -376,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "warning",
enabled: true,
installed: true,
authStatus: "unknown",
auth: { status: "unknown" },
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -494,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
@@ -537,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
const status = yield* checkCodexProviderStatus();
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -558,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
@@ -568,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
assert.strictEqual(parsed.auth.status, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -578,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
assert.strictEqual(parsed.auth.status, "unknown");
});
});
@@ -715,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -733,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "maxplan");
assert.strictEqual(status.auth.label, "Claude Max Subscription");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for claude api key auth", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "Claude API Key");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
@@ -771,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
@@ -799,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -819,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
@@ -844,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
@@ -854,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
@@ -864,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
assert.strictEqual(parsed.auth.status, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -874,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
assert.strictEqual(parsed.auth.status, "unknown");
});
});
},
+123
View File
@@ -0,0 +1,123 @@
import type { ServerProviderModel } from "@t3tools/contracts";
export type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
export interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: false,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
if (account?.type === "apiKey") {
return "apiKey";
}
if (account?.type !== "chatgpt") {
return undefined;
}
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
}
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
switch (codexAuthSubType(account)) {
case "apiKey":
return "OpenAI API Key";
case "chatgpt":
return "ChatGPT Subscription";
case "free":
return "ChatGPT Free Subscription";
case "go":
return "ChatGPT Go Subscription";
case "plus":
return "ChatGPT Plus Subscription";
case "pro":
return "ChatGPT Pro Subscription";
case "team":
return "ChatGPT Team Subscription";
case "business":
return "ChatGPT Business Subscription";
case "enterprise":
return "ChatGPT Enterprise Subscription";
case "edu":
return "ChatGPT Edu Subscription";
default:
return undefined;
}
}
export function adjustCodexModelsForAccount(
baseModels: ReadonlyArray<ServerProviderModel>,
account: CodexAccountSnapshot | undefined,
): ReadonlyArray<ServerProviderModel> {
if (account?.sparkEnabled !== false) {
return baseModels;
}
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
+154
View File
@@ -0,0 +1,154 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
interface JsonRpcProbeResponse {
readonly id?: unknown;
readonly result?: unknown;
readonly error?: {
readonly message?: unknown;
};
}
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
return typeof response.error?.message === "string" ? response.error.message : undefined;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill();
}
export async function probeCodexAccount(input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly signal?: AbortSignal;
}): Promise<CodexAccountSnapshot> {
return await new Promise((resolve, reject) => {
const child = spawn(input.binaryPath, ["app-server"], {
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
let completed = false;
const cleanup = () => {
output.removeAllListeners();
output.close();
child.removeAllListeners();
if (!child.killed) {
killCodexChildProcess(child);
}
};
const finish = (callback: () => void) => {
if (completed) return;
completed = true;
cleanup();
callback();
};
const fail = (error: unknown) =>
finish(() =>
reject(
error instanceof Error
? error
: new Error(`Codex account probe failed: ${String(error)}.`),
),
);
if (input.signal?.aborted) {
fail(new Error("Codex account probe aborted."));
return;
}
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
const writeMessage = (message: unknown) => {
if (!child.stdin.writable) {
fail(new Error("Cannot write to codex app-server stdin."));
return;
}
child.stdin.write(`${JSON.stringify(message)}\n`);
};
output.on("line", (line) => {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
fail(new Error("Received invalid JSON from codex app-server during account probe."));
return;
}
if (!parsed || typeof parsed !== "object") {
return;
}
const response = parsed as JsonRpcProbeResponse;
if (response.id === 1) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`initialize failed: ${errorMessage}`));
return;
}
writeMessage({ method: "initialized" });
writeMessage({ id: 2, method: "account/read", params: {} });
return;
}
if (response.id === 2) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`account/read failed: ${errorMessage}`));
return;
}
finish(() => resolve(readCodexAccountSnapshot(response.result)));
}
});
child.once("error", fail);
child.once("exit", (code, signal) => {
if (completed) return;
fail(
new Error(
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
),
);
});
writeMessage({
id: 1,
method: "initialize",
params: buildCodexInitializeParams(),
});
});
}
+3 -3
View File
@@ -1,6 +1,6 @@
import type {
ServerProvider,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderModel,
ServerProviderState,
} from "@t3tools/contracts";
@@ -21,7 +21,7 @@ export interface ProviderProbeResult {
readonly installed: boolean;
readonly version: string | null;
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: ServerProviderAuth;
readonly message?: string;
}
@@ -137,7 +137,7 @@ export function buildServerProvider(input: {
installed: input.probe.installed,
version: input.probe.version,
status: input.enabled ? input.probe.status : "disabled",
authStatus: input.probe.authStatus,
auth: input.probe.auth,
checkedAt: input.checkedAt,
...(input.probe.message ? { message: input.probe.message } : {}),
models: input.models,
+83
View File
@@ -104,6 +104,43 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
// Start with Claude text generation selection
yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "high",
},
},
});
// Switch to Codex — the stale Claude "effort" in options must not
// cause the update to lose the selected model.
const next = yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
},
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims provider path settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -179,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())),
);
});
+45 -6
View File
@@ -27,6 +27,7 @@ import {
FileSystem,
Layer,
Path,
Equal,
PubSub,
Ref,
Schema,
@@ -38,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",
@@ -100,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"];
@@ -130,9 +134,12 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings
};
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
return Equal.equals(current, defaults) ? undefined : current;
}
if (
@@ -146,9 +153,15 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
if (ATOMIC_SETTINGS_KEYS.has(key)) {
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
next[key] = currentRecord[key];
}
} else {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
}
}
@@ -167,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));
@@ -197,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", {
@@ -222,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>;
}
/**
+22 -15
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";
@@ -74,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
@@ -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(
@@ -397,7 +397,6 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
style={style}
onClick={() => selectBranch(branch)}
>
+183 -16
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 {
@@ -117,7 +122,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: NOW_ISO,
models: [],
},
@@ -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,
});
});
@@ -1041,6 +1121,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
);
it("shows an explicit empty state for projects without threads in the sidebar", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
});
try {
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd for draft threads without a worktree path", async () => {
setDraftThreadWithoutWorktree();
@@ -1760,6 +1853,87 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("hides the archive action when the pointer leaves a thread row", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-hover-test" as MessageId,
targetText: "archive hover target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
const archiveButton = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
"Unable to find archive button.",
);
const archiveAction = archiveButton.parentElement;
expect(
archiveAction,
"Archive button should render inside a visibility wrapper.",
).not.toBeNull();
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
await threadRow.hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("1");
},
{ timeout: 4_000, interval: 16 },
);
await page.getByTestId("composer-editor").hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
},
{ timeout: 4_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("shows the confirm archive action after clicking the archive button", async () => {
localStorage.setItem(
"t3code:client-settings:v1",
JSON.stringify({
...DEFAULT_CLIENT_SETTINGS,
confirmThreadArchive: true,
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-confirm-test" as MessageId,
targetText: "archive confirm target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
await threadRow.hover();
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
await expect.element(archiveButton).toBeInTheDocument();
await archiveButton.click();
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
await expect.element(confirmButton).toBeInTheDocument();
await expect.element(confirmButton).toBeVisible();
} finally {
localStorage.removeItem("t3code:client-settings:v1");
await mounted.cleanup();
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1787,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.
@@ -2123,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 -5
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: [],
@@ -75,8 +75,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
@@ -161,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)
);
}
+227 -119
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,14 +176,18 @@ import {
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
SendPhase,
threadHasStarted,
waitForStartedServerThread,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -190,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;
@@ -245,13 +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 threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
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,8 +485,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
@@ -466,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(
() =>
@@ -495,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) => {
@@ -595,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;
@@ -664,15 +824,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
sendStartedAt,
);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -735,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),
@@ -752,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 ||
@@ -980,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 },
@@ -1230,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;
}
@@ -1244,7 +1390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[setStoreThreadError, threads],
[setStoreThreadError],
);
const focusComposer = useCallback(() => {
@@ -1411,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,
@@ -2020,15 +2166,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
setSendPhase("idle");
setSendStartedAt(null);
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;
@@ -2161,37 +2306,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
}, [phase]);
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
setSendStartedAt((current) => current ?? new Date().toISOString());
setSendPhase(nextPhase);
}, []);
const resetSendPhase = useCallback(() => {
setSendPhase("idle");
setSendStartedAt(null);
}, []);
useEffect(() => {
if (sendPhase === "idle") {
return;
}
if (
phase === "running" ||
activePendingApproval !== null ||
activePendingUserInput !== null ||
activeThread?.error
) {
resetSendPhase();
}
}, [
activePendingApproval,
activePendingUserInput,
activeThread?.error,
phase,
resetSendPhase,
sendPhase,
]);
useEffect(() => {
if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
@@ -2529,7 +2643,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
sendInFlightRef.current = true;
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2603,7 +2717,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginSendPhase("preparing-worktree");
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2715,7 +2829,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginSendPhase("sending-turn");
beginLocalDispatch({ preparingWorktree: false });
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2772,7 +2886,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetSendPhase();
resetLocalDispatch();
}
};
@@ -2971,7 +3085,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginSendPhase("sending-turn");
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -3040,19 +3154,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetSendPhase();
resetLocalDispatch();
}
},
[
activeThread,
activeProposedPlan,
beginSendPhase,
beginLocalDispatch,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetSendPhase,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
@@ -3094,10 +3208,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginSendPhase("sending-turn");
beginLocalDispatch({ preparingWorktree: false });
const finish = () => {
sendInFlightRef.current = false;
resetSendPhase();
resetLocalDispatch();
};
await api.orchestration
@@ -3132,9 +3246,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt,
});
})
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
.then(() => {
return waitForStartedServerThread(nextThreadId);
})
.then(() => {
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
@@ -3150,12 +3265,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
@@ -3168,18 +3277,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject,
activeProposedPlan,
activeThread,
beginSendPhase,
beginLocalDispatch,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetSendPhase,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
syncServerReadModel,
selectedModel,
]);
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: NOW_ISO,
models: [],
},
@@ -323,7 +323,7 @@ describe("Keybindings update toast", () => {
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
bootstrapComplete: false,
});
});
+137 -4
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
createThreadJumpHintVisibilityController,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -8,6 +9,7 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -15,8 +17,9 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
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,
@@ -27,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",
@@ -52,6 +55,68 @@ describe("hasUnseenCompletion", () => {
});
});
describe("createThreadJumpHintVisibilityController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delays showing jump hints until the configured delay elapses", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
expect(visibilityChanges).toEqual([]);
vi.advanceTimersByTime(1);
expect(visibilityChanges).toEqual([true]);
});
it("hides immediately when the modifiers are released", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
controller.sync(false);
expect(visibilityChanges).toEqual([true, false]);
});
it("cancels a pending reveal when the modifier is released early", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
controller.sync(false);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
expect(visibilityChanges).toEqual([]);
});
});
describe("shouldClearThreadSelectionOnMouseDown", () => {
it("preserves selection for thread items", () => {
const child = {
@@ -99,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 = [
@@ -171,6 +280,27 @@ describe("getVisibleSidebarThreadIds", () => {
ThreadId.makeUnsafe("thread-6"),
]);
});
it("skips threads from collapsed projects whose thread panels are not shown", () => {
expect(
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
});
});
describe("isContextMenuPointerDown", () => {
@@ -429,6 +559,9 @@ describe("getVisibleThreadsForProject", () => {
ThreadId.makeUnsafe("thread-6"),
ThreadId.makeUnsafe("thread-8"),
]);
expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-7"),
]);
});
it("returns all threads when the list is expanded", () => {
@@ -449,6 +582,7 @@ describe("getVisibleThreadsForProject", () => {
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
expect(result.hiddenThreads).toEqual([]);
});
});
@@ -463,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: [],
+147 -12
View File
@@ -1,3 +1,4 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
@@ -8,6 +9,7 @@ import {
} from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
@@ -15,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";
@@ -43,8 +48,95 @@ 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;
dispose: () => void;
}
export function createThreadJumpHintVisibilityController(input: {
delayMs: number;
onVisibilityChange: (visible: boolean) => void;
setTimeoutFn?: typeof globalThis.setTimeout;
clearTimeoutFn?: typeof globalThis.clearTimeout;
}): ThreadJumpHintVisibilityController {
const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
let isVisible = false;
let timeoutId: NodeJS.Timeout | null = null;
const clearPendingShow = () => {
if (timeoutId === null) {
return;
}
clearTimeoutFn(timeoutId);
timeoutId = null;
};
return {
sync: (shouldShow) => {
if (!shouldShow) {
clearPendingShow();
if (isVisible) {
isVisible = false;
input.onVisibilityChange(false);
}
return;
}
if (isVisible || timeoutId !== null) {
return;
}
timeoutId = setTimeoutFn(() => {
timeoutId = null;
isVisible = true;
input.onVisibilityChange(true);
}, input.delayMs);
},
dispose: () => {
clearPendingShow();
},
};
}
export function useThreadJumpHintVisibility(): {
showThreadJumpHints: boolean;
updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
} {
const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
React.useEffect(() => {
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
setShowThreadJumpHints(visible);
},
setTimeoutFn: window.setTimeout.bind(window),
clearTimeoutFn: window.clearTimeout.bind(window),
});
controllerRef.current = controller;
return () => {
controller.dispose();
controllerRef.current = null;
};
}, []);
const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
controllerRef.current?.sync(shouldShow);
}, []);
return {
showThreadJumpHints,
updateThreadJumpHintsVisibility,
};
}
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -69,15 +161,46 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
getId: (item: TItem) => TId;
}): TItem[] {
const { getId, items, preferredIds } = input;
if (preferredIds.length === 0) {
return [...items];
}
const itemsById = new Map(items.map((item) => [getId(item), item] as const));
const preferredIdSet = new Set(preferredIds);
const emittedPreferredIds = new Set<TId>();
const ordered = preferredIds.flatMap((id) => {
if (emittedPreferredIds.has(id)) {
return [];
}
const item = itemsById.get(id);
if (!item) {
return [];
}
emittedPreferredIds.add(id);
return [item];
});
const remaining = items.filter((item) => !preferredIdSet.has(getId(item)));
return [...ordered, ...remaining];
}
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
);
}
@@ -237,14 +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;
visibleThreads: Thread[];
visibleThreads: T[];
hiddenThreads: T[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
@@ -252,6 +376,7 @@ export function getVisibleThreadsForProject(input: {
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
hiddenThreads: [],
visibleThreads: [...threads],
};
}
@@ -260,6 +385,7 @@ export function getVisibleThreadsForProject(input: {
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -268,6 +394,7 @@ export function getVisibleThreadsForProject(input: {
if (!activeThread) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -276,6 +403,7 @@ export function getVisibleThreadsForProject(input: {
return {
hasHiddenThreads: true,
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
@@ -287,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;
@@ -317,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);
@@ -330,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"];
@@ -374,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,
+310 -138
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,
@@ -69,6 +71,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useThreadActions } from "../hooks/useThreadActions";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
@@ -113,13 +116,16 @@ import {
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
useThreadJumpHintVisibility,
} from "./Sidebar.logic";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import type { Project, Thread } from "../types";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -136,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;
@@ -151,6 +231,44 @@ interface PrStatusIndicator {
type ThreadPr = GitStatusResult["pr"];
function ThreadStatusLabel({
status,
compact = false,
}: {
status: NonNullable<ReturnType<typeof resolveThreadStatusPill>>;
compact?: boolean;
}) {
if (compact) {
return (
<span
title={status.label}
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="sr-only">{status.label}</span>
</span>
);
}
return (
<span
title={status.label}
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
</span>
);
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
@@ -321,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,
@@ -356,14 +481,14 @@ export default function Sidebar() {
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [hoveredThreadId, setHoveredThreadId] = useState<ThreadId | null>(null);
const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState<ThreadId | null>(null);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
const [showThreadJumpHints, setShowThreadJumpHints] = useState(false);
const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<ThreadId, HTMLButtonElement>());
const dragInProgressRef = useRef(false);
const suppressProjectClickAfterDragRef = useRef(false);
const suppressProjectClickForContextMenuRef = useRef(false);
@@ -378,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],
@@ -712,7 +859,7 @@ export default function Sidebar() {
}
if (clicked === "mark-unread") {
markThreadUnread(threadId);
markThreadUnread(threadId, thread.latestTurn?.completedAt);
return;
}
if (clicked === "copy-path") {
@@ -774,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;
@@ -805,6 +953,7 @@ export default function Sidebar() {
markThreadUnread,
removeFromSelection,
selectedThreadIds,
threads,
],
);
@@ -947,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(
@@ -1012,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(
@@ -1023,14 +1173,18 @@ export default function Sidebar() {
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) =>
const threadStatuses = new Map(
projectThreads.map((thread) => [
thread.id,
resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
}),
),
]),
);
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const activeThreadId = routeThreadId ?? undefined;
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
@@ -1039,25 +1193,35 @@ export default function Sidebar() {
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const { hasHiddenThreads, visibleThreads: visibleProjectThreads } =
getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const {
hasHiddenThreads,
hiddenThreads,
visibleThreads: visibleProjectThreads,
} = getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const hiddenThreadStatus = resolveProjectStatusIndicator(
hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = pinnedCollapsedThread
? [pinnedCollapsedThread]
: visibleProjectThreads;
const showEmptyThreadState = project.expanded && projectThreads.length === 0;
return {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
};
@@ -1070,23 +1234,22 @@ export default function Sidebar() {
visibleThreads,
],
);
const visibleSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const threadJumpCommandById = useMemo(() => {
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
let visibleThreadIndex = 0;
for (const renderedProject of renderedProjects) {
for (const thread of renderedProject.renderedThreads) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(thread.id, jumpCommand);
visibleThreadIndex += 1;
for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(threadId, jumpCommand);
}
return mapping;
}, [renderedProjects]);
}, [visibleSidebarThreadIds]);
const threadJumpThreadIds = useMemo(
() => [...threadJumpCommandById.keys()],
[threadJumpCommandById],
@@ -1101,10 +1264,7 @@ export default function Sidebar() {
}
return mapping;
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
const orderedSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const orderedSidebarThreadIds = visibleSidebarThreadIds;
useEffect(() => {
const getShortcutContext = () => ({
@@ -1113,7 +1273,7 @@ export default function Sidebar() {
});
const onWindowKeyDown = (event: KeyboardEvent) => {
setShowThreadJumpHints(
updateThreadJumpHintsVisibility(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1161,7 +1321,7 @@ export default function Sidebar() {
};
const onWindowKeyUp = (event: KeyboardEvent) => {
setShowThreadJumpHints(
updateThreadJumpHintsVisibility(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1170,7 +1330,7 @@ export default function Sidebar() {
};
const onWindowBlur = () => {
setShowThreadJumpHints(false);
updateThreadJumpHintsVisibility(false);
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1190,6 +1350,7 @@ export default function Sidebar() {
routeTerminalOpen,
routeThreadId,
threadJumpThreadIds,
updateThreadJumpHintsVisibility,
]);
function renderProjectItem(
@@ -1198,11 +1359,14 @@ export default function Sidebar() {
) {
const {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
} = renderedProject;
@@ -1213,37 +1377,45 @@ export default function Sidebar() {
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
const threadStatus = threadStatuses.get(thread.id) ?? null;
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseEnter={() => {
setHoveredThreadId(thread.id);
}}
onMouseLeave={() => {
setHoveredThreadId((current) => (current === thread.id ? null : current));
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
}}
onBlurCapture={(event) => {
const currentTarget = event.currentTarget;
requestAnimationFrame(() => {
if (currentTarget.contains(document.activeElement)) {
return;
}
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
});
}}
>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
data-testid={`thread-row-${thread.id}`}
className={`${resolveThreadRowClassName({
isActive,
isSelected,
})} relative`}
})} relative isolate`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
@@ -1254,7 +1426,6 @@ export default function Sidebar() {
}}
onContextMenu={(event) => {
event.preventDefault();
setHoveredThreadId((current) => (current === thread.id ? null : current));
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
@@ -1291,18 +1462,7 @@ export default function Sidebar() {
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
@@ -1352,10 +1512,18 @@ export default function Sidebar() {
</span>
)}
<div className="flex min-w-12 justify-end">
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
{isConfirmingArchive ? (
<button
ref={(element) => {
if (element) {
confirmArchiveButtonRefs.current.set(thread.id, element);
} else {
confirmArchiveButtonRefs.current.delete(thread.id);
}
}}
type="button"
data-thread-selection-safe
data-testid={`thread-archive-confirm-${thread.id}`}
aria-label={`Confirm archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
onPointerDown={(event) => {
@@ -1367,80 +1535,84 @@ export default function Sidebar() {
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
setHoveredThreadId((current) => (current === thread.id ? null : current));
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : hoveredThreadId === thread.id && !isThreadRunning ? (
) : !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
});
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
) : (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setHoveredThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : (
<>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</>
)}
) : null}
<span className={threadMetaClassName}>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</span>
</div>
</div>
</SidebarMenuSubButton>
@@ -1535,6 +1707,16 @@ export default function Sidebar() {
ref={attachThreadListAutoAnimateRef}
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
>
{shouldShowThreadPanel && showEmptyThreadState ? (
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
<div
data-thread-selection-safe
className="flex h-6 w-full translate-x-0 items-center px-2 text-left text-[10px] text-muted-foreground/60"
>
<span>No threads yet</span>
</div>
</SidebarMenuSubItem>
) : null}
{shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))}
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
@@ -1548,7 +1730,10 @@ export default function Sidebar() {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
<span className="flex min-w-0 flex-1 items-center gap-2">
{hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />}
<span>Show more</span>
</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
@@ -1859,7 +2044,6 @@ export default function Sidebar() {
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
@@ -1910,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>
)}
@@ -50,6 +50,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
<div key={`dir:${node.path}`}>
<button
type="button"
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
@@ -1,5 +1,5 @@
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
import { memo } from "react";
import { memo, useLayoutEffect, useRef } from "react";
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
import { BotIcon } from "lucide-react";
import { cn } from "~/lib/utils";
@@ -41,8 +41,19 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
const listRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (!props.activeItemId || !listRef.current) return;
const el = listRef.current.querySelector<HTMLElement>(
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
);
el?.scrollIntoView({ block: "nearest" });
}, [props.activeItemId]);
return (
<Command
autoHighlight={false}
mode="none"
onItemHighlighted={(highlightedValue) => {
props.onHighlightedItemChange(
@@ -50,7 +61,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
<div
ref={listRef}
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<CommandList className="max-h-64">
{props.items.map((item) => (
<ComposerCommandMenuItem
@@ -58,6 +72,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
@@ -80,15 +95,20 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
item: ComposerCommandItem;
resolvedTheme: "light" | "dark";
isActive: boolean;
onHighlight: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
return (
<CommandItem
value={props.item.id}
data-composer-item-id={props.item.id}
className={cn(
"cursor-pointer select-none gap-2",
props.isActive && "bg-accent text-accent-foreground",
"cursor-pointer select-none gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
props.isActive && "bg-accent! text-accent-foreground!",
)}
onMouseMove={() => {
if (!props.isActive) props.onHighlight(props.item.id);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -264,9 +264,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
rowVirtualizer.measure();
}, [rowVirtualizer, timelineWidthPx]);
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const itemIntersectsViewport =
item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
if (itemIntersectsViewport) {
return false;
}
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
@@ -483,6 +488,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
@@ -22,7 +22,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models: [
{
@@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "1.0.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models: [
{
@@ -110,6 +110,19 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
},
];
function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {
return {
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models,
};
}
async function mountPicker(props: {
provider: ProviderKind;
model: string;
@@ -241,6 +254,93 @@ describe("ProviderModelPicker", () => {
}
});
it("only shows codex spark when the server reports it for the account", async () => {
const providersWithoutSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const providersWithSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "GPT-5.3 Codex Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const hidden = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithoutSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("GPT-5.3 Codex");
expect(text).not.toContain("GPT-5.3 Codex Spark");
});
} finally {
await hidden.cleanup();
}
const visible = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark");
});
} finally {
await visible.cleanup();
}
});
it("dispatches the canonical slug when a model is selected", async () => {
const mounted = await mountPicker({
provider: "claudeAgent",
@@ -35,7 +35,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -61,7 +61,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -71,6 +71,41 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
describe("getComposerProviderState", () => {
it("returns codex defaults when no codex draft options exist", () => {
const state = getComposerProviderState({
@@ -156,6 +191,7 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: false,
},
});
});
@@ -268,7 +304,116 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
fastMode: false,
},
});
});
it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => {
// Regression: normalizeClaudeModelOptionsWithCapabilities used to strip
// fastMode: false, which meant deepMerge could never clear a previous true.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: false,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => {
// Regression: thinking: true (the default) used to be stripped, which
// meant deepMerge could never clear a previous thinking: false.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
thinking: true,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default context window explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toMatchObject({
effort: "high",
contextWindow: "200k",
});
});
it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => {
// Regression: the default contextWindow must survive normalization so
// deepMerge can clear an older non-default 1m selection.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k");
});
it("omits contextWindow when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "1m",
},
},
});
expect(state.modelOptionsForDispatch).toBeUndefined();
});
it("omits fastMode when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: true,
},
},
});
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
});
});
@@ -6,12 +6,12 @@ import {
} from "@t3tools/contracts";
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
import type { ReactNode } from "react";
import { getProviderModelCapabilities } from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
import {
getProviderModelCapabilities,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
} from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
} from "@t3tools/shared/model";
export type ComposerProviderStateInput = {
provider: ProviderKind;
@@ -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;
@@ -146,13 +196,14 @@ function getProviderSummary(provider: ServerProvider | undefined) {
detail: provider.message ?? "CLI not detected on PATH.",
};
}
if (provider.authStatus === "authenticated") {
if (provider.auth.status === "authenticated") {
const authLabel = provider.auth.label ?? provider.auth.type;
return {
headline: "Authenticated",
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
detail: provider.message ?? null,
};
}
if (provider.authStatus === "unauthenticated") {
if (provider.auth.status === "unauthenticated") {
return {
headline: "Not authenticated",
detail: provider.message ?? null,
@@ -773,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
@@ -815,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
@@ -839,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 ? (
@@ -866,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
@@ -907,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
@@ -933,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
@@ -959,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
+1 -1
View File
@@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti
return (
<AutocompletePrimitive.Item
className={cn(
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
className,
)}
data-slot="autocomplete-item"
+1 -1
View File
@@ -195,7 +195,7 @@ function ComboboxItem({
return (
<ComboboxPrimitive.Item
className={cn(
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
data-slot="combobox-item"
+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;
},
};
}
+1 -36
View File
@@ -1,13 +1,11 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import { normalizeModelSlug } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -69,36 +67,3 @@ export function getDefaultServerModel(
DEFAULT_MODEL_BY_PROVIDER[provider]
);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
+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> {
+488 -94
View File
@@ -1,13 +1,22 @@
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 { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
import {
applyOrchestrationEvent,
applyOrchestrationEvents,
syncServerReadModel,
type AppState,
} from "./store";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -48,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"),
@@ -126,97 +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 = {
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(
@@ -287,7 +243,7 @@ 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");
@@ -301,7 +257,6 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
@@ -312,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,
@@ -344,6 +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]);
});
});
describe("incremental orchestration updates", () => {
it("does not mark bootstrap complete for incremental events", () => {
const state: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.meta-updated", {
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Updated title",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.bootstrapComplete).toBe(false);
});
it("preserves state identity for no-op project and thread deletes", () => {
const thread = makeThread();
const state = makeState(thread);
const nextAfterProjectDelete = applyOrchestrationEvent(
state,
makeEvent("project.deleted", {
projectId: ProjectId.makeUnsafe("project-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
const nextAfterThreadDelete = applyOrchestrationEvent(
state,
makeEvent("thread.deleted", {
threadId: ThreadId.makeUnsafe("thread-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(nextAfterProjectDelete).toBe(state);
expect(nextAfterThreadDelete).toBe(state);
});
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const state: AppState = {
projects: [
{
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
state,
makeEvent("project.created", {
projectId: recreatedProjectId,
title: "Project Recreated",
workspaceRoot: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe(recreatedProjectId);
expect(next.projects[0]?.cwd).toBe("/tmp/project");
expect(next.projects[0]?.name).toBe("Project Recreated");
});
it("updates only the affected thread for message events", () => {
const thread1 = makeThread({
id: ThreadId.makeUnsafe("thread-1"),
messages: [
{
id: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: "hello",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
],
});
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
const state: AppState = {
...makeState(thread1),
threads: [thread1, thread2],
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: thread1.id,
messageId: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: " world",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: true,
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
expect(next.threads[0]?.latestTurn?.state).toBe("running");
expect(next.threads[1]).toBe(thread2);
});
it("applies replay batches in sequence and updates session state", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "running",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: null,
assistantMessageId: null,
},
});
const state = makeState(thread);
const next = applyOrchestrationEvents(state, [
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:00:02.000Z",
},
},
{ sequence: 2 },
),
makeEvent(
"thread.message-sent",
{
threadId: thread.id,
messageId: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
},
{ sequence: 3 },
),
]);
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
});
it("does not regress latestTurn when an older turn diff completes late", () => {
const state = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "running",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:03.000Z",
completedAt: null,
assistantMessageId: null,
},
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.turn-diff-completed", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:04.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
});
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
const turnId = TurnId.makeUnsafe("turn-1");
const state = makeState(
makeThread({
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
},
turnDiffSummaries: [
{
turnId,
completedAt: "2026-02-27T00:00:02.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: MessageId.makeUnsafe("assistant-real"),
role: "assistant",
text: "final answer",
turnId,
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
});
it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
const state = makeState(
makeThread({
messages: [
{
id: MessageId.makeUnsafe("user-1"),
role: "user",
text: "first",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "first reply",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:01.000Z",
completedAt: "2026-02-27T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("user-2"),
role: "user",
text: "second",
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
streaming: false,
},
],
proposedPlans: [
{
id: "plan-1",
turnId: TurnId.makeUnsafe("turn-1"),
planMarkdown: "plan 1",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
},
{
id: "plan-2",
turnId: TurnId.makeUnsafe("turn-2"),
planMarkdown: "plan 2",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
},
],
activities: [
{
id: EventId.makeUnsafe("activity-1"),
tone: "info",
kind: "step",
summary: "one",
payload: {},
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
},
{
id: EventId.makeUnsafe("activity-2"),
tone: "info",
kind: "step",
summary: "two",
payload: {},
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
},
],
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.reverted", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
}),
);
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant-1",
]);
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
EventId.makeUnsafe("activity-1"),
]);
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
TurnId.makeUnsafe("turn-1"),
]);
});
it("clears pending source proposed plans after revert before a new session-set event", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "completed",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:03.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant-2"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
},
pendingSourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
});
const reverted = applyOrchestrationEvent(
makeState(thread),
makeEvent("thread.reverted", {
threadId: thread.id,
turnCount: 1,
}),
);
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
const next = applyOrchestrationEvent(
reverted,
makeEvent("thread.session-set", {
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-3"),
lastError: null,
updatedAt: "2026-02-27T00:00:04.000Z",
},
}),
);
expect(next.threads[0]?.latestTurn).toMatchObject({
turnId: TurnId.makeUnsafe("turn-3"),
state: "running",
});
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
});
});
+788 -308
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 -2
View File
@@ -45,6 +45,7 @@ export interface ChatMessage {
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
turnId?: TurnId | null;
createdAt: string;
completedAt?: string | undefined;
streaming: boolean;
@@ -82,7 +83,6 @@ export interface Project {
name: string;
cwd: string;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
@@ -104,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[];
+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();
});
}
+1 -1
View File
@@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
+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
+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: {
+36 -16
View File
@@ -46,33 +46,53 @@ 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.annotate({
description: "Keyboard shortcut to listen for.",
}),
),
command: KeybindingCommand.pipe(
Schema.annotate({
description: "Command to execute when the shortcut matches.",
}),
),
when: Schema.optional(KeybindingWhen).pipe(
Schema.annotate({
description: "Optional expression limiting when the shortcut is active.",
}),
),
}).annotate({
description: "Single keybinding rule entry in `keybindings.json`.",
});
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;
+37 -7
View File
@@ -46,20 +46,50 @@ 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.annotate({
description: "The Codex model slug to use for text generation.",
}),
),
options: Schema.optionalKey(CodexModelOptions).pipe(
Schema.annotate({
description: "Optional Codex-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Codex provider.",
});
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.annotate({
description: "The Claude model slug to use for text generation.",
}),
),
options: Schema.optionalKey(ClaudeModelOptions).pipe(
Schema.annotate({
description: "Optional Claude-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Claude provider.",
});
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"]);
+8 -1
View File
@@ -35,6 +35,13 @@ export const ServerProviderAuthStatus = Schema.Literals([
]);
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
export const ServerProviderAuth = Schema.Struct({
status: ServerProviderAuthStatus,
type: Schema.optional(TrimmedNonEmptyString),
label: Schema.optional(TrimmedNonEmptyString),
});
export type ServerProviderAuth = typeof ServerProviderAuth.Type;
export const ServerProviderModel = Schema.Struct({
slug: TrimmedNonEmptyString,
name: TrimmedNonEmptyString,
@@ -49,7 +56,7 @@ export const ServerProvider = Schema.Struct({
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
status: ServerProviderState,
authStatus: ServerProviderAuthStatus,
auth: ServerProviderAuth,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
models: Schema.Array(ServerProviderModel),
-8
View File
@@ -1,8 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
describe("DEFAULT_CLIENT_SETTINGS", () => {
it("includes archive confirmation with a false default", () => {
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
});
});
+78 -28
View File
@@ -23,17 +23,29 @@ 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) => TrimmedString.annotate({ description });
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 +53,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 +71,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 +124,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;
@@ -112,6 +161,7 @@ const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
});
const ModelSelectionPatch = Schema.Union([
+2 -2
View File
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
export const TerminalThreadInput = Schema.Struct({
threadId: TrimmedNonEmptyStringSchema,
});
export type TerminalThreadInput = 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>;
});
+56
View File
@@ -8,6 +8,8 @@ import {
hasContextWindowOption,
hasEffortLevel,
isClaudeUltrathinkPrompt,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
normalizeModelSlug,
resolveApiModelId,
resolveContextWindow,
@@ -226,3 +228,57 @@ describe("resolveApiModelId", () => {
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
});
});
describe("normalize*ModelOptionsWithCapabilities", () => {
it("preserves explicit false codex fast mode", () => {
expect(
normalizeCodexModelOptionsWithCapabilities(codexCaps, {
reasoningEffort: "high",
fastMode: false,
}),
).toEqual({
reasoningEffort: "high",
fastMode: false,
});
});
it("preserves the default Claude context window explicitly", () => {
expect(
normalizeClaudeModelOptionsWithCapabilities(
{
...claudeCaps,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
},
{
effort: "high",
contextWindow: "200k",
},
),
).toEqual({
effort: "high",
contextWindow: "200k",
});
});
it("omits unsupported Claude context window options", () => {
expect(
normalizeClaudeModelOptionsWithCapabilities(
{
...claudeCaps,
reasoningEffortLevels: [],
supportsThinkingToggle: true,
contextWindowOptions: [],
},
{
thinking: true,
contextWindow: "1m",
},
),
).toEqual({
thinking: true,
});
});
});
+34
View File
@@ -2,6 +2,8 @@ import {
DEFAULT_MODEL_BY_PROVIDER,
MODEL_SLUG_ALIASES_BY_PROVIDER,
type ClaudeCodeEffort,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ModelSelection,
type ProviderKind,
@@ -83,6 +85,38 @@ export function resolveContextWindow(
return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastMode !== undefined ? { fastMode } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined;
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking !== undefined ? { thinking } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
return typeof text === "string" && /\bultrathink\b/i.test(text);
}
+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}`);
+135
View File
@@ -0,0 +1,135 @@
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,
};
}
export const asJsonSchemaRecord = (value: unknown): Record<string, unknown> | null =>
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
export const getJsonSchemaProperty = (
schema: Record<string, unknown>,
propertyName: string,
): Record<string, unknown> | null => {
const properties = asJsonSchemaRecord(schema.properties);
return properties ? asJsonSchemaRecord(properties[propertyName]) : null;
};
export const getNullableJsonSchemaBranch = (
schema: Record<string, unknown> | null,
): Record<string, unknown> | null => {
if (!schema) {
return null;
}
const anyOf = Array.isArray(schema.anyOf) ? schema.anyOf : null;
if (!anyOf) {
return schema;
}
for (const entry of anyOf) {
const branch = asJsonSchemaRecord(entry);
if (!branch || branch.type === "null") {
continue;
}
return branch;
}
return null;
};
export const getJsonSchemaAnyOfBranches = (
schema: Record<string, unknown> | null,
): ReadonlyArray<Record<string, unknown>> => {
if (!schema || !Array.isArray(schema.anyOf)) {
return [];
}
return schema.anyOf
.map(asJsonSchemaRecord)
.filter(
(branch): branch is Record<string, unknown> => branch !== null && branch.type !== "null",
);
};
export const setJsonSchemaDescription = (
schema: Record<string, unknown> | null,
description: string,
): void => {
if (!schema) {
return;
}
schema.description = description;
};
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());
let changed = writeJsonFileIfChanged(
resolve(rootDir, options.latestRelativePath),
options.document,
);
if (options.version) {
changed =
writeJsonFileIfChanged(
resolve(rootDir, options.getVersionedRelativePath(options.version)),
options.document,
) || changed;
}
return { changed };
}
+58
View File
@@ -0,0 +1,58 @@
import { 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 });
}
});
});
+57
View File
@@ -0,0 +1,57 @@
import { KeybindingsConfig } from "@t3tools/contracts";
import {
buildJsonSchemaDocument,
getJsonSchemaProperty,
setJsonSchemaDescription,
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> {
const schema = buildJsonSchemaDocument(KeybindingsConfig, {
title: "T3 Code Keybindings",
description: "JSON Schema for the keybindings.json file consumed by T3 Code.",
});
const items =
schema.items && typeof schema.items === "object" && !Array.isArray(schema.items)
? (schema.items as Record<string, unknown>)
: null;
setJsonSchemaDescription(items, "Single keybinding rule entry in `keybindings.json`.");
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "key"),
"Keyboard shortcut to listen for.",
);
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "command"),
"Command to execute when the shortcut matches.",
);
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "when"),
"Optional expression limiting when the shortcut is active.",
);
return schema;
}
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,65 @@
import { 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 });
}
});
});
+126
View File
@@ -0,0 +1,126 @@
import { ServerSettings } from "@t3tools/contracts/settings";
import {
buildJsonSchemaDocument,
getJsonSchemaAnyOfBranches,
getJsonSchemaProperty,
getNullableJsonSchemaBranch,
setJsonSchemaDescription,
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.");
}
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "enableAssistantStreaming")),
"Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "defaultThreadEnvMode")),
"Default execution environment to use when creating new threads.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "textGenerationModelSelection")),
"Default provider and model to use for server-side text generation features.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "providers")),
"Provider-specific server configuration.",
);
const providersBranch = getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "providers"));
const codexBranch = getNullableJsonSchemaBranch(
getJsonSchemaProperty(providersBranch ?? {}, "codex"),
);
const claudeBranch = getNullableJsonSchemaBranch(
getJsonSchemaProperty(providersBranch ?? {}, "claudeAgent"),
);
setJsonSchemaDescription(codexBranch, "Configuration for the Codex provider.");
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(codexBranch ?? {}, "binaryPath")),
"Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(codexBranch ?? {}, "homePath")),
"Optional Codex home directory. Leave blank to use the default provider-managed location.",
);
setJsonSchemaDescription(claudeBranch, "Configuration for the Claude provider.");
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(claudeBranch ?? {}, "binaryPath")),
"Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH.",
);
for (const selectionBranch of getJsonSchemaAnyOfBranches(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "textGenerationModelSelection")),
)) {
const providerProperty = getJsonSchemaProperty(selectionBranch, "provider");
const providerBranch = getNullableJsonSchemaBranch(providerProperty);
const providerName =
Array.isArray(providerBranch?.enum) && typeof providerBranch.enum[0] === "string"
? providerBranch.enum[0]
: null;
if (providerName === "codex") {
setJsonSchemaDescription(
getJsonSchemaProperty(selectionBranch, "model"),
"The Codex model slug to use for text generation.",
);
} else if (providerName === "claudeAgent") {
setJsonSchemaDescription(
getJsonSchemaProperty(selectionBranch, "model"),
"The Claude model slug to use for text generation.",
);
}
}
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,69 @@
import { 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";
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 });
}
});
});
+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) {