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
68 changed files with 2124 additions and 1017 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
@@ -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
}
@@ -116,7 +116,6 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
pinned: false,
defaultModelSelection: {
provider,
model: defaultModel,
@@ -130,7 +129,6 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
pinned: false,
modelSelection: {
provider,
model: defaultModel,
@@ -267,7 +265,6 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -281,7 +278,6 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -31,7 +31,6 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
@@ -44,7 +43,6 @@ function makeSnapshot(input: {
id: input.threadId,
projectId: input.projectId,
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -13,6 +13,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
@@ -27,7 +28,6 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -5,6 +5,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
@@ -26,7 +27,6 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
-9
View File
@@ -14,15 +14,6 @@ export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
+3 -13
View File
@@ -34,7 +34,6 @@ import {
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
@@ -44,7 +43,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -418,16 +417,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -676,7 +666,7 @@ const makeKeybindings = Effect.gen(function* () {
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
@@ -282,7 +282,6 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -297,7 +296,6 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -72,7 +72,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -87,7 +86,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -134,7 +132,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -149,7 +146,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-archive"),
projectId: asProjectId("project-archive"),
title: "Archive me",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -203,7 +199,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -218,7 +213,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -263,7 +257,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -288,7 +281,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -326,7 +318,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -341,7 +332,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -445,7 +435,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -462,7 +451,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -483,7 +471,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -541,7 +528,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -556,7 +542,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-atomic"),
projectId: asProjectId("project-atomic"),
title: "atomic",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -684,7 +669,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -699,7 +683,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-sync"),
projectId: asProjectId("project-sync"),
title: "sync-before",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -771,7 +754,6 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -787,7 +769,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -808,7 +789,6 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1867,7 +1867,6 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
projectId: ProjectId.makeUnsafe("project-live"),
title: "Live Project",
workspaceRoot: "/tmp/project-live",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1906,7 +1905,6 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
projectId: ProjectId.makeUnsafe("project-scripts"),
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -383,7 +383,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
projectId: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
pinnedAt: event.payload.pinnedAt,
defaultModelSelection: event.payload.defaultModelSelection,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
@@ -405,7 +404,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.workspaceRoot !== undefined
? { workspaceRoot: event.payload.workspaceRoot }
: {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
: {}),
@@ -444,7 +442,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
pinnedAt: event.payload.pinnedAt,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
@@ -498,7 +495,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
@@ -234,7 +234,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -258,7 +257,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -46,7 +46,6 @@ import {
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(IsoDateTime),
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
@@ -60,7 +59,6 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(IsoDateTime),
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
@@ -149,7 +147,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -169,7 +166,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -546,7 +542,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
pinnedAt: row.pinnedAt,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -558,7 +553,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.threadId,
projectId: row.projectId,
title: row.title,
pinnedAt: row.pinnedAt,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
@@ -245,7 +245,6 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
pinned: false,
defaultModelSelection: modelSelection,
createdAt: now,
}),
@@ -257,7 +256,6 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: modelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
@@ -225,7 +225,6 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -240,7 +239,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -770,7 +768,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -806,7 +803,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -959,7 +955,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1113,7 +1108,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1149,7 +1143,6 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -28,7 +28,6 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -42,7 +41,6 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -58,7 +56,6 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -82,7 +79,6 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -162,7 +158,6 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-3"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -187,7 +182,6 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -29,7 +29,6 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
pinned: false,
createdAt: now,
},
readModel,
@@ -38,10 +37,7 @@ describe("decider project scripts", () => {
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect(event.payload).toMatchObject({
pinnedAt: null,
scripts: [],
});
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
});
it("propagates scripts in project.meta.update payload", async () => {
@@ -63,7 +59,6 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -99,82 +94,6 @@ describe("decider project scripts", () => {
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
});
it("propagates pin state through thread create and meta update", async () => {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-pin"),
aggregateKind: "project",
aggregateId: asProjectId("project-pin"),
type: "project.created",
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-project-create-pin"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-project-create-pin"),
metadata: {},
payload: {
projectId: asProjectId("project-pin"),
title: "Project",
workspaceRoot: "/tmp/project-pin",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const created = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-pin"),
threadId: ThreadId.makeUnsafe("thread-pin"),
projectId: asProjectId("project-pin"),
title: "Pinned thread",
pinned: true,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
createdAt: now,
},
readModel: withProject,
}),
);
const createdEvent = Array.isArray(created) ? created[0] : created;
expect(createdEvent.type).toBe("thread.created");
expect(createdEvent.payload).toMatchObject({ pinnedAt: now });
const withThread = await Effect.runPromise(
projectEvent(withProject, {
...createdEvent,
sequence: 2,
}),
);
const updated = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-update-pin"),
threadId: ThreadId.makeUnsafe("thread-pin"),
pinned: false,
},
readModel: withThread,
}),
);
const updatedEvent = Array.isArray(updated) ? updated[0] : updated;
expect(updatedEvent.type).toBe("thread.meta-updated");
expect(updatedEvent.payload).toMatchObject({ pinnedAt: null });
});
it("emits user message and turn-start-requested events for thread.turn.start", async () => {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
@@ -194,7 +113,6 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -218,7 +136,6 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -305,7 +222,6 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -329,7 +245,6 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -389,7 +304,6 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -413,7 +327,6 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
-4
View File
@@ -77,7 +77,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
title: command.title,
workspaceRoot: command.workspaceRoot,
pinnedAt: command.pinned ? command.createdAt : null,
defaultModelSelection: command.defaultModelSelection ?? null,
scripts: [],
createdAt: command.createdAt,
@@ -105,7 +104,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
...(command.pinned !== undefined ? { pinnedAt: command.pinned ? occurredAt : null } : {}),
...(command.defaultModelSelection !== undefined
? { defaultModelSelection: command.defaultModelSelection }
: {}),
@@ -160,7 +158,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
projectId: command.projectId,
title: command.title,
pinnedAt: command.pinned ? command.createdAt : null,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
@@ -257,7 +254,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.pinned !== undefined ? { pinnedAt: command.pinned ? occurredAt : null } : {}),
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
@@ -76,7 +76,6 @@ describe("orchestration projector", () => {
id: "thread-1",
projectId: "project-1",
title: "demo",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -99,99 +98,6 @@ describe("orchestration projector", () => {
]);
});
it("applies pin updates for projects and threads", async () => {
const now = new Date().toISOString();
const later = new Date(Date.parse(now) + 1_000).toISOString();
const withProject = await Effect.runPromise(
projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "project.created",
aggregateKind: "project",
aggregateId: "project-1",
occurredAt: now,
commandId: "cmd-project-create",
payload: {
projectId: "project-1",
title: "demo",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
),
);
const withPinnedProject = await Effect.runPromise(
projectEvent(
withProject,
makeEvent({
sequence: 2,
type: "project.meta-updated",
aggregateKind: "project",
aggregateId: "project-1",
occurredAt: later,
commandId: "cmd-project-pin",
payload: {
projectId: "project-1",
pinnedAt: later,
updatedAt: later,
},
}),
),
);
expect(withPinnedProject.projects[0]?.pinnedAt).toBe(later);
const withThread = await Effect.runPromise(
projectEvent(
withPinnedProject,
makeEvent({
sequence: 3,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const withPinnedThread = await Effect.runPromise(
projectEvent(
withThread,
makeEvent({
sequence: 4,
type: "thread.meta-updated",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-pin",
payload: {
threadId: "thread-1",
pinnedAt: later,
updatedAt: later,
},
}),
),
);
expect(withPinnedThread.threads[0]?.pinnedAt).toBe(later);
});
it("fails when event payload cannot be decoded by runtime schema", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -183,7 +183,6 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
pinnedAt: payload.pinnedAt,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
createdAt: payload.createdAt,
@@ -214,7 +213,6 @@ export function projectEvent(
...(payload.workspaceRoot !== undefined
? { workspaceRoot: payload.workspaceRoot }
: {}),
...(payload.pinnedAt !== undefined ? { pinnedAt: payload.pinnedAt } : {}),
...(payload.defaultModelSelection !== undefined
? { defaultModelSelection: payload.defaultModelSelection }
: {}),
@@ -256,7 +254,6 @@ export function projectEvent(
id: payload.threadId,
projectId: payload.projectId,
title: payload.title,
pinnedAt: payload.pinnedAt,
modelSelection: payload.modelSelection,
runtimeMode: payload.runtimeMode,
interactionMode: payload.interactionMode,
@@ -323,7 +320,6 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.pinnedAt !== undefined ? { pinnedAt: payload.pinnedAt } : {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
@@ -14,7 +14,6 @@ import {
const ProjectionProjectDbRow = ProjectionProject.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(Schema.String),
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
@@ -32,7 +31,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id,
title,
workspace_root,
pinned_at,
default_model_selection_json,
scripts_json,
created_at,
@@ -43,7 +41,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.pinnedAt},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${JSON.stringify(row.scripts)},
${row.createdAt},
@@ -54,7 +51,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
pinned_at = excluded.pinned_at,
default_model_selection_json = excluded.default_model_selection_json,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
@@ -72,7 +68,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -92,7 +87,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -27,7 +27,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
pinnedAt: "2026-03-24T00:00:00.000Z",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -61,7 +60,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const persisted = yield* projects.getById({
projectId: ProjectId.makeUnsafe("project-null-options"),
});
assert.strictEqual(Option.getOrNull(persisted)?.pinnedAt, "2026-03-24T00:00:00.000Z");
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
@@ -78,7 +76,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
threadId: ThreadId.makeUnsafe("thread-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options thread",
pinnedAt: "2026-03-24T00:00:00.000Z",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
@@ -117,7 +114,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const persisted = yield* threads.getById({
threadId: ThreadId.makeUnsafe("thread-null-options"),
});
assert.strictEqual(Option.getOrNull(persisted)?.pinnedAt, "2026-03-24T00:00:00.000Z");
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
@@ -15,7 +15,6 @@ import { ModelSelection } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(Schema.String),
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
@@ -32,7 +31,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id,
project_id,
title,
pinned_at,
model_selection_json,
runtime_mode,
interaction_mode,
@@ -48,7 +46,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.threadId},
${row.projectId},
${row.title},
${row.pinnedAt},
${JSON.stringify(row.modelSelection)},
${row.runtimeMode},
${row.interactionMode},
@@ -64,7 +61,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
DO UPDATE SET
project_id = excluded.project_id,
title = excluded.title,
pinned_at = excluded.pinned_at,
model_selection_json = excluded.model_selection_json,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
@@ -87,7 +83,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -112,7 +107,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -31,7 +31,6 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionPins.ts";
/**
* Migration loader with all migrations defined inline.
@@ -62,7 +61,6 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionPins", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,26 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const projectColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
if (!projectColumns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN pinned_at TEXT
`;
}
const threadColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!threadColumns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pinned_at TEXT
`;
}
});
@@ -16,7 +16,6 @@ export const ProjectionProject = Schema.Struct({
projectId: ProjectId,
title: Schema.String,
workspaceRoot: Schema.String,
pinnedAt: Schema.NullOr(IsoDateTime),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -24,7 +24,6 @@ export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: Schema.String,
pinnedAt: Schema.NullOr(IsoDateTime),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
+46
View File
@@ -216,4 +216,50 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves a top-level $schema declaration when rewriting settings", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(
serverConfig.settingsPath,
`${JSON.stringify(
{
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
},
},
null,
2,
)}\n`,
);
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.start;
yield* serverSettings.updateSettings({
providers: {
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+31 -2
View File
@@ -39,7 +39,7 @@ import {
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
@@ -101,6 +101,9 @@ export class ServerSettingsService extends ServiceMap.Service<
}
const ServerSettingsJson = fromLenientJson(ServerSettings);
const UnknownJson = fromLenientJson(Schema.Unknown);
const encodeServerSettingsDocument = encodePrettyJsonEffect(Schema.Unknown);
const SETTINGS_SCHEMA_DECLARATION_KEY = "$schema";
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
@@ -177,6 +180,7 @@ const makeServerSettings = Effect.gen(function* () {
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
const schemaDeclarationRef = yield* Ref.make<string | undefined>(undefined);
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
@@ -207,10 +211,25 @@ const makeServerSettings = Effect.gen(function* () {
const loadSettingsFromDisk = Effect.gen(function* () {
if (!(yield* readConfigExists)) {
yield* Ref.set(schemaDeclarationRef, undefined);
return DEFAULT_SERVER_SETTINGS;
}
const raw = yield* readRawConfig;
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
if (rawJson._tag === "Success") {
const value = rawJson.value;
const valueRecord =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
const schemaDeclaration =
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
: undefined;
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
}
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -232,7 +251,17 @@ const makeServerSettings = Effect.gen(function* () {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
return Ref.get(schemaDeclarationRef).pipe(
Effect.map((schemaDeclaration) =>
schemaDeclaration
? {
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
...sparseSettings,
}
: sparseSettings,
),
Effect.flatMap(encodeServerSettingsDocument),
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
-4
View File
@@ -1221,7 +1221,6 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1235,7 +1234,6 @@ describe("WebSocket Server", () => {
threadId: "thread-diff",
projectId: "project-diff",
title: "Diff Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1308,7 +1306,6 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "WS Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1322,7 +1319,6 @@ describe("WebSocket Server", () => {
threadId: "thread-1",
projectId: "project-1",
title: "Thread 1",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
-2
View File
@@ -675,7 +675,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
pinned: false,
defaultModelSelection: bootstrapProjectDefaultModelSelection,
createdAt,
});
@@ -699,7 +698,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
threadId,
projectId: bootstrapProjectId,
title: "New thread",
pinned: false,
modelSelection: bootstrapProjectDefaultModelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
@@ -237,7 +237,6 @@ function createSnapshotForTargetUser(options: {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -253,7 +252,6 @@ function createSnapshotForTargetUser(options: {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Browser test thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -312,7 +310,6 @@ function addThreadToSnapshot(
id: threadId,
projectId: PROJECT_ID,
title: "New thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -360,7 +357,6 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest
threadId,
projectId: PROJECT_ID,
title: "New thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -89,7 +89,6 @@ const makeThread = (input?: {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
@@ -248,7 +247,6 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
@@ -285,7 +283,6 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
@@ -331,7 +328,6 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
@@ -26,7 +26,6 @@ export function buildLocalDraftThread(
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
pinnedAt: null,
modelSelection: fallbackModelSelection,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
-2
View File
@@ -2774,7 +2774,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: threadIdForSend,
projectId: activeProject.id,
title,
pinned: false,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
@@ -3222,7 +3221,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: nextThreadId,
projectId: activeProject.id,
title: nextThreadTitle,
pinned: false,
modelSelection: nextThreadModelSelection,
runtimeMode,
interactionMode: "default",
@@ -76,7 +76,6 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -92,7 +91,6 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Test thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -592,7 +592,6 @@ function makeProject(overrides: Partial<Project> = {}): Project {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -611,7 +610,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -760,73 +758,6 @@ describe("sortThreadsForSidebar", () => {
ThreadId.makeUnsafe("thread-2"),
]);
});
it("puts pinned threads ahead of unpinned threads in auto-sort modes", () => {
const sorted = sortThreadsForSidebar(
[
{
...makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: null,
},
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
]);
});
it("sorts pinned threads by latest pin timestamp before activity recency", () => {
const sorted = sortThreadsForSidebar(
[
{
...makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:01:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
pinnedAt: "2026-03-09T10:10:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-3"),
createdAt: "2026-03-09T10:10:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
}),
pinnedAt: null,
},
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-3"),
]);
});
});
describe("getFallbackThreadIdAfterDelete", () => {
@@ -865,41 +796,6 @@ describe("getFallbackThreadIdAfterDelete", () => {
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-newest"));
});
it("respects pinning when choosing the fallback thread after delete", () => {
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads: [
{
...makeThread({
id: ThreadId.makeUnsafe("thread-active"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: null,
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-pinned"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:03:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-newer"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:10:00.000Z",
}),
pinnedAt: null,
},
],
deletedThreadId: ThreadId.makeUnsafe("thread-active"),
sortOrder: "updated_at",
});
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-pinned"));
});
it("skips other threads being deleted in the same action", () => {
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads: [
@@ -1004,65 +900,6 @@ describe("sortProjectsForSidebar", () => {
]);
});
it("puts pinned projects ahead of unpinned projects in auto-sort modes", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Pinned older project",
pinnedAt: "2026-03-09T10:20:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Unpinned newer project",
pinnedAt: null,
updatedAt: "2026-03-09T10:05:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("sorts pinned projects by latest pin timestamp before project recency", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Pinned older project",
pinnedAt: "2026-03-09T10:10:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Pinned newer project",
pinnedAt: "2026-03-09T10:20:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-3"),
name: "Unpinned project",
pinnedAt: null,
updatedAt: "2026-03-09T10:10:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-3"),
]);
});
it("falls back to name and id ordering when projects have no sortable timestamps", () => {
const sorted = sortProjectsForSidebar(
[
-26
View File
@@ -16,12 +16,10 @@ type SidebarProject = {
name: string;
createdAt?: string | undefined;
updatedAt?: string | undefined;
pinnedAt?: string | null | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
latestUserMessageAt?: string | null;
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
pinnedAt?: string | null | undefined;
};
export type ThreadTraversalDirection = "previous" | "next";
@@ -450,24 +448,10 @@ function getThreadSortTimestamp(
return getLatestUserMessageTimestamp(thread);
}
function getPinnedSortTimestamp(input: { pinnedAt?: string | null | undefined }): number | null {
return toSortableTimestamp(input.pinnedAt ?? undefined);
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const leftPinnedAt = getPinnedSortTimestamp(left);
const rightPinnedAt = getPinnedSortTimestamp(right);
const leftPinned = leftPinnedAt !== null;
const rightPinned = rightPinnedAt !== null;
if (leftPinned !== rightPinned) {
return rightPinned ? 1 : -1;
}
if (leftPinnedAt !== null && rightPinnedAt !== null && leftPinnedAt !== rightPinnedAt) {
return rightPinnedAt > leftPinnedAt ? 1 : -1;
}
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
const byTimestamp =
@@ -542,16 +526,6 @@ export function sortProjectsForSidebar<
}
return [...projects].toSorted((left, right) => {
const leftPinnedAt = getPinnedSortTimestamp(left);
const rightPinnedAt = getPinnedSortTimestamp(right);
const leftPinned = leftPinnedAt !== null;
const rightPinned = rightPinnedAt !== null;
if (leftPinned !== rightPinned) {
return rightPinned ? 1 : -1;
}
if (leftPinnedAt !== null && rightPinnedAt !== null && leftPinnedAt !== rightPinnedAt) {
return rightPinnedAt > leftPinnedAt ? 1 : -1;
}
const rightTimestamp = getProjectSortTimestamp(
right,
threadsByProjectId.get(right.id) ?? [],
+281 -380
View File
@@ -4,7 +4,6 @@ import {
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
PinIcon,
PlusIcon,
SettingsIcon,
SquarePenIcon,
@@ -153,7 +152,6 @@ type SidebarThreadSnapshot = Pick<
| "id"
| "interactionMode"
| "latestTurn"
| "pinnedAt"
| "projectId"
| "proposedPlans"
| "session"
@@ -165,7 +163,9 @@ type SidebarThreadSnapshot = Pick<
latestUserMessageAt: string | null;
};
type SidebarProjectSnapshot = Project & { expanded: boolean };
type SidebarProjectSnapshot = Project & {
expanded: boolean;
};
const sidebarThreadSnapshotCache = new WeakMap<
Thread,
@@ -206,7 +206,6 @@ function toSidebarThreadSnapshot(
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
latestTurn: thread.latestTurn,
pinnedAt: thread.pinnedAt,
lastVisitedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
@@ -676,7 +675,6 @@ export default function Sidebar() {
projectId,
title,
workspaceRoot: cwd,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -834,42 +832,6 @@ export default function Sidebar() {
});
},
});
const setThreadPinned = useCallback(async (thread: SidebarThreadSnapshot, pinned: boolean) => {
const api = readNativeApi();
if (!api) return;
try {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: thread.id,
pinned,
});
} catch (error) {
toastManager.add({
type: "error",
title: `${pinned ? "Pin" : "Unpin"} thread failed`,
description: error instanceof Error ? error.message : "An error occurred.",
});
}
}, []);
const setProjectPinned = useCallback(async (project: Project, pinned: boolean) => {
const api = readNativeApi();
if (!api) return;
try {
await api.orchestration.dispatchCommand({
type: "project.meta.update",
commandId: newCommandId(),
projectId: project.id,
pinned,
});
} catch (error) {
toastManager.add({
type: "error",
title: `${pinned ? "Pin" : "Unpin"} project failed`,
description: error instanceof Error ? error.message : "An error occurred.",
});
}
}, []);
const handleThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
@@ -880,10 +842,6 @@ export default function Sidebar() {
thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null;
const clicked = await api.contextMenu.show(
[
{
id: "toggle-pin",
label: thread.pinnedAt !== null ? "Unpin thread" : "Pin thread",
},
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
@@ -893,11 +851,6 @@ export default function Sidebar() {
position,
);
if (clicked === "toggle-pin") {
await setThreadPinned(thread, thread.pinnedAt === null);
return;
}
if (clicked === "rename") {
setRenamingThreadId(threadId);
setRenamingTitle(thread.title);
@@ -947,7 +900,6 @@ export default function Sidebar() {
markThreadUnread,
projectCwdById,
threads,
setThreadPinned,
],
);
@@ -1066,19 +1018,11 @@ export default function Sidebar() {
const clicked = await api.contextMenu.show(
[
{
id: "toggle-pin",
label: project.pinnedAt !== null ? "Unpin project" : "Pin project",
},
{ id: "copy-path", label: "Copy Project Path" },
{ id: "delete", label: "Remove project", destructive: true },
],
position,
);
if (clicked === "toggle-pin") {
await setProjectPinned(project, project.pinnedAt === null);
return;
}
if (clicked === "copy-path") {
copyPathToClipboard(project.cwd, { path: project.cwd });
return;
@@ -1125,7 +1069,6 @@ export default function Sidebar() {
copyPathToClipboard,
getDraftThreadByProjectId,
projects,
setProjectPinned,
threads,
],
);
@@ -1217,32 +1160,6 @@ export default function Sidebar() {
() => threads.filter((thread) => thread.archivedAt === null),
[threads],
);
const threadStatusById = useMemo(
() =>
new Map(
visibleThreads.map((thread) => [
thread.id,
resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
}),
]),
),
[visibleThreads],
);
const globalPinnedThreads = useMemo(
() =>
sortThreadsForSidebar(
visibleThreads.filter((thread) => thread.pinnedAt !== null),
appSettings.sidebarThreadSortOrder,
),
[appSettings.sidebarThreadSortOrder, visibleThreads],
);
const globalPinnedThreadIds = useMemo(
() => globalPinnedThreads.map((thread) => thread.id),
[globalPinnedThreads],
);
const sortedProjects = useMemo(
() =>
sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder),
@@ -1252,17 +1169,30 @@ export default function Sidebar() {
const renderedProjects = useMemo(
() =>
sortedProjects.map((project) => {
const allProjectThreads = sortThreadsForSidebar(
const projectThreads = sortThreadsForSidebar(
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const projectThreads = allProjectThreads.filter((thread) => thread.pinnedAt === null);
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(
allProjectThreads.map((thread) => threadStatusById.get(thread.id) ?? null),
projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const activeThreadId = routeThreadId ?? undefined;
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
const shouldShowThreadPanel = project.expanded;
const pinnedCollapsedThread =
!project.expanded && activeThreadId
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const {
hasHiddenThreads,
hiddenThreads,
@@ -1274,11 +1204,13 @@ export default function Sidebar() {
previewLimit: THREAD_PREVIEW_LIMIT,
});
const hiddenThreadStatus = resolveProjectStatusIndicator(
hiddenThreads.map((thread) => threadStatusById.get(thread.id) ?? null),
hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = visibleProjectThreads;
const showEmptyThreadState = project.expanded && allProjectThreads.length === 0;
const renderedThreads = pinnedCollapsedThread
? [pinnedCollapsedThread]
: visibleProjectThreads;
const showEmptyThreadState = project.expanded && projectThreads.length === 0;
return {
hasHiddenThreads,
@@ -1286,6 +1218,8 @@ export default function Sidebar() {
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
@@ -1297,13 +1231,12 @@ export default function Sidebar() {
expandedThreadListsByProject,
routeThreadId,
sortedProjects,
threadStatusById,
visibleThreads,
],
);
const visibleSidebarThreadIds = useMemo(
() => [...globalPinnedThreadIds, ...getVisibleSidebarThreadIds(renderedProjects)],
[globalPinnedThreadIds, renderedProjects],
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const threadJumpCommandById = useMemo(() => {
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
@@ -1420,258 +1353,6 @@ export default function Sidebar() {
updateThreadJumpHintsVisibility,
]);
const renderThreadRow = (
thread: SidebarThreadSnapshot,
options: {
leadingVisual?: "project-favicon";
orderedThreadIds: readonly ThreadId[];
},
) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = threadStatusById.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";
const hoverActionClassName =
"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";
const hoverActionGroupClassName =
"pointer-events-none absolute top-1/2 right-1 flex -translate-y-1/2 items-center gap-0.5 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";
const projectCwd = projectCwdById.get(thread.projectId);
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseLeave={() => {
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 isolate`}
onClick={(event) => {
handleThreadClick(event, thread.id, options.orderedThreadIds);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
navigateToThread(thread.id);
}}
onContextMenu={(event) => {
event.preventDefault();
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
} else {
if (selectedThreadIds.size > 0) {
clearSelection();
}
void handleThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{options.leadingVisual === "project-favicon" ? (
projectCwd ? (
<ProjectFavicon cwd={projectCwd} />
) : (
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />
)
) : null}
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
)}
<div className="flex min-w-12 justify-end">
{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) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : null}
{!isConfirmingArchive ? (
<div className={hoverActionGroupClassName}>
{!isThreadRunning ? (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className={hoverActionClassName}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
if (appSettings.confirmThreadArchive) {
setConfirmingArchiveThreadId(thread.id);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
});
return;
}
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
) : null}
</div>
) : 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>
</SidebarMenuSubItem>
);
};
function renderProjectItem(
renderedProject: (typeof renderedProjects)[number],
dragHandleProps: SortableProjectHandleProps | null,
@@ -1682,11 +1363,262 @@ export default function Sidebar() {
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
} = renderedProject;
const renderThreadRow = (thread: (typeof projectThreads)[number]) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = threadStatuses.get(thread.id) ?? null;
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseLeave={() => {
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
}}
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 isolate`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
navigateToThread(thread.id);
}}
onContextMenu={(event) => {
event.preventDefault();
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
} else {
if (selectedThreadIds.size > 0) {
clearSelection();
}
void handleThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<div className="flex min-w-12 justify-end">
{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) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
});
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
) : (
<Tooltip>
<TooltipTrigger
render={
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : null}
<span className={threadMetaClassName}>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</span>
</div>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
};
return (
<>
@@ -1738,15 +1670,6 @@ export default function Sidebar() {
{project.name}
</span>
</SidebarMenuButton>
{project.pinnedAt !== null ? (
<span
aria-hidden="true"
title="Pinned project"
className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center text-muted-foreground/65 transition-opacity duration-150 group-hover/menu-item:opacity-0 group-focus-within/menu-item:opacity-0"
>
<PinIcon className="size-3.5" />
</span>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -1760,10 +1683,6 @@ export default function Sidebar() {
}
showOnHover
className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -1798,10 +1717,7 @@ export default function Sidebar() {
</div>
</SidebarMenuSubItem>
) : null}
{shouldShowThreadPanel &&
renderedThreads.map((thread) =>
renderThreadRow(thread, { orderedThreadIds: orderedProjectThreadIds }),
)}
{shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))}
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
@@ -2086,21 +2002,6 @@ export default function Sidebar() {
</Alert>
</SidebarGroup>
) : null}
{globalPinnedThreads.length > 0 ? (
<SidebarGroup className="px-2 pt-2 pb-0">
<SidebarMenuSub
ref={attachThreadListAutoAnimateRef}
className="mx-0 w-full translate-x-0 gap-0.5 border-l-0 px-0 py-0"
>
{globalPinnedThreads.map((thread) =>
renderThreadRow(thread, {
leadingVisual: "project-favicon",
orderedThreadIds: globalPinnedThreadIds,
}),
)}
</SidebarMenuSub>
</SidebarGroup>
) : null}
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between pl-2 pr-1.5">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
@@ -12,14 +12,19 @@ import {
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ClaudeSettings,
ClientSettingsSchema,
CodexSettings,
PROVIDER_DISPLAY_NAMES,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
ServerSettings,
ThreadId,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { getSchemaDescription } from "@t3tools/shared/schemaJson";
import { Equal } from "effect";
import { APP_VERSION } from "../../branding";
import {
@@ -81,6 +86,51 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
function requireSchemaDescription(
schema: Parameters<typeof getSchemaDescription>[0],
label: string,
) {
const description = getSchemaDescription(schema);
if (!description) {
throw new Error(`Missing schema description for ${label}`);
}
return description;
}
const SETTINGS_DESCRIPTIONS = {
timestampFormat: requireSchemaDescription(
ClientSettingsSchema.fields.timestampFormat,
"ClientSettings.timestampFormat",
),
diffWordWrap: requireSchemaDescription(
ClientSettingsSchema.fields.diffWordWrap,
"ClientSettings.diffWordWrap",
),
confirmThreadArchive: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadArchive,
"ClientSettings.confirmThreadArchive",
),
confirmThreadDelete: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadDelete,
"ClientSettings.confirmThreadDelete",
),
enableAssistantStreaming: requireSchemaDescription(
ServerSettings.fields.enableAssistantStreaming,
"ServerSettings.enableAssistantStreaming",
),
defaultThreadEnvMode: requireSchemaDescription(
ServerSettings.fields.defaultThreadEnvMode,
"ServerSettings.defaultThreadEnvMode",
),
textGenerationModelSelection: requireSchemaDescription(
ServerSettings.fields.textGenerationModelSelection,
"ServerSettings.textGenerationModelSelection",
),
codexBinaryPath: requireSchemaDescription(CodexSettings.fields.binaryPath, "Codex.binaryPath"),
codexHomePath: requireSchemaDescription(CodexSettings.fields.homePath, "Codex.homePath"),
claudeBinaryPath: requireSchemaDescription(ClaudeSettings.fields.binaryPath, "Claude.binaryPath"),
} as const;
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
type InstallProviderSettings = {
@@ -98,16 +148,16 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
provider: "codex",
title: "Codex",
binaryPlaceholder: "Codex binary path",
binaryDescription: "Path to the Codex binary",
binaryDescription: SETTINGS_DESCRIPTIONS.codexBinaryPath,
homePathKey: "codexHomePath",
homePlaceholder: "CODEX_HOME",
homeDescription: "Optional custom Codex home and config directory.",
homeDescription: SETTINGS_DESCRIPTIONS.codexHomePath,
},
{
provider: "claudeAgent",
title: "Claude",
binaryPlaceholder: "Claude binary path",
binaryDescription: "Path to the Claude binary",
binaryDescription: SETTINGS_DESCRIPTIONS.claudeBinaryPath,
},
] as const;
@@ -774,7 +824,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Time format"
description="System default follows your browser or OS clock preference."
description={SETTINGS_DESCRIPTIONS.timestampFormat}
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
<SettingResetButton
@@ -816,7 +866,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Diff line wrapping"
description="Set the default wrap state when the diff panel opens."
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
<SettingResetButton
@@ -840,7 +890,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Assistant output"
description="Show token-by-token output while a response is in progress."
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
@@ -867,7 +917,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="New threads"
description="Pick the default workspace mode for newly created draft threads."
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
<SettingResetButton
@@ -908,7 +958,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Archive confirmation"
description="Require a second click on the inline archive action before a thread is archived."
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
<SettingResetButton
@@ -934,7 +984,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Delete confirmation"
description="Ask before deleting a thread and its chat history."
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
<SettingResetButton
@@ -960,7 +1010,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Text generation model"
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
resetAction={
isGitWritingModelDirty ? (
<SettingResetButton
@@ -48,7 +48,6 @@ describe("deriveOrchestrationBatchEffects", () => {
threadId: createdThreadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Created thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
@@ -81,7 +80,6 @@ describe("deriveOrchestrationBatchEffects", () => {
threadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Recreated thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
-9
View File
@@ -25,7 +25,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -54,7 +53,6 @@ function makeState(thread: Thread): AppState {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -99,7 +97,6 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -131,7 +128,6 @@ function makeReadModel(thread: OrchestrationReadModel["threads"][number]): Orche
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -153,7 +149,6 @@ function makeReadModelProject(
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -258,7 +253,6 @@ describe("store read model sync", () => {
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -269,7 +263,6 @@ describe("store read model sync", () => {
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -360,7 +353,6 @@ describe("incremental orchestration updates", () => {
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -378,7 +370,6 @@ describe("incremental orchestration updates", () => {
projectId: recreatedProjectId,
title: "Project Recreated",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
-6
View File
@@ -147,7 +147,6 @@ function mapThread(thread: OrchestrationThread): Thread {
codexThreadId: null,
projectId: thread.projectId,
title: thread.title,
pinnedAt: thread.pinnedAt,
modelSelection: normalizeModelSelection(thread.modelSelection),
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
@@ -172,7 +171,6 @@ function mapProject(project: OrchestrationReadModel["projects"][number]): Projec
id: project.id,
name: project.title,
cwd: project.workspaceRoot,
pinnedAt: project.pinnedAt,
defaultModelSelection: project.defaultModelSelection
? normalizeModelSelection(project.defaultModelSelection)
: null,
@@ -426,7 +424,6 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
id: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
pinnedAt: event.payload.pinnedAt,
defaultModelSelection: event.payload.defaultModelSelection,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
@@ -447,7 +444,6 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
...project,
...(event.payload.title !== undefined ? { name: event.payload.title } : {}),
...(event.payload.workspaceRoot !== undefined ? { cwd: event.payload.workspaceRoot } : {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.defaultModelSelection !== undefined
? {
defaultModelSelection: event.payload.defaultModelSelection
@@ -474,7 +470,6 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
id: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
pinnedAt: event.payload.pinnedAt,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
@@ -524,7 +519,6 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
...thread,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: normalizeModelSelection(event.payload.modelSelection) }
: {}),
-2
View File
@@ -82,7 +82,6 @@ export interface Project {
id: ProjectId;
name: string;
cwd: string;
pinnedAt: string | null;
defaultModelSelection: ModelSelection | null;
createdAt?: string | undefined;
updatedAt?: string | undefined;
@@ -94,7 +93,6 @@ export interface Thread {
codexThreadId: string | null;
projectId: ProjectId;
title: string;
pinnedAt: string | null;
modelSelection: ModelSelection;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
-1
View File
@@ -10,7 +10,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
-2
View File
@@ -289,7 +289,6 @@ describe("wsNativeApi", () => {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/workspace",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-02-24T00:00:00.000Z",
@@ -332,7 +331,6 @@ describe("wsNativeApi", () => {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
+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
+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;
@@ -95,7 +95,6 @@ it.effect("trims branded ids and command string fields at decode boundaries", ()
assert.strictEqual(parsed.projectId, "project-1");
assert.strictEqual(parsed.title, "Project Title");
assert.strictEqual(parsed.workspaceRoot, "/tmp/workspace");
assert.strictEqual(parsed.pinned, false);
assert.deepStrictEqual(parsed.defaultModelSelection, {
provider: "codex",
model: "gpt-5.2",
@@ -118,7 +117,6 @@ it.effect("decodes historical project.created payloads with a default provider",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.strictEqual(parsed.defaultModelSelection?.provider, "codex");
assert.strictEqual(parsed.pinnedAt, null);
}),
);
@@ -216,7 +214,6 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
assert.strictEqual(parsed.modelSelection.provider, "codex");
assert.strictEqual(parsed.pinnedAt, null);
}),
);
+37 -17
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"]);
@@ -145,7 +175,6 @@ export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -275,7 +304,6 @@ export const OrchestrationThread = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
@@ -310,7 +338,6 @@ export const ProjectCreateCommand = Schema.Struct({
projectId: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinned: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
createdAt: IsoDateTime,
});
@@ -321,7 +348,6 @@ const ProjectMetaUpdateCommand = Schema.Struct({
projectId: ProjectId,
title: Schema.optional(TrimmedNonEmptyString),
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
pinned: Schema.optional(Schema.Boolean),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
});
@@ -338,7 +364,6 @@ const ThreadCreateCommand = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinned: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
@@ -372,7 +397,6 @@ const ThreadMetaUpdateCommand = Schema.Struct({
commandId: CommandId,
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
pinned: Schema.optional(Schema.Boolean),
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
@@ -630,7 +654,6 @@ export const ProjectCreatedPayload = Schema.Struct({
projectId: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -641,7 +664,6 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
projectId: ProjectId,
title: Schema.optional(TrimmedNonEmptyString),
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,
@@ -656,7 +678,6 @@ export const ThreadCreatedPayload = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
@@ -687,7 +708,6 @@ export const ThreadUnarchivedPayload = Schema.Struct({
export const ThreadMetaUpdatedPayload = Schema.Struct({
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+77 -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;
+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) {