Compare commits

..
Author SHA1 Message Date
Julius Marminge 346402e6ea Merge remote-tracking branch 'origin/main' into t3code/server-settings-schema
# Conflicts:
#	apps/web/src/components/settings/SettingsPanels.tsx
2026-04-01 00:03:33 -07:00
Julius Marminge c13fc4f6f8 Inline keybindings schema source for scripts
- Import keybindings types directly from contracts source
- Narrow TS includes to the schema generation inputs
2026-03-30 23:51:27 -07:00
Julius Marminge 56f56f5506 Export keybindings contract for schema generation
- Add a dedicated `@t3tools/contracts/keybindings` export
- Point keybindings schema generation at the new subpath
- Keep generated schema output under `apps/marketing/public/schemas`
2026-03-30 23:44:55 -07:00
Julius Marminge 9d475dd325 Format marketing JSON schemas
- Reformat keybinding and settings schema enums
- Normalize required field arrays
2026-03-30 23:31:37 -07:00
Julius Marminge a43922f5c9 Remove unused JSON schema helpers
- Delete dead helper exports from `scripts/lib/json-schema.ts`
- Keep schema document generation focused on file output
2026-03-30 23:31:13 -07:00
Julius Marminge c3097ba5d7 Move schema descriptions into contracts
- Inline settings and keybinding schema descriptions in shared contracts
- Simplify schema generation scripts to emit the updated docs
2026-03-30 22:31:33 -07:00
Julius Marminge 32f1d4c34f Merge remote-tracking branch 'origin/main' into t3code/server-settings-schema 2026-03-30 15:49:59 -07:00
Julius Marminge 80475e854c Skip unchanged versioned schema writes
- Avoid writing versioned schema snapshots when the latest schema content did not change
- Add coverage for keybindings, server settings, and release version updates
2026-03-30 15:44:56 -07:00
Julius Marminge aeaf31ff6d Rename published schema artifacts to .json
- Move server settings and keybindings schema URLs to shorter `.json` paths
- Update release tooling, docs, and tests to match the new schema locations
2026-03-30 15:39:49 -07:00
Julius Marminge 8b9cf23ec7 Sync settings descriptions with schema metadata
- Centralize settings copy in schema annotations
- Reuse schema descriptions in the settings UI
- Refresh generated server settings schema output
2026-03-30 15:33:18 -07:00
Julius Marminge 68ff6d8578 Format marketing schema enums consistently
- Reflow schema arrays and required lists
- Keep published server settings and keybindings schemas normalized
2026-03-30 15:29:07 -07:00
Julius Marminge 8f5078c6d5 Annotate settings and keybinding schemas with docs
- Add schema descriptions for editor tooling and generated JSON schemas
- Update published keybindings and server settings schema docs
2026-03-30 15:27:37 -07:00
Julius Marminge 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
41 changed files with 2167 additions and 550 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
+2 -1
View File
@@ -9,7 +9,8 @@
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
"apps/web/public/mockServiceWorker.js",
"apps/marketing/public/schemas"
],
"sortPackageJson": {}
}
+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,72 @@
{
"$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`."
}
]
}
+326
View File
@@ -0,0 +1,326 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Show token-by-token output while a response is in progress."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": [
"local",
"worktree"
],
"description": "Pick the default workspace mode for newly created draft threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": [
"codex"
],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": [
"xhigh",
"high",
"medium",
"low"
]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": [
"provider",
"model"
],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": [
"claudeAgent"
],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": [
"low",
"medium",
"high",
"max",
"ultrathink"
]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": [
"provider",
"model"
],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex binary"
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional custom Codex home and config directory."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude binary"
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
@@ -0,0 +1,302 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Default execution environment to use when creating new threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["codex"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": ["xhigh", "high", "medium", "low"]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["claudeAgent"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": ["low", "medium", "high", "max", "ultrathink"]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Default provider and model to use for server-side text generation features."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
+102 -101
View File
@@ -122,34 +122,35 @@ const buildCmd = Command.make(
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
Effect.fn("buildCmd")(function* (config) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
// ---------------------------------------------------------------------------
@@ -166,87 +167,87 @@ const publishCmd = Command.make(
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
Effect.fn("publishCmd")(function* (config) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
}
}
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.fn("publishCmd.acquire")(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
})(),
// Use: npm publish
() =>
Effect.fn("publishCmd.use")(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
})(),
// Release: restore
Effect.fn("publishCmd.release")(function* (resource: {
readonly iconBackups: ReadonlyArray<PublishIconBackup>;
}) {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: npm publish
() =>
Effect.gen(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
}),
// Release: restore
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
).pipe(Command.withDescription("Publish the server package to npm."));
// ---------------------------------------------------------------------------
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -149,8 +149,7 @@ const make = Effect.gen(function* () {
}
return turnDiff;
},
);
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
@@ -86,140 +86,139 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
if (!commitOid) {
return false;
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
}
return true;
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -248,26 +247,24 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
},
);
});
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
return {
isGitRepository,
+117 -111
View File
@@ -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 "@t3tools/contracts";
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";
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
const runClaudeJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -82,126 +82,132 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
),
],
{ concurrency: "unbounded" },
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"claude",
operation,
cause,
"Failed to read Claude CLI exit code",
),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
),
);
return stdout;
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
const rawStdout = yield* runClaudeCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
// ---------------------------------------------------------------------------
@@ -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
@@ -35,7 +35,6 @@ import {
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
@@ -45,7 +44,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";
type WhenToken =
| { type: "identifier"; value: string }
@@ -406,16 +405,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;
@@ -664,7 +654,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)),
+1 -20
View File
@@ -31,15 +31,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["/tmp/workspace"],
});
const traeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLaunch, {
command: "trae",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
@@ -98,15 +89,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
@@ -274,7 +256,6 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
@@ -282,7 +263,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
+13 -14
View File
@@ -92,20 +92,19 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
/**
* Layer that runs migrations when the layer is built.
+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
@@ -41,7 +41,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 interface ServerSettingsShape {
/** Start the settings runtime and attach file watching. */
@@ -90,6 +90,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"];
@@ -166,6 +169,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));
@@ -196,10 +200,25 @@ const makeServerSettings = Effect.gen(function* () {
const loadSettingsFromDisk = Effect.gen(function* () {
if (!(yield* readConfigExists)) {
yield* Ref.set(schemaDeclarationRef, undefined);
return DEFAULT_SERVER_SETTINGS;
}
const raw = yield* readRawConfig;
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
if (rawJson._tag === "Success") {
const value = rawJson.value;
const valueRecord =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
const schemaDeclaration =
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
: undefined;
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
}
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -222,7 +241,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)),
+8 -1
View File
@@ -21,5 +21,12 @@
}
]
},
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
"include": [
"src",
"tsdown.config.ts",
"scripts",
"integration",
"../../scripts/lib/brand-assets.ts",
"../../scripts/lib/resolve-catalog.ts"
]
}
@@ -1407,52 +1407,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("opens the project cwd with Trae when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
availableEditors: ["trae"],
};
},
});
try {
await waitForServerConfigToApply();
const openButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Open",
) as HTMLButtonElement | null,
"Unable to find Open button.",
);
await vi.waitFor(() => {
expect(openButton.disabled).toBe(false);
});
openButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.shellOpenInEditor,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.shellOpenInEditor,
cwd: "/repo/project",
editor: "trae",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("filters the open picker menu and opens VSCodium from the menu", async () => {
setDraftThreadWithoutWorktree();
-14
View File
@@ -20,20 +20,6 @@ export const CursorIcon: Icon = (props) => (
</svg>
);
export const TraeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
<rect x="1" y="4" width="3" height="14" />
<rect x="4" y="18" width="18" height="3" />
{/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */}
<rect x="4" y="4" width="18" height="3" />
<rect x="19" y="7" width="3" height="11" />
{/* Two diamonds, offset slightly to the right within the open area */}
<path d="M11 10L13 12L11 14L9 12Z" />
<path d="M16 10L18 12L16 14L14 12Z" />
</svg>
);
export const VisualStudioCode: Icon = (props) => {
const id = useId();
const maskId = `${id}-vscode-a`;
@@ -6,7 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -17,11 +17,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
Icon: CursorIcon,
value: "cursor",
},
{
label: "Trae",
Icon: TraeIcon,
value: "trae",
},
{
label: "VS Code",
Icon: VisualStudioCode,
@@ -12,14 +12,19 @@ import {
import { 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 {
@@ -85,6 +90,52 @@ 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 = {
provider: ProviderKind;
title: string;
@@ -100,16 +151,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;
@@ -773,7 +824,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Time format"
description="System default follows your browser or OS clock preference."
description={SETTINGS_DESCRIPTIONS.timestampFormat}
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
<SettingResetButton
@@ -815,7 +866,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Diff line wrapping"
description="Set the default wrap state when the diff panel opens."
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
<SettingResetButton
@@ -839,7 +890,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Assistant output"
description="Show token-by-token output while a response is in progress."
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
@@ -866,7 +917,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="New threads"
description="Pick the default workspace mode for newly created draft threads."
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
<SettingResetButton
@@ -907,7 +958,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Archive confirmation"
description="Require a second click on the inline archive action before a thread is archived."
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
<SettingResetButton
@@ -933,7 +984,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Delete confirmation"
description="Ask before deleting a thread and its chat history."
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
<SettingResetButton
@@ -959,7 +1010,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Text generation model"
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
resetAction={
isGitWritingModelDirty ? (
<SettingResetButton
+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
-1
View File
@@ -3,7 +3,6 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
{ id: "trae", label: "Trae", command: "trae", supportsGoto: true },
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
{
id: "vscode-insiders",
+38 -16
View File
@@ -46,33 +46,55 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
),
Schema.Literal(".run"),
]);
]).annotate({
description: "Command identifier for running a project script, formatted as `script.<id>.run`.",
});
export const KeybindingCommand = Schema.Union([
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
SCRIPT_RUN_COMMAND_PATTERN,
]);
]).annotate({
description: "Command invoked when the keybinding is triggered.",
});
export type KeybindingCommand = typeof KeybindingCommand.Type;
const KeybindingValue = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
const KeybindingValue = TrimmedString.annotate({
description:
"Keyboard shortcut string such as `mod+j`, `ctrl+k`, or `shift+space`, using the T3 Code keybinding syntax.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH));
const KeybindingWhen = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
const KeybindingWhen = TrimmedString.annotate({
description:
"Optional context expression controlling when the keybinding is active, such as `terminalFocus` or `!terminalFocus`.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH));
export const KeybindingRule = Schema.Struct({
key: KeybindingValue,
command: KeybindingCommand,
when: Schema.optional(KeybindingWhen),
key: KeybindingValue.pipe(
Schema.flip,
Schema.annotate({
description: "Keyboard shortcut to listen for.",
}),
Schema.flip,
),
command: KeybindingCommand.pipe(
Schema.annotate({
description: "Command to execute when the shortcut matches.",
}),
),
when: Schema.optional(KeybindingWhen).pipe(
Schema.annotate({
description: "Optional expression limiting when the shortcut is active.",
}),
),
}).annotate({
description: "Single keybinding rule entry in `keybindings.json`.",
});
export type KeybindingRule = typeof KeybindingRule.Type;
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export const KeybindingsConfig = Schema.Array(KeybindingRule)
.check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT))
.annotate({
description: "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
});
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
export const KeybindingShortcut = Schema.Struct({
+37 -6
View File
@@ -9,16 +9,47 @@ export type ClaudeCodeEffort = (typeof CLAUDE_CODE_EFFORT_OPTIONS)[number];
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeCodeEffort;
export const CodexModelOptions = Schema.Struct({
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Codex fast mode when the selected model supports it.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Codex models.",
});
export type CodexModelOptions = typeof CodexModelOptions.Type;
export const ClaudeModelOptions = Schema.Struct({
thinking: Schema.optional(Schema.Boolean),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
thinking: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether Claude should enable extended thinking for the selected model.",
}),
),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Claude fast mode when the selected model supports it.",
}),
),
contextWindow: Schema.optional(Schema.String).pipe(
Schema.annotate({
description:
"Optional Claude context window preset to request for the selected model, if supported.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Claude models.",
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
+41 -7
View File
@@ -42,20 +42,54 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const CodexModelSelection = Schema.Struct({
provider: Schema.Literal("codex"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(CodexModelOptions),
provider: Schema.Literal("codex").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.flip,
Schema.annotate({
description: "The Codex model slug to use for text generation.",
}),
Schema.flip,
),
options: Schema.optionalKey(CodexModelOptions).pipe(
Schema.annotate({
description: "Optional Codex-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Codex provider.",
});
export type CodexModelSelection = typeof CodexModelSelection.Type;
export const ClaudeModelSelection = Schema.Struct({
provider: Schema.Literal("claudeAgent"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(ClaudeModelOptions),
provider: Schema.Literal("claudeAgent").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.flip,
Schema.annotate({
description: "The Claude model slug to use for text generation.",
}),
Schema.flip,
),
options: Schema.optionalKey(ClaudeModelOptions).pipe(
Schema.annotate({
description: "Optional Claude-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Claude provider.",
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]).annotate({
description: "Selects which provider and model T3 Code should use for text generation.",
});
export type ModelSelection = typeof ModelSelection.Type;
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
+80 -28
View File
@@ -23,17 +23,32 @@ export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
const makeTrimmedStringSetting = (description: string) =>
Schema.String.annotate({ description }).pipe(
Schema.decodeTo(TrimmedString, SchemaTransformation.passthrough()),
);
export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
confirmThreadArchive: Schema.Boolean.annotate({
description: "Require a second click on the inline archive action before a thread is archived.",
}).pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.annotate({
description: "Ask before deleting a thread and its chat history.",
}).pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.annotate({
description: "Set the default wrap state when the diff panel opens.",
}).pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.annotate({
description: "Choose how projects are ordered in the sidebar.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
sidebarThreadSortOrder: SidebarThreadSortOrder.annotate({
description: "Choose how threads are ordered inside the selected project.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
timestampFormat: TimestampFormat.annotate({
description: "System default follows your browser or OS clock preference.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
}).annotate({
description: "Client-only settings persisted locally in the browser.",
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -41,11 +56,13 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]).annotate({
description: "Pick the default workspace mode for newly created draft threads.",
});
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
const makeBinaryPathSetting = (fallback: string) =>
TrimmedString.pipe(
const makeBinaryPathSetting = (fallback: string, description: string) =>
makeTrimmedStringSetting(description).pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
@@ -57,26 +74,51 @@ const makeBinaryPathSetting = (fallback: string) =>
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
enabled: Schema.Boolean.annotate({
description: "Whether the Codex provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex", "Path to the Codex binary"),
homePath: makeTrimmedStringSetting("Optional custom Codex home and config directory.").pipe(
Schema.withDecodingDefault(() => ""),
),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Codex model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Codex provider.",
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude"),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
enabled: Schema.Boolean.annotate({
description: "Whether the Claude provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude", "Path to the Claude binary"),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Claude model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Claude provider.",
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
enableAssistantStreaming: Schema.Boolean.annotate({
description: "Show token-by-token output while a response is in progress.",
}).pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.annotate({
description: "Pick the default workspace mode for newly created draft threads.",
}).pipe(Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode)),
textGenerationModelSelection: ModelSelection.annotate({
description:
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
}).pipe(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
@@ -85,9 +127,19 @@ export const ServerSettings = Schema.Struct({
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
codex: CodexSettings.annotate({
description: "Configuration for the Codex provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.annotate({
description: "Configuration for the Claude provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
})
.annotate({
description: "Provider-specific server configuration.",
})
.pipe(Schema.withDecodingDefault(() => ({}))),
}).annotate({
description: "Server-authoritative settings persisted in `settings.json`.",
});
export type ServerSettings = typeof ServerSettings.Type;
+67
View File
@@ -0,0 +1,67 @@
import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { encodePrettyJsonEffect, getSchemaDescription, toJsonSchemaObject } from "./schemaJson";
it.effect("encodePrettyJsonEffect writes indented JSON", () =>
Effect.gen(function* () {
const encodePrettyJson = encodePrettyJsonEffect(
Schema.Struct({
provider: Schema.String,
options: Schema.Struct({
enabled: Schema.Boolean,
}),
}),
);
const encoded = yield* encodePrettyJson({
provider: "codex",
options: {
enabled: true,
},
});
assert.strictEqual(
encoded,
`{
"provider": "codex",
"options": {
"enabled": true
}
}`,
);
}),
);
it.effect("toJsonSchemaObject hoists descriptions from wrapper nodes", () =>
Effect.sync(() => {
const schema = toJsonSchemaObject(
Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the feature is enabled.",
}).pipe(Schema.withDecodingDefault(() => false)),
name: Schema.String.annotate({
description: "Human-readable display name.",
}).check(Schema.isMinLength(1)),
}),
) as Record<string, unknown>;
const properties = schema.properties as Record<string, Record<string, unknown>>;
const enabled = properties.enabled;
const name = properties.name;
assert.isDefined(enabled);
assert.isDefined(name);
assert.strictEqual(enabled.description, "Whether the feature is enabled.");
assert.strictEqual(name.description, "Human-readable display name.");
}),
);
it.effect("getSchemaDescription reads hoisted descriptions from wrapped schemas", () =>
Effect.sync(() => {
const enabled = Schema.Boolean.annotate({
description: "Whether the feature is enabled.",
}).pipe(Schema.withDecodingDefault(() => false));
assert.strictEqual(getSchemaDescription(enabled), "Whether the feature is enabled.");
}),
);
+82
View File
@@ -36,6 +36,22 @@ export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown,
};
};
const schemaDescriptionCache = new WeakMap<object, string | undefined>();
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
export const encodePrettyJsonEffect = <S extends Schema.Top>(schema: S) =>
Schema.encodeEffect(
Schema.fromJsonString(schema).pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
),
);
export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
const squashed = Cause.squash(cause);
return Schema.isSchemaError(squashed)
@@ -43,6 +59,72 @@ export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
: Cause.pretty(cause);
};
function hoistJsonSchemaDescriptions(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(hoistJsonSchemaDescriptions);
}
if (!value || typeof value !== "object") {
return value;
}
const record = Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, hoistJsonSchemaDescriptions(entry)]),
) as Record<string, unknown>;
if (typeof record.description !== "string") {
const candidates = ["allOf", "anyOf", "oneOf"]
.flatMap((key) => (Array.isArray(record[key]) ? (record[key] as ReadonlyArray<unknown>) : []))
.filter((candidate): candidate is Record<string, unknown> => {
return !!candidate && typeof candidate === "object" && !Array.isArray(candidate);
});
const description = candidates.find(
(candidate) =>
typeof candidate.description === "string" &&
!(candidate.type === "null" && Object.keys(candidate).length <= 1),
)?.description;
if (typeof description === "string") {
record.description = description;
}
}
return record;
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export const toJsonSchemaObject = (schema: Schema.Top): unknown => {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return hoistJsonSchemaDescriptions({ ...document.schema, $defs: document.definitions });
}
return hoistJsonSchemaDescriptions(document.schema);
};
export const getSchemaDescription = (schema: Schema.Top): string | undefined => {
if (schema && typeof schema === "object") {
const cached = schemaDescriptionCache.get(schema);
if (cached !== undefined || schemaDescriptionCache.has(schema)) {
return cached;
}
}
const jsonSchema = toJsonSchemaObject(schema);
const description =
jsonSchema && typeof jsonSchema === "object" && !Array.isArray(jsonSchema)
? typeof (jsonSchema as Record<string, unknown>).description === "string"
? ((jsonSchema as Record<string, unknown>).description as string)
: undefined
: undefined;
if (schema && typeof schema === "object") {
schemaDescriptionCache.set(schema, description);
}
return description;
};
/**
* A `Getter` that parses a lenient JSON string (tolerating trailing commas
* and JS-style comments) into an unknown value.
+19
View File
@@ -0,0 +1,19 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
writeKeybindingsJsonSchemas,
} from "./lib/keybindings-schema.ts";
import {
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
writeServerSettingsJsonSchemas,
} from "./lib/server-settings-schema.ts";
const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
writeServerSettingsJsonSchemas({ rootDir });
writeKeybindingsJsonSchemas({ rootDir });
console.log(`Wrote ${SERVER_SETTINGS_SCHEMA_RELATIVE_PATH}`);
console.log(`Wrote ${KEYBINDINGS_SCHEMA_RELATIVE_PATH}`);
+76
View File
@@ -0,0 +1,76 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { type Schema } from "effect";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
const JSON_SCHEMA_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";
export function buildJsonSchemaDocument(
schema: Schema.Top,
options: {
readonly title: string;
readonly description: string;
},
): Record<string, unknown> {
const jsonSchema = toJsonSchemaObject(schema);
if (!jsonSchema || typeof jsonSchema !== "object" || Array.isArray(jsonSchema)) {
throw new Error(
`${options.title} JSON schema must be an object or array JSON schema document.`,
);
}
return {
$schema: JSON_SCHEMA_DRAFT_2020_12,
title: options.title,
description: options.description,
...jsonSchema,
};
}
function writeJsonFileIfChanged(filePath: string, document: Record<string, unknown>): boolean {
const nextContent = `${JSON.stringify(document, null, 2)}\n`;
const previousContent = (() => {
try {
return readFileSync(filePath, "utf8");
} catch {
return null;
}
})();
if (previousContent === nextContent) {
return false;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, nextContent);
return true;
}
export function writeJsonSchemaArtifacts(options: {
readonly rootDir?: string;
readonly version?: string;
readonly latestRelativePath: string;
readonly getVersionedRelativePath: (version: string) => string;
readonly document: Record<string, unknown>;
}): {
readonly changed: boolean;
} {
const rootDir = resolve(options.rootDir ?? process.cwd());
const latestChanged = writeJsonFileIfChanged(
resolve(rootDir, options.latestRelativePath),
options.document,
);
let changed = latestChanged;
if (options.version && latestChanged) {
changed =
writeJsonFileIfChanged(
resolve(rootDir, options.getVersionedRelativePath(options.version)),
options.document,
) || changed;
}
return { changed };
}
+75
View File
@@ -0,0 +1,75 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { describe, expect, it } from "vitest";
import {
buildKeybindingsJsonSchema,
getVersionedKeybindingsSchemaRelativePath,
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
writeKeybindingsJsonSchemas,
} from "./keybindings-schema";
describe("buildKeybindingsJsonSchema", () => {
it("builds a JSON schema document for keybindings.json", () => {
const schema = buildKeybindingsJsonSchema();
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
expect(schema.title).toBe("T3 Code Keybindings");
expect(schema.type).toBe("array");
expect(schema.items).toMatchObject({
description: expect.stringContaining("keybinding rule"),
type: "object",
properties: {
key: {
description: expect.stringContaining("shortcut"),
},
command: {
description: expect.stringContaining("execute"),
},
when: {
description: expect.stringContaining("active"),
},
},
});
});
it("writes latest and versioned schema files", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
try {
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(true);
const latestSchema = JSON.parse(
readFileSync(resolve(rootDir, KEYBINDINGS_SCHEMA_RELATIVE_PATH), "utf8"),
) as Record<string, unknown>;
const versionedSchema = JSON.parse(
readFileSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")), "utf8"),
) as Record<string, unknown>;
expect(latestSchema).toEqual(versionedSchema);
expect(latestSchema.title).toBe("T3 Code Keybindings");
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
try {
const latestOnly = writeKeybindingsJsonSchemas({ rootDir });
expect(latestOnly.changed).toBe(true);
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(false);
expect(existsSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")))).toBe(
false,
);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+31
View File
@@ -0,0 +1,31 @@
import { KeybindingsConfig } from "../../packages/contracts/src/keybindings.ts";
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
export const KEYBINDINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/keybindings.json";
export const KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/keybindings";
export const getVersionedKeybindingsSchemaRelativePath = (version: string) =>
`${KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildKeybindingsJsonSchema(): Record<string, unknown> {
return buildJsonSchemaDocument(KeybindingsConfig, {
title: "T3 Code Keybindings",
description: "JSON Schema for the keybindings.json file consumed by T3 Code.",
});
}
export function writeKeybindingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: KEYBINDINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedKeybindingsSchemaRelativePath,
document: buildKeybindingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
@@ -0,0 +1,82 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { describe, expect, it } from "vitest";
import {
buildServerSettingsJsonSchema,
getVersionedServerSettingsSchemaRelativePath,
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
writeServerSettingsJsonSchemas,
} from "./server-settings-schema";
describe("buildServerSettingsJsonSchema", () => {
it("builds a JSON schema document for settings.json", () => {
const schema = buildServerSettingsJsonSchema();
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
expect(schema.title).toBe("T3 Code Server Settings");
expect(schema.type).toBe("object");
expect(schema.additionalProperties).toBe(false);
expect(schema.properties).toMatchObject({
$schema: {
type: "string",
},
enableAssistantStreaming: {
description: "Show token-by-token output while a response is in progress.",
},
defaultThreadEnvMode: {
description: "Pick the default workspace mode for newly created draft threads.",
},
textGenerationModelSelection: {
description:
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
},
providers: {
description: expect.stringContaining("Provider-specific"),
},
});
});
it("writes latest and versioned schema files", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
try {
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(true);
const latestSchema = JSON.parse(
readFileSync(resolve(rootDir, SERVER_SETTINGS_SCHEMA_RELATIVE_PATH), "utf8"),
) as Record<string, unknown>;
const versionedSchema = JSON.parse(
readFileSync(
resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3")),
"utf8",
),
) as Record<string, unknown>;
expect(latestSchema).toEqual(versionedSchema);
expect(latestSchema.title).toBe("T3 Code Server Settings");
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
try {
const latestOnly = writeServerSettingsJsonSchemas({ rootDir });
expect(latestOnly.changed).toBe(true);
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
expect(result.changed).toBe(false);
expect(
existsSync(resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3"))),
).toBe(false);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+55
View File
@@ -0,0 +1,55 @@
import { ServerSettings } from "@t3tools/contracts/settings";
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
export const SERVER_SETTINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/settings.json";
export const SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/settings";
export const getVersionedServerSettingsSchemaRelativePath = (version: string) =>
`${SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildServerSettingsJsonSchema(): Record<string, unknown> {
const schema = buildJsonSchemaDocument(ServerSettings, {
title: "T3 Code Server Settings",
description: "JSON Schema for the server-authoritative settings.json file consumed by T3 Code.",
});
const properties =
schema.type === "object" &&
schema.properties &&
typeof schema.properties === "object" &&
!Array.isArray(schema.properties)
? schema.properties
: null;
if (!properties) {
throw new Error("ServerSettings JSON schema must expose object properties.");
}
return {
...schema,
properties: {
$schema: {
type: "string",
description:
"Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL.",
},
...properties,
},
};
}
export function writeServerSettingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedServerSettingsSchemaRelativePath,
document: buildServerSettingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
+56 -2
View File
@@ -1,5 +1,13 @@
import { execFileSync } from "node:child_process";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -81,7 +89,7 @@ try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
process.execPath,
"bun",
[
resolve(repoRoot, "scripts/update-release-package-versions.ts"),
"9.9.9-smoke.0",
@@ -106,6 +114,52 @@ try {
"Expected bun.lock to contain the smoke version.",
);
const latestSchemaPath = resolve(tempRoot, "apps/marketing/public/schemas/settings.json");
const versionedSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/settings/9.9.9-smoke.0.json",
);
const latestKeybindingsSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/keybindings.json",
);
const versionedKeybindingsSchemaPath = resolve(
tempRoot,
"apps/marketing/public/schemas/keybindings/9.9.9-smoke.0.json",
);
if (!existsSync(latestSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the latest server settings schema.",
);
}
if (!existsSync(versionedSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the versioned server settings schema.",
);
}
if (!existsSync(latestKeybindingsSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the latest keybindings schema.",
);
}
if (!existsSync(versionedKeybindingsSchemaPath)) {
throw new Error(
"Expected release version alignment to generate the versioned keybindings schema.",
);
}
const versionedSchema = readFileSync(versionedSchemaPath, "utf8");
assertContains(
versionedSchema,
'"title": "T3 Code Server Settings"',
"Expected versioned server settings schema to contain schema metadata.",
);
const versionedKeybindingsSchema = readFileSync(versionedKeybindingsSchemaPath, "utf8");
assertContains(
versionedKeybindingsSchema,
'"title": "T3 Code Keybindings"',
"Expected versioned keybindings schema to contain schema metadata.",
);
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
execFileSync(
process.execPath,
+5 -1
View File
@@ -12,5 +12,9 @@
}
]
},
"include": ["**/*.ts"]
"include": [
"**/*.ts",
"../packages/contracts/src/baseSchemas.ts",
"../packages/contracts/src/keybindings.ts"
]
}
@@ -0,0 +1,101 @@
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { describe, expect, it } from "vitest";
import {
releasePackageFiles,
updateReleasePackageVersions,
} from "./update-release-package-versions";
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema";
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema";
describe("updateReleasePackageVersions", () => {
it("updates package versions and writes latest plus versioned config schemas", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
try {
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(
filePath,
`${JSON.stringify({ name: relativePath, version: "0.0.0" }, null, 2)}\n`,
);
}
const result = updateReleasePackageVersions("1.2.3", { rootDir });
expect(result.changed).toBe(true);
for (const relativePath of releasePackageFiles) {
const packageJson = JSON.parse(readFileSync(resolve(rootDir, relativePath), "utf8")) as {
version?: string;
};
expect(packageJson.version).toBe("1.2.3");
}
expect(
JSON.parse(
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/settings.json"), "utf8"),
),
).toMatchObject({ title: "T3 Code Server Settings" });
expect(
JSON.parse(
readFileSync(
resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json"),
"utf8",
),
),
).toMatchObject({ title: "T3 Code Server Settings" });
expect(
JSON.parse(
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings.json"), "utf8"),
),
).toMatchObject({ title: "T3 Code Keybindings" });
expect(
JSON.parse(
readFileSync(
resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json"),
"utf8",
),
),
).toMatchObject({ title: "T3 Code Keybindings" });
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
it("skips versioned schema snapshots when the latest schemas are unchanged", () => {
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
try {
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(
filePath,
`${JSON.stringify({ name: relativePath, version: "1.2.3" }, null, 2)}\n`,
);
}
writeServerSettingsJsonSchemas({ rootDir });
writeKeybindingsJsonSchemas({ rootDir });
const result = updateReleasePackageVersions("1.2.3", { rootDir });
expect(result.changed).toBe(false);
expect(
existsSync(resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json")),
).toBe(false);
expect(
existsSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json")),
).toBe(false);
} finally {
rmSync(rootDir, { recursive: true, force: true });
}
});
});
+7 -1
View File
@@ -2,6 +2,9 @@ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema.ts";
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema.ts";
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
@@ -37,6 +40,9 @@ export function updateReleasePackageVersions(
changed = true;
}
changed = writeServerSettingsJsonSchemas({ rootDir, version }).changed || changed;
changed = writeKeybindingsJsonSchemas({ rootDir, version }).changed || changed;
return { changed };
}
@@ -99,7 +105,7 @@ if (isMain) {
);
if (!changed) {
console.log("All package.json versions already match release version.");
console.log("All release version artifacts already match the requested version.");
}
if (writeGithubOutput) {