Compare commits

..
Author SHA1 Message Date
Cursor Agent 7ec01e28bd Remove unused runtime parameter from plan helper functions 2026-03-31 07:44:40 +00:00
Julius Marminge 2ade03788b Refactor open service onto Effect-backed process spawning
- Add external opener support alongside browser/editor launches
- Remove the `open` dependency and cover platform behavior in tests
2026-03-31 00:31:41 -07:00
Julius Marminge 48fc85e7fe Bump Effect catalog dependencies (#1594) 2026-03-30 22:08:25 +00:00
37 changed files with 1242 additions and 2367 deletions

No files matched your search

+5 -5
View File
@@ -126,7 +126,7 @@ jobs:
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
@@ -248,7 +248,7 @@ jobs:
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -348,7 +348,7 @@ jobs:
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: bun scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
@@ -364,7 +364,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock; then
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
@@ -372,6 +372,6 @@ jobs:
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
-23
View File
@@ -15,29 +15,6 @@ The file must be a JSON array of rules:
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Editor Schema Support
`keybindings.json` is intentionally a top-level JSON array, so it cannot carry an inline `$schema` property the way `settings.json` can.
To get autocomplete and hover docs in editors like VS Code, associate the file externally with the published schema:
```json
{
"json.schemas": [
{
"fileMatch": ["**/.t3/keybindings.json", "**/keybindings.json"],
"url": "https://t3.codes/schemas/keybindings.json"
}
]
}
```
If you want a pinned schema instead of the latest stable one, use a versioned URL such as:
```text
https://t3.codes/schemas/keybindings/0.0.15.json
```
## Defaults
```json
@@ -1,69 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Keybindings",
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
"type": "array",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Keyboard shortcut to listen for."
},
"command": {
"anyOf": [
{
"type": "string",
"enum": [
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"diff.toggle",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
"thread.previous",
"thread.next",
"thread.jump.1",
"thread.jump.2",
"thread.jump.3",
"thread.jump.4",
"thread.jump.5",
"thread.jump.6",
"thread.jump.7",
"thread.jump.8",
"thread.jump.9"
]
},
{
"type": "string",
"pattern": "^script\\.[\\s\\S]*?\\.run$",
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
}
],
"description": "Command to execute when the shortcut matches."
},
"when": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional expression limiting when the shortcut is active."
}
},
"required": ["key", "command"],
"additionalProperties": false,
"description": "Single keybinding rule entry in `keybindings.json`."
},
"allOf": [
{
"maxItems": 256,
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
}
]
}
@@ -1,69 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Keybindings",
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
"type": "array",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Keyboard shortcut to listen for."
},
"command": {
"anyOf": [
{
"type": "string",
"enum": [
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"diff.toggle",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
"thread.previous",
"thread.next",
"thread.jump.1",
"thread.jump.2",
"thread.jump.3",
"thread.jump.4",
"thread.jump.5",
"thread.jump.6",
"thread.jump.7",
"thread.jump.8",
"thread.jump.9"
]
},
{
"type": "string",
"pattern": "^script\\.[\\s\\S]*?\\.run$",
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
}
],
"description": "Command to execute when the shortcut matches."
},
"when": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional expression limiting when the shortcut is active."
}
},
"required": ["key", "command"],
"additionalProperties": false,
"description": "Single keybinding rule entry in `keybindings.json`."
},
"allOf": [
{
"maxItems": 256,
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
}
]
}
-302
View File
@@ -1,302 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Default execution environment to use when creating new threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["codex"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": ["xhigh", "high", "medium", "low"]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["claudeAgent"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": ["low", "medium", "high", "max", "ultrathink"]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Default provider and model to use for server-side text generation features."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
@@ -1,302 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "T3 Code Server Settings",
"description": "Server-authoritative settings persisted in `settings.json`.",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
},
"enableAssistantStreaming": {
"anyOf": [
{
"type": "boolean",
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
},
{
"type": "null"
}
],
"description": "Show token-by-token output while a response is in progress."
},
"defaultThreadEnvMode": {
"anyOf": [
{
"type": "string",
"enum": ["local", "worktree"],
"description": "Default execution environment to use when creating new threads."
},
{
"type": "null"
}
],
"description": "Pick the default workspace mode for newly created draft threads."
},
"textGenerationModelSelection": {
"anyOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["codex"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Codex model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"reasoningEffort": {
"anyOf": [
{
"type": "string",
"enum": ["xhigh", "high", "medium", "low"]
},
{
"type": "null"
}
],
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Codex fast mode when the selected model supports it."
}
},
"additionalProperties": false,
"description": "Optional Codex-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Codex provider."
},
{
"type": "object",
"properties": {
"provider": {
"type": "string",
"enum": ["claudeAgent"],
"description": "The provider used for text generation."
},
"model": {
"type": "string",
"description": "The Claude model slug to use for text generation."
},
"options": {
"type": "object",
"properties": {
"thinking": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether Claude should enable extended thinking for the selected model."
},
"effort": {
"anyOf": [
{
"type": "string",
"enum": ["low", "medium", "high", "max", "ultrathink"]
},
{
"type": "null"
}
],
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
},
"fastMode": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"description": "Whether to prefer Claude fast mode when the selected model supports it."
},
"contextWindow": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Optional Claude context window preset to request for the selected model, if supported."
}
},
"additionalProperties": false,
"description": "Optional Claude-specific tuning knobs for the selected model."
}
},
"required": ["provider", "model"],
"additionalProperties": false,
"description": "Text generation model selection for the Claude provider."
}
],
"description": "Default provider and model to use for server-side text generation features."
},
{
"type": "null"
}
],
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
},
"providers": {
"anyOf": [
{
"type": "object",
"properties": {
"codex": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Codex provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Codex provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Codex binary"
},
"homePath": {
"anyOf": [
{
"type": "string",
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
},
{
"type": "null"
}
],
"description": "Optional custom Codex home and config directory."
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Codex provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Codex provider."
},
"claudeAgent": {
"anyOf": [
{
"type": "object",
"properties": {
"enabled": {
"anyOf": [
{
"type": "boolean",
"description": "Whether the Claude provider is enabled and available for selection."
},
{
"type": "null"
}
],
"description": "Whether the Claude provider is enabled and available for selection."
},
"binaryPath": {
"anyOf": [
{
"type": "string",
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
},
{
"type": "null"
}
],
"description": "Path to the Claude binary"
},
"customModels": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
},
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
},
{
"type": "null"
}
],
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
}
},
"additionalProperties": false,
"description": "Configuration for the Claude provider."
},
{
"type": "null"
}
],
"description": "Configuration for the Claude provider."
}
},
"additionalProperties": false,
"description": "Provider-specific server configuration."
},
{
"type": "null"
}
],
"description": "Provider-specific server configuration."
}
},
"additionalProperties": false
}
-1
View File
@@ -29,7 +29,6 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
@@ -13,7 +13,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
@@ -28,6 +27,7 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -5,7 +5,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
@@ -27,6 +26,7 @@ import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
+9
View File
@@ -14,6 +14,15 @@ export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
+13 -3
View File
@@ -34,6 +34,7 @@ import {
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
@@ -43,7 +44,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -417,7 +418,16 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -666,7 +676,7 @@ const makeKeybindings = Effect.gen(function* () {
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return encodeKeybindingsConfigPrettyJson(rules).pipe(
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
+2
View File
@@ -51,6 +51,8 @@ const testLayer = Layer.mergeAll(
stopSignal: Effect.void,
} satisfies ServerShape),
Layer.succeed(Open, {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
+536 -247
View File
@@ -1,269 +1,558 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodePath from "@effect/platform-node/NodePath";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import {
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
Deferred,
Effect,
Exit,
FileSystem,
Layer,
PlatformError,
Scope,
Sink,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
import { makeOpenLayer, Open } from "./open";
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const encoder = new TextEncoder();
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
interface SpawnCall {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly detached?: boolean | undefined;
readonly shell?: boolean | string | undefined;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
}
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLaunch, {
command: "code-insiders",
args: ["/tmp/workspace"],
});
function decodePowerShellCommand(encoded: string): string {
return Buffer.from(encoded, "base64").toString("utf16le");
}
const vscodiumLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLaunch, {
command: "codium",
args: ["/tmp/workspace"],
});
function platformSpawnError(message: string) {
return PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "spawn",
description: message,
});
}
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
function spawnerLayer(
calls: Array<SpawnCall>,
handler: (call: SpawnCall) => {
readonly code?: number;
readonly fail?: string;
readonly awaitExit?: Deferred.Deferred<void>;
readonly onKill?: () => void;
} = () => ({
code: 0,
}),
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const standardCommand = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: {
readonly detached?: boolean;
readonly shell?: boolean | string;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
};
};
const call: SpawnCall = {
command: standardCommand.command,
args: [...standardCommand.args],
detached: standardCommand.options.detached,
shell: standardCommand.options.shell,
stdin: standardCommand.options.stdin,
stdout: standardCommand.options.stdout,
stderr: standardCommand.options.stderr,
};
calls.push(call);
const result = handler(call);
if (result.fail) {
return Effect.fail(platformSpawnError(result.fail));
}
let exited = false;
const exitCode = result.awaitExit
? Deferred.await(result.awaitExit).pipe(
Effect.tap(() =>
Effect.sync(() => {
exited = true;
}),
),
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
)
: Effect.sync(() => {
exited = true;
return ChildProcessSpawner.ExitCode(result.code ?? 0);
});
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(calls.length),
exitCode,
isRunning: Effect.succeed(false),
kill: () =>
Effect.sync(() => {
if (!exited) {
result.onKill?.();
}
}),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode("")),
stderr: Stream.make(encoder.encode("")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
}
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLineAndColumn, {
command: "code-insiders",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLineAndColumn, {
command: "codium",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
const provideOpen = (
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
makeOpenLayer(options).pipe(
Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, spawnLayer)),
);
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"darwin",
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
const runOpen = <A>(
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
effect: Effect.Effect<A, Error, Open>,
) => effect.pipe(Effect.provide(provideOpen(options, spawnLayer)));
const launch2 = yield* resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
"win32",
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
const readOpen = Effect.service(Open);
const launch3 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"linux",
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
}),
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: `t3code-no-such-command-${Date.now()}`,
args: [],
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
const writeExecutable = (filePath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
yield* fs.chmod(filePath, 0o755);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
it.effect("getAvailableEditors detects installed editors through the service", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
const editors = yield* open.getAvailableEditors;
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
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");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
const editors = yield* open.getAvailableEditors;
assert.equal(editors.includes("file-manager"), false);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses --goto for editors that support it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
yield* writeExecutable(`${dir}/cursor`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace/src/open.ts:71:5",
editor: "cursor",
});
assert.deepEqual(calls, [
{
command: `${dir}/cursor`,
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor launches Windows batch shims through cmd.exe without shell mode", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
yield* fs.writeFileString(`${dir}/code.cmd`, "@echo off\r\n");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "C:\\work\\100% real\\file.ts:12:4",
editor: "vscode",
});
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, "cmd.exe");
assert.deepEqual(calls[0]?.args.slice(0, 4), ["/d", "/v:off", "/s", "/c"]);
assert.equal(calls[0]?.args[4]?.toLowerCase().includes(`${dir}/code.cmd`.toLowerCase()), true);
assert.equal(calls[0]?.args[4]?.includes('"--goto"'), true);
assert.equal(calls[0]?.args[4]?.includes("100%% real"), true);
assert.equal(calls[0]?.detached, true);
assert.equal(calls[0]?.shell, false);
assert.equal(calls[0]?.stdin, "ignore");
assert.equal(calls[0]?.stdout, "ignore");
assert.equal(calls[0]?.stderr, "ignore");
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor detached launches survive service scope shutdown", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
yield* writeExecutable(`${dir}/zed`);
const calls: Array<SpawnCall> = [];
const exitDeferred = yield* Deferred.make<void>();
let killCount = 0;
yield* Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const runtimeServices = yield* Layer.build(
provideOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls, () => ({
awaitExit: exitDeferred,
onKill: () => {
killCount += 1;
},
})),
),
).pipe(Scope.provide(scope));
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "zed",
});
}),
(scope) => Scope.close(scope, Exit.void),
);
assert.equal(killCount, 0);
assert.deepEqual(calls, [
{
command: `${dir}/zed`,
args: ["/tmp/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
yield* Deferred.succeed(exitDeferred, void 0);
yield* Effect.yieldNow;
assert.equal(killCount, 0);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: ["/tmp/workspace"],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses macOS open flags and app arguments", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com", {
wait: true,
background: true,
newInstance: true,
app: {
name: "google chrome",
arguments: ["--profile-directory=Work"],
},
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: [
"--wait-apps",
"--background",
"--new",
"-a",
"google chrome",
"https://example.com",
"--args",
"--profile-directory=Work",
],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses PowerShell on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
assert.equal(
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
"Start 'https://example.com'",
);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls, (call) =>
call.command.includes("powershell")
? { fail: "powershell unavailable" }
: {
code: 0,
},
),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls[0]?.command.includes("powershell"), true);
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/home/julius/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/xdg-open`,
args: ["/home/julius/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor fails when the editor command is unavailable", () =>
Effect.gen(function* () {
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: "" },
},
spawnerLayer(calls),
readOpen,
);
const error = yield* open
.openInEditor({
cwd: "/tmp/workspace",
editor: "cursor",
})
.pipe(Effect.flip);
assert.equal(error._tag, "OpenError");
assert.equal(error.message, "Command not found: cursor");
assert.deepEqual(calls, []);
}),
);
+575 -171
View File
@@ -1,21 +1,17 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser and workspace
* paths in a configured editor.
* Owns process launch helpers for opening URLs in a browser, workspace paths in
* a configured editor, and generic external targets through the platform's
* default opener.
*
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import os from "node:os";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
// ==============================
// Definitions
// ==============================
import { Effect, Exit, FileSystem, Layer, Option, Path, Schema, Scope, ServiceMap } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
@@ -27,33 +23,66 @@ export interface OpenInEditorInput {
readonly editor: EditorId;
}
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
export interface OpenApplicationInput {
readonly name: string | ReadonlyArray<string>;
readonly arguments?: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
export interface OpenExternalInput {
readonly target: string;
readonly wait?: boolean;
readonly background?: boolean;
readonly newInstance?: boolean;
readonly allowNonzeroExitCode?: boolean;
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
}
export interface OpenRuntimeOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
readonly isWsl?: boolean;
readonly isInsideContainer?: boolean;
readonly powerShellCommand?: string;
}
interface OpenRuntime {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly isWsl: boolean;
readonly isInsideContainer: boolean;
readonly powerShellCandidates: ReadonlyArray<string>;
readonly windowsPathExtensions: ReadonlyArray<string>;
}
interface LaunchPlan {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
}
interface ResolvedCommand {
readonly path: string;
readonly usesCmdWrapper: boolean;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
const WSL_POWERSHELL_CANDIDATES = [
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
"powershell.exe",
"pwsh.exe",
] as const;
const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
@@ -72,19 +101,24 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
runtime: OpenRuntime,
pathService: Path.Path,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
if (runtime.platform !== "win32") return [command];
const extension = pathService.extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
@@ -96,179 +130,549 @@ function resolveCommandCandidates(
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
for (const extensionName of runtime.windowsPathExtensions) {
candidates.push(`${command}${extensionName}`);
candidates.push(`${command}${extensionName.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
if (platform !== "linux") return false;
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
return true;
}
return os.release().toLowerCase().includes("microsoft");
}
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
function quotePowerShellValue(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function encodePowerShellCommand(command: string): string {
return Buffer.from(command, "utf16le").toString("base64");
}
function normalizeAppCandidates(
app: OpenExternalInput["app"],
): ReadonlyArray<{ readonly name: string; readonly arguments: ReadonlyArray<string> } | undefined> {
if (!app) return [undefined];
const apps = Array.isArray(app) ? app : [app];
const candidates: Array<{ readonly name: string; readonly arguments: ReadonlyArray<string> }> =
[];
for (const appDef of apps) {
const names = Array.isArray(appDef.name) ? appDef.name : [appDef.name];
for (const name of names) {
candidates.push({ name, arguments: appDef.arguments ?? [] });
}
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
return candidates;
}
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
function isUriLikeTarget(target: string): boolean {
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
}
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: OpenRuntime): boolean {
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
}
function makeLaunchPlan(
command: string,
args: ReadonlyArray<string>,
options: {
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
},
): LaunchPlan {
return {
command,
args,
wait: options.wait,
allowNonzeroExitCode: options.allowNonzeroExitCode,
shell: options.shell ?? false,
...(options.detached !== undefined ? { detached: options.detached } : {}),
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
};
}
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push(input.target);
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makeDarwinApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push("-a", app.name);
args.push(input.target);
if (app.arguments.length > 0) {
args.push("--args", ...app.arguments);
}
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
const encodedParts = ["Start"];
const wait = input.wait ?? false;
if (wait) encodedParts.push("-Wait");
encodedParts.push(quotePowerShellValue(input.target));
return makeLaunchPlan(
powerShellCommand,
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodePowerShellCommand(encodedParts.join(" ")),
],
{
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
},
);
}
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
const wait = input.wait ?? false;
return makeLaunchPlan("xdg-open", [input.target], {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
detached: !wait,
...(wait ? {} : { stdio: "ignore" as const }),
shell: false,
});
}
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
return makeLaunchPlan("explorer", [input.target], {
wait: false,
allowNonzeroExitCode: false,
shell: false,
});
}
function makeDirectApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
wait: input.wait ?? false,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function resolveExternalPlans(
input: OpenExternalInput,
runtime: OpenRuntime,
): ReadonlyArray<LaunchPlan> {
const appCandidates = normalizeAppCandidates(input.app);
const plans: LaunchPlan[] = [];
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
for (const app of appCandidates) {
if (app) {
if (runtime.platform === "darwin") {
plans.push(makeDarwinApplicationPlan(input, app));
} else {
plans.push(makeDirectApplicationPlan(input, app));
}
continue;
}
if (runtime.platform === "darwin") {
plans.push(makeDarwinDefaultPlan(input));
continue;
}
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
for (const powerShellCommand of runtime.powerShellCandidates) {
plans.push(makePowerShellPlan(input, powerShellCommand));
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
const command = editor.command ?? fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
if (runtime.platform === "win32") {
if (!(input.wait ?? false)) {
plans.push(makeWindowsExplorerPlan(input));
}
continue;
}
plans.push(makeLinuxDefaultPlan(input));
}
return available;
return plans;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
export interface OpenShape {
/**
* Open a URL target in the default browser.
*/
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
function toOpenError(message: string, cause: unknown): OpenError {
return new OpenError({ message, cause });
}
/**
* Open a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean {
return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never);
}
function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray<string>): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
}
export interface OpenShape {
readonly getAvailableEditors: Effect.Effect<ReadonlyArray<EditorId>, OpenError>;
readonly openExternal: (input: OpenExternalInput) => Effect.Effect<void, OpenError>;
readonly openBrowser: (
target: string,
options?: Omit<OpenExternalInput, "target">,
) => Effect.Effect<void, OpenError>;
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
}
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
const makeOpen = (options: OpenRuntimeOptions = {}) =>
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
const isInsideContainer =
options.isInsideContainer ??
(typeof options.env?.CONTAINER === "string" ||
typeof options.env?.container === "string" ||
typeof options.env?.KUBERNETES_SERVICE_HOST === "string"
? true
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
const runtime: OpenRuntime = {
platform: options.platform ?? process.platform,
env: options.env ?? process.env,
isWsl:
options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env),
isInsideContainer,
powerShellCandidates:
options.powerShellCommand !== undefined
? [options.powerShellCommand]
: (options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env))
? WSL_POWERSHELL_CANDIDATES
: WINDOWS_POWERSHELL_CANDIDATES,
windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env),
};
const resolveCommand = Effect.fn(function* (
command: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const candidates = resolveCommandCandidates(command, runtime, pathService);
const resolveExecutableFile = Effect.fn(function* (
filePath: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
if (runtime.platform === "win32") {
const extension = pathService.extname(filePath);
if (
extension.length === 0 ||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
) {
return Option.none();
}
return Option.some({
path: filePath,
usesCmdWrapper: isWindowsBatchShim(pathService, filePath),
} satisfies ResolvedCommand);
}
return (info.value.mode & 0o111) !== 0
? Option.some({
path: filePath,
usesCmdWrapper: false,
} satisfies ResolvedCommand)
: Option.none();
});
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(candidate);
if (Option.isSome(resolved)) return resolved;
}
return Option.none();
}
const pathValue = resolvePathEnvironmentVariable(runtime.env);
if (pathValue.length === 0) return Option.none();
const pathEntries = pathValue
.split(resolvePathDelimiter(runtime.platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
if (Option.isSome(resolved)) {
return resolved;
}
}
}
return Option.none();
});
const commandAvailable = (command: string) =>
resolveCommand(command).pipe(Effect.map(Option.isSome));
const fileManagerAvailable = Effect.gen(function* () {
const candidates =
runtime.platform === "darwin"
? ["open"]
: runtime.platform === "win32"
? [...runtime.powerShellCandidates, "explorer"]
: ["xdg-open"];
for (const candidate of candidates) {
if (yield* commandAvailable(candidate)) {
return true;
}
}
return false;
});
const getAvailableEditors = Effect.gen(function* () {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.id === "file-manager") {
if (yield* fileManagerAvailable) {
available.push(editor.id);
}
continue;
}
if (editor.command && (yield* commandAvailable(editor.command))) {
available.push(editor.id);
}
}
return available as ReadonlyArray<EditorId>;
}).pipe(Effect.mapError((cause) => toOpenError("Failed to resolve available editors", cause)));
const spawnPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
spawner
.spawn(
ChildProcess.make(
resolvedCommand.usesCmdWrapper
? resolveWindowsCommandShell(runtime.env)
: resolvedCommand.path,
resolvedCommand.usesCmdWrapper
? [
"/d",
"/v:off",
"/s",
"/c",
makeWindowsCmdCommandLine(resolvedCommand.path, plan.args),
]
: [...plan.args],
{
detached: plan.detached,
shell: plan.shell,
...(plan.stdio === "ignore"
? {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
}
: {}),
},
),
)
.pipe(Effect.mapError((cause) => toOpenError(failureMessage, cause)));
const waitForExit = (
plan: LaunchPlan,
failureMessage: string,
handle: ChildProcessSpawner.ChildProcessHandle,
) =>
handle.exitCode.pipe(
Effect.flatMap((exitCode) =>
!plan.allowNonzeroExitCode && (exitCode as number) !== 0
? Effect.fail(
new OpenError({
message: `${failureMessage} (code=${exitCode as number})`,
}),
)
: Effect.void,
),
Effect.mapError((cause) => toOpenError(failureMessage, cause)),
);
const runWaitedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(scope),
);
yield* waitForExit(plan, failureMessage, handle);
}),
(scope) => Scope.close(scope, Exit.void),
);
const runDetachedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.gen(function* () {
const childScope = yield* Scope.make("sequential");
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(childScope),
Effect.catch((error) =>
Scope.close(childScope, Exit.void).pipe(Effect.andThen(Effect.fail(error))),
),
);
const releaseOnExit: Effect.Effect<void, never> = handle.exitCode.pipe(
Effect.ignoreCause,
Effect.ensuring(Scope.close(childScope, Exit.void)),
);
yield* Effect.forkDetach(releaseOnExit);
});
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, failureMessage: string) =>
plan.wait
? runWaitedPlan(plan, resolvedCommand, failureMessage)
: runDetachedPlan(plan, resolvedCommand, failureMessage);
const runFirstAvailablePlan = (
plans: ReadonlyArray<LaunchPlan>,
failureMessage: string,
): Effect.Effect<void, OpenError> => {
const [first, ...rest] = plans;
if (!first) {
return Effect.fail(new OpenError({ message: failureMessage }));
}
return resolveCommand(first.command).pipe(
Effect.flatMap((resolvedCommand) => {
if (Option.isNone(resolvedCommand)) {
return rest.length === 0
? Effect.fail(new OpenError({ message: `Command not found: ${first.command}` }))
: runFirstAvailablePlan(rest, failureMessage);
}
return runPlan(first, resolvedCommand.value, failureMessage).pipe(
Effect.catch((error) =>
rest.length === 0 ? Effect.fail(error) : runFirstAvailablePlan(rest, failureMessage),
),
);
}),
);
};
const openExternal = (input: OpenExternalInput) => {
if (input.target.trim().length === 0) {
return Effect.fail(new OpenError({ message: "Open target must not be empty" }));
}
return runFirstAvailablePlan(
resolveExternalPlans(input, runtime),
`Failed to open ${input.target}`,
);
};
const openInEditor = (input: OpenInEditorInput) => {
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
if (!editor) {
return Effect.fail(new OpenError({ message: `Unknown editor: ${input.editor}` }));
}
if (editor.command) {
return runFirstAvailablePlan(
[
makeLaunchPlan(
editor.command,
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
{
wait: false,
allowNonzeroExitCode: false,
detached: true,
stdio: "ignore",
shell: false,
},
),
],
`Failed to open ${input.cwd} in ${input.editor}`,
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
return openExternal({ target: input.cwd });
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
return {
getAvailableEditors,
openExternal,
openBrowser: (target, openOptions = {}) => openExternal({ ...openOptions, target }),
openInEditor,
} satisfies OpenShape;
});
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
export const makeOpenLayer = (options: OpenRuntimeOptions = {}) =>
Layer.effect(Open, makeOpen(options));
return {
openBrowser: (target) =>
Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
export const OpenLive = Layer.effect(Open, make);
export const OpenLive = makeOpenLayer();
-46
View File
@@ -216,50 +216,4 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves a top-level $schema declaration when rewriting settings", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(
serverConfig.settingsPath,
`${JSON.stringify(
{
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
},
},
null,
2,
)}\n`,
);
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.start;
yield* serverSettings.updateSettings({
providers: {
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
},
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+2 -33
View File
@@ -39,7 +39,7 @@ import {
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
@@ -101,9 +101,6 @@ export class ServerSettingsService extends ServiceMap.Service<
}
const ServerSettingsJson = fromLenientJson(ServerSettings);
const UnknownJson = fromLenientJson(Schema.Unknown);
const encodeServerSettingsDocument = encodePrettyJsonEffect(Schema.Unknown);
const SETTINGS_SCHEMA_DECLARATION_KEY = "$schema";
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
@@ -180,7 +177,6 @@ const makeServerSettings = Effect.gen(function* () {
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
const schemaDeclarationRef = yield* Ref.make<string | undefined>(undefined);
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
@@ -211,27 +207,10 @@ const makeServerSettings = Effect.gen(function* () {
const loadSettingsFromDisk = Effect.gen(function* () {
if (!(yield* readConfigExists)) {
yield* Ref.set(schemaDeclarationRef, undefined);
return DEFAULT_SERVER_SETTINGS;
}
const raw = yield* readRawConfig;
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
if (rawJson._tag === "Success") {
const value = rawJson.value;
const valueRecord =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
const schemaDeclaration =
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
: undefined;
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
} else {
yield* Ref.set(schemaDeclarationRef, undefined);
}
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -253,17 +232,7 @@ const makeServerSettings = Effect.gen(function* () {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return Ref.get(schemaDeclarationRef).pipe(
Effect.map((schemaDeclaration) =>
schemaDeclaration
? {
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
...sparseSettings,
}
: sparseSettings,
),
Effect.flatMap(encodeServerSettingsDocument),
Effect.map((encoded) => `${encoded}\n`),
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
+6
View File
@@ -63,6 +63,8 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const defaultOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () => Effect.void,
};
@@ -1030,6 +1032,8 @@ describe("WebSocket Server", () => {
it("routes shell.openInEditor through the injected open service", async () => {
const openCalls: Array<{ cwd: string; editor: string }> = [];
const openService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: (input) => {
openCalls.push({ cwd: input.cwd, editor: input.editor });
@@ -1531,6 +1535,8 @@ describe("WebSocket Server", () => {
process.on("unhandledRejection", onUnhandledRejection);
const brokenOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () =>
Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)),
+6 -3
View File
@@ -58,7 +58,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
import { Open } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
@@ -250,7 +250,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const open = yield* Open;
const availableEditors = yield* open.getAvailableEditors.pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })),
);
const runtimeServices = yield* Effect.services<
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
@@ -615,7 +618,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = yield* Open;
const { openInEditor } = open;
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
@@ -12,19 +12,14 @@ import {
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ClaudeSettings,
ClientSettingsSchema,
CodexSettings,
PROVIDER_DISPLAY_NAMES,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
ServerSettings,
ThreadId,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { getSchemaDescription } from "@t3tools/shared/schemaJson";
import { Equal } from "effect";
import { APP_VERSION } from "../../branding";
import {
@@ -86,51 +81,6 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
function requireSchemaDescription(
schema: Parameters<typeof getSchemaDescription>[0],
label: string,
) {
const description = getSchemaDescription(schema);
if (!description) {
throw new Error(`Missing schema description for ${label}`);
}
return description;
}
const SETTINGS_DESCRIPTIONS = {
timestampFormat: requireSchemaDescription(
ClientSettingsSchema.fields.timestampFormat,
"ClientSettings.timestampFormat",
),
diffWordWrap: requireSchemaDescription(
ClientSettingsSchema.fields.diffWordWrap,
"ClientSettings.diffWordWrap",
),
confirmThreadArchive: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadArchive,
"ClientSettings.confirmThreadArchive",
),
confirmThreadDelete: requireSchemaDescription(
ClientSettingsSchema.fields.confirmThreadDelete,
"ClientSettings.confirmThreadDelete",
),
enableAssistantStreaming: requireSchemaDescription(
ServerSettings.fields.enableAssistantStreaming,
"ServerSettings.enableAssistantStreaming",
),
defaultThreadEnvMode: requireSchemaDescription(
ServerSettings.fields.defaultThreadEnvMode,
"ServerSettings.defaultThreadEnvMode",
),
textGenerationModelSelection: requireSchemaDescription(
ServerSettings.fields.textGenerationModelSelection,
"ServerSettings.textGenerationModelSelection",
),
codexBinaryPath: requireSchemaDescription(CodexSettings.fields.binaryPath, "Codex.binaryPath"),
codexHomePath: requireSchemaDescription(CodexSettings.fields.homePath, "Codex.homePath"),
claudeBinaryPath: requireSchemaDescription(ClaudeSettings.fields.binaryPath, "Claude.binaryPath"),
} as const;
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
type InstallProviderSettings = {
@@ -148,16 +98,16 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
provider: "codex",
title: "Codex",
binaryPlaceholder: "Codex binary path",
binaryDescription: SETTINGS_DESCRIPTIONS.codexBinaryPath,
binaryDescription: "Path to the Codex binary",
homePathKey: "codexHomePath",
homePlaceholder: "CODEX_HOME",
homeDescription: SETTINGS_DESCRIPTIONS.codexHomePath,
homeDescription: "Optional custom Codex home and config directory.",
},
{
provider: "claudeAgent",
title: "Claude",
binaryPlaceholder: "Claude binary path",
binaryDescription: SETTINGS_DESCRIPTIONS.claudeBinaryPath,
binaryDescription: "Path to the Claude binary",
},
] as const;
@@ -824,7 +774,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Time format"
description={SETTINGS_DESCRIPTIONS.timestampFormat}
description="System default follows your browser or OS clock preference."
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
<SettingResetButton
@@ -866,7 +816,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Diff line wrapping"
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
description="Set the default wrap state when the diff panel opens."
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
<SettingResetButton
@@ -890,7 +840,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Assistant output"
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
description="Show token-by-token output while a response is in progress."
resetAction={
settings.enableAssistantStreaming !==
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
@@ -917,7 +867,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="New threads"
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
description="Pick the default workspace mode for newly created draft threads."
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
<SettingResetButton
@@ -958,7 +908,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Archive confirmation"
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
description="Require a second click on the inline archive action before a thread is archived."
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
<SettingResetButton
@@ -984,7 +934,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Delete confirmation"
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
description="Ask before deleting a thread and its chat history."
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
<SettingResetButton
@@ -1010,7 +960,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
title="Text generation model"
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
resetAction={
isGitWritingModelDirty ? (
<SettingResetButton
+11 -26
View File
@@ -54,7 +54,6 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
"devDependencies": {
@@ -176,13 +175,13 @@
"vite": "^8.0.0",
},
"catalog": {
"@effect/language-service": "0.84.1",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@effect/language-service": "0.84.2",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"effect": "4.0.0-beta.42",
"effect": "4.0.0-beta.43",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
@@ -268,15 +267,15 @@
"@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],
"@effect/language-service": ["@effect/[email protected].1", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-YUqjJU24HeYgPV453cR2fDqkZ+zZKMuxGnmxWAPscWJ6gt6FB7JZohMCOczRTIOGPrQMcloJX7BjCaPu+RNhpw=="],
"@effect/language-service": ["@effect/[email protected].2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="],
"@effect/platform-node": ["@effect/[email protected]2", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.42", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42", "ioredis": "^5.7.0" } }, "sha512-kbdRML2FBa4q8U8rZQcnmLKZ5zN/z1bAA7t5D1/UsBHZqJgnfRgu1CP6kaEfb1Nie6YyaWshxTktZQryjvW/Yg=="],
"@effect/platform-node": ["@effect/[email protected]3", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43", "ioredis": "^5.7.0" } }, "sha512-Uq6E1rjaIpjHauzjwoB2HzAg3battYt2Boy8XO50GoHiWCXKE6WapYZ0/AnaBx5v5qg2sOfqpuiLsUf9ZgxOkA=="],
"@effect/platform-node-shared": ["@effect/[email protected]2", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-PC+lxLsrwob3+nBChAPrQq32olCeyApgXBvs1NrRsoArLViNT76T/68CttuCAksCZj5e1bZ1ZibLPel3vUmx2g=="],
"@effect/platform-node-shared": ["@effect/[email protected]3", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-A9q0GEb61pYcQ06Dr6gXj1nKlDI3KHsar1sk3qb1ZY+kVSR64tBAylI8zGon23KY+NPtTUj/sEIToB7jc3Qt5w=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-Ah2QfkeV+I9r5OBVJijSDnFXCv51giBXngSwhju5gefc0uWiM3G1tsYAqrNX24HlvFFEnOAZqNf/Sq1h4NqOAA=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-Ryb7x0rBjW5NHegbzvz9y2Yv4KpwZ1UiPk7/Rv+Mkux74Qkjdmotmrvy9P+M5A9TZyL2Av+GpaLTPJKsL0PG+Q=="],
"@effect/vitest": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-/11arjUnCRhIrBRvOn/nrbg5p/FadjAPvStddZlpl1VrCxtB2s0n39cbG9uTyDdf1ZrRBG73Upo1ZDF1CTWy8w=="],
"@effect/vitest": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-XN2LAwiUWPqbV2jrsYYRjrVydQ8MIgwr83MVImtUaOQco4vk43+8OHlXQMRN/u2HnGK29KT+O2yTMMBdk2Q6Sw=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -896,8 +895,6 @@
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"cacheable-lookup": ["[email protected]", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
@@ -972,16 +969,10 @@
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"defu": ["[email protected]", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="],
@@ -1020,7 +1011,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"effect": ["[email protected]2", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-c1UrRP+tLzyHb4Fepl8XBDJlLQLkrcMXrRBba441GQRxMbeQ/aIOSFcBwSda1iMJ5l9F0lYc3Bhe33/whrmavQ=="],
"effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
@@ -1462,8 +1453,6 @@
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
@@ -1598,8 +1587,6 @@
"rolldown-plugin-dts": ["[email protected]", "", { "dependencies": { "@babel/generator": "8.0.0-rc.2", "@babel/helper-validator-identifier": "8.0.0-rc.2", "@babel/parser": "8.0.0-rc.2", "@babel/types": "8.0.0-rc.2", "ast-kit": "^3.0.0-beta.1", "birpc": "^4.0.0", "dts-resolver": "^2.1.3", "get-tsconfig": "^4.13.6", "obug": "^2.1.1" }, "peerDependencies": { "@ts-macro/tsc": "^0.3.6", "@typescript/native-preview": ">=7.0.0-dev.20250601.1", "rolldown": "^1.0.0-rc.3", "typescript": "^5.0.0 || ^6.0.0-beta", "vue-tsc": "~3.2.0" }, "optionalPeers": ["@ts-macro/tsc", "@typescript/native-preview", "typescript", "vue-tsc"] }, "sha512-M/HXfM4cboo+jONx9Z0X+CUf3B5tCi7ni+kR5fUW50Fp9AlZk0oVLesibGWgCXDKFp5lpgQ9yhKoImUFjl3VZw=="],
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
@@ -1856,8 +1843,6 @@
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
-2
View File
@@ -17,8 +17,6 @@ This document covers how to run desktop releases from one tag, first without sig
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
- Signing is optional and auto-detected per platform from secrets.
- Refreshes the marketing-site JSON Schemas for `settings.json` and `keybindings.json` at `/schemas/settings.json` and `/schemas/keybindings.json`.
- Commits immutable versioned JSON Schema copies at `/schemas/settings/<version>.json` and `/schemas/keybindings/<version>.json`.
## Desktop auto-update notes
+5 -5
View File
@@ -8,11 +8,11 @@
"scripts"
],
"catalog": {
"effect": "4.0.0-beta.42",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@effect/language-service": "0.84.1",
"effect": "4.0.0-beta.43",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@effect/language-service": "0.84.2",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"tsdown": "^0.20.3",
+16 -36
View File
@@ -46,53 +46,33 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
),
Schema.Literal(".run"),
]).annotate({
description: "Command identifier for running a project script, formatted as `script.<id>.run`.",
});
]);
export const KeybindingCommand = Schema.Union([
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
SCRIPT_RUN_COMMAND_PATTERN,
]).annotate({
description: "Command invoked when the keybinding is triggered.",
});
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;
const KeybindingValue = TrimmedString.annotate({
description:
"Keyboard shortcut string such as `mod+j`, `ctrl+k`, or `shift+space`, using the T3 Code keybinding syntax.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH));
const KeybindingValue = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
const KeybindingWhen = TrimmedString.annotate({
description:
"Optional context expression controlling when the keybinding is active, such as `terminalFocus` or `!terminalFocus`.",
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH));
const KeybindingWhen = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
export const KeybindingRule = Schema.Struct({
key: KeybindingValue.pipe(
Schema.annotate({
description: "Keyboard shortcut to listen for.",
}),
),
command: KeybindingCommand.pipe(
Schema.annotate({
description: "Command to execute when the shortcut matches.",
}),
),
when: Schema.optional(KeybindingWhen).pipe(
Schema.annotate({
description: "Optional expression limiting when the shortcut is active.",
}),
),
}).annotate({
description: "Single keybinding rule entry in `keybindings.json`.",
key: KeybindingValue,
command: KeybindingCommand,
when: Schema.optional(KeybindingWhen),
});
export type KeybindingRule = typeof KeybindingRule.Type;
export const KeybindingsConfig = Schema.Array(KeybindingRule)
.check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT))
.annotate({
description: "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
});
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
export const KeybindingShortcut = Schema.Struct({
+6 -37
View File
@@ -9,47 +9,16 @@ export type ClaudeCodeEffort = (typeof CLAUDE_CODE_EFFORT_OPTIONS)[number];
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeCodeEffort;
export const CodexModelOptions = Schema.Struct({
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Codex fast mode when the selected model supports it.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Codex models.",
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
});
export type CodexModelOptions = typeof CodexModelOptions.Type;
export const ClaudeModelOptions = Schema.Struct({
thinking: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether Claude should enable extended thinking for the selected model.",
}),
),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)).pipe(
Schema.annotate({
description:
"Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning.",
}),
),
fastMode: Schema.optional(Schema.Boolean).pipe(
Schema.annotate({
description: "Whether to prefer Claude fast mode when the selected model supports it.",
}),
),
contextWindow: Schema.optional(Schema.String).pipe(
Schema.annotate({
description:
"Optional Claude context window preset to request for the selected model, if supported.",
}),
),
}).annotate({
description: "Provider-specific text generation options for Claude models.",
thinking: Schema.optional(Schema.Boolean),
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
fastMode: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
+7 -37
View File
@@ -46,50 +46,20 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const CodexModelSelection = Schema.Struct({
provider: Schema.Literal("codex").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.annotate({
description: "The Codex model slug to use for text generation.",
}),
),
options: Schema.optionalKey(CodexModelOptions).pipe(
Schema.annotate({
description: "Optional Codex-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Codex provider.",
provider: Schema.Literal("codex"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(CodexModelOptions),
});
export type CodexModelSelection = typeof CodexModelSelection.Type;
export const ClaudeModelSelection = Schema.Struct({
provider: Schema.Literal("claudeAgent").pipe(
Schema.annotate({
description: "The provider used for text generation.",
}),
),
model: TrimmedNonEmptyString.pipe(
Schema.annotate({
description: "The Claude model slug to use for text generation.",
}),
),
options: Schema.optionalKey(ClaudeModelOptions).pipe(
Schema.annotate({
description: "Optional Claude-specific tuning knobs for the selected model.",
}),
),
}).annotate({
description: "Text generation model selection for the Claude provider.",
provider: Schema.Literal("claudeAgent"),
model: TrimmedNonEmptyString,
options: Schema.optionalKey(ClaudeModelOptions),
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]).annotate({
description: "Selects which provider and model T3 Code should use for text generation.",
});
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
export type ModelSelection = typeof ModelSelection.Type;
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
+28 -80
View File
@@ -23,32 +23,17 @@ export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
const makeTrimmedStringSetting = (description: string) =>
Schema.String.annotate({ description }).pipe(
Schema.decodeTo(TrimmedString, SchemaTransformation.passthrough()),
);
export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.annotate({
description: "Require a second click on the inline archive action before a thread is archived.",
}).pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.annotate({
description: "Ask before deleting a thread and its chat history.",
}).pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.annotate({
description: "Set the default wrap state when the diff panel opens.",
}).pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.annotate({
description: "Choose how projects are ordered in the sidebar.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
sidebarThreadSortOrder: SidebarThreadSortOrder.annotate({
description: "Choose how threads are ordered inside the selected project.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
timestampFormat: TimestampFormat.annotate({
description: "System default follows your browser or OS clock preference.",
}).pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
}).annotate({
description: "Client-only settings persisted locally in the browser.",
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -56,13 +41,11 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]).annotate({
description: "Pick the default workspace mode for newly created draft threads.",
});
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
const makeBinaryPathSetting = (fallback: string, description: string) =>
makeTrimmedStringSetting(description).pipe(
const makeBinaryPathSetting = (fallback: string) =>
TrimmedString.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
@@ -74,51 +57,26 @@ const makeBinaryPathSetting = (fallback: string, description: string) =>
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the Codex provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex", "Path to the Codex binary"),
homePath: makeTrimmedStringSetting("Optional custom Codex home and config directory.").pipe(
Schema.withDecodingDefault(() => ""),
),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Codex model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Codex provider.",
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.annotate({
description: "Whether the Claude provider is enabled and available for selection.",
}).pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude", "Path to the Claude binary"),
customModels: Schema.Array(Schema.String)
.annotate({
description:
"Additional Claude model slugs to surface in the UI alongside discovered defaults.",
})
.pipe(Schema.withDecodingDefault(() => [])),
}).annotate({
description: "Server-side configuration for the Claude provider.",
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude"),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.annotate({
description: "Show token-by-token output while a response is in progress.",
}).pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.annotate({
description: "Pick the default workspace mode for newly created draft threads.",
}).pipe(Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode)),
textGenerationModelSelection: ModelSelection.annotate({
description:
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
}).pipe(
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
@@ -127,19 +85,9 @@ export const ServerSettings = Schema.Struct({
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.annotate({
description: "Configuration for the Codex provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.annotate({
description: "Configuration for the Claude provider.",
}).pipe(Schema.withDecodingDefault(() => ({}))),
})
.annotate({
description: "Provider-specific server configuration.",
})
.pipe(Schema.withDecodingDefault(() => ({}))),
}).annotate({
description: "Server-authoritative settings persisted in `settings.json`.",
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
-67
View File
@@ -1,67 +0,0 @@
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,22 +36,6 @@ 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)
@@ -59,72 +43,6 @@ 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
@@ -1,19 +0,0 @@
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}`);
-136
View File
@@ -1,136 +0,0 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { type Schema } from "effect";
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
const JSON_SCHEMA_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";
export function buildJsonSchemaDocument(
schema: Schema.Top,
options: {
readonly title: string;
readonly description: string;
},
): Record<string, unknown> {
const jsonSchema = toJsonSchemaObject(schema);
if (!jsonSchema || typeof jsonSchema !== "object" || Array.isArray(jsonSchema)) {
throw new Error(
`${options.title} JSON schema must be an object or array JSON schema document.`,
);
}
return {
$schema: JSON_SCHEMA_DRAFT_2020_12,
title: options.title,
description: options.description,
...jsonSchema,
};
}
export const asJsonSchemaRecord = (value: unknown): Record<string, unknown> | null =>
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
export const getJsonSchemaProperty = (
schema: Record<string, unknown>,
propertyName: string,
): Record<string, unknown> | null => {
const properties = asJsonSchemaRecord(schema.properties);
return properties ? asJsonSchemaRecord(properties[propertyName]) : null;
};
export const getNullableJsonSchemaBranch = (
schema: Record<string, unknown> | null,
): Record<string, unknown> | null => {
if (!schema) {
return null;
}
const anyOf = Array.isArray(schema.anyOf) ? schema.anyOf : null;
if (!anyOf) {
return schema;
}
for (const entry of anyOf) {
const branch = asJsonSchemaRecord(entry);
if (!branch || branch.type === "null") {
continue;
}
return branch;
}
return null;
};
export const getJsonSchemaAnyOfBranches = (
schema: Record<string, unknown> | null,
): ReadonlyArray<Record<string, unknown>> => {
if (!schema || !Array.isArray(schema.anyOf)) {
return [];
}
return schema.anyOf
.map(asJsonSchemaRecord)
.filter(
(branch): branch is Record<string, unknown> => branch !== null && branch.type !== "null",
);
};
export const setJsonSchemaDescription = (
schema: Record<string, unknown> | null,
description: string,
): void => {
if (!schema) {
return;
}
schema.description = description;
};
function writeJsonFileIfChanged(filePath: string, document: Record<string, unknown>): boolean {
const nextContent = `${JSON.stringify(document, null, 2)}\n`;
const previousContent = (() => {
try {
return readFileSync(filePath, "utf8");
} catch {
return null;
}
})();
if (previousContent === nextContent) {
return false;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, nextContent);
return true;
}
export function writeJsonSchemaArtifacts(options: {
readonly rootDir?: string;
readonly version?: string;
readonly latestRelativePath: string;
readonly getVersionedRelativePath: (version: string) => string;
readonly document: Record<string, unknown>;
}): {
readonly changed: boolean;
} {
const rootDir = resolve(options.rootDir ?? process.cwd());
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
@@ -1,75 +0,0 @@
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 });
}
});
});
-57
View File
@@ -1,57 +0,0 @@
import { KeybindingsConfig } from "@t3tools/contracts";
import {
buildJsonSchemaDocument,
getJsonSchemaProperty,
setJsonSchemaDescription,
writeJsonSchemaArtifacts,
} from "./json-schema";
export const KEYBINDINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/keybindings.json";
export const KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/keybindings";
export const getVersionedKeybindingsSchemaRelativePath = (version: string) =>
`${KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildKeybindingsJsonSchema(): Record<string, unknown> {
const schema = buildJsonSchemaDocument(KeybindingsConfig, {
title: "T3 Code Keybindings",
description: "JSON Schema for the keybindings.json file consumed by T3 Code.",
});
const items =
schema.items && typeof schema.items === "object" && !Array.isArray(schema.items)
? (schema.items as Record<string, unknown>)
: null;
setJsonSchemaDescription(items, "Single keybinding rule entry in `keybindings.json`.");
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "key"),
"Keyboard shortcut to listen for.",
);
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "command"),
"Command to execute when the shortcut matches.",
);
setJsonSchemaDescription(
getJsonSchemaProperty(items ?? {}, "when"),
"Optional expression limiting when the shortcut is active.",
);
return schema;
}
export function writeKeybindingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: KEYBINDINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedKeybindingsSchemaRelativePath,
document: buildKeybindingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
@@ -1,82 +0,0 @@
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 });
}
});
});
-126
View File
@@ -1,126 +0,0 @@
import { ServerSettings } from "@t3tools/contracts/settings";
import {
buildJsonSchemaDocument,
getJsonSchemaAnyOfBranches,
getJsonSchemaProperty,
getNullableJsonSchemaBranch,
setJsonSchemaDescription,
writeJsonSchemaArtifacts,
} from "./json-schema";
export const SERVER_SETTINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/settings.json";
export const SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
"apps/marketing/public/schemas/settings";
export const getVersionedServerSettingsSchemaRelativePath = (version: string) =>
`${SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
export function buildServerSettingsJsonSchema(): Record<string, unknown> {
const schema = buildJsonSchemaDocument(ServerSettings, {
title: "T3 Code Server Settings",
description: "JSON Schema for the server-authoritative settings.json file consumed by T3 Code.",
});
const properties =
schema.type === "object" &&
schema.properties &&
typeof schema.properties === "object" &&
!Array.isArray(schema.properties)
? schema.properties
: null;
if (!properties) {
throw new Error("ServerSettings JSON schema must expose object properties.");
}
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "enableAssistantStreaming")),
"Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "defaultThreadEnvMode")),
"Default execution environment to use when creating new threads.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "textGenerationModelSelection")),
"Default provider and model to use for server-side text generation features.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "providers")),
"Provider-specific server configuration.",
);
const providersBranch = getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "providers"));
const codexBranch = getNullableJsonSchemaBranch(
getJsonSchemaProperty(providersBranch ?? {}, "codex"),
);
const claudeBranch = getNullableJsonSchemaBranch(
getJsonSchemaProperty(providersBranch ?? {}, "claudeAgent"),
);
setJsonSchemaDescription(codexBranch, "Configuration for the Codex provider.");
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(codexBranch ?? {}, "binaryPath")),
"Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH.",
);
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(codexBranch ?? {}, "homePath")),
"Optional Codex home directory. Leave blank to use the default provider-managed location.",
);
setJsonSchemaDescription(claudeBranch, "Configuration for the Claude provider.");
setJsonSchemaDescription(
getNullableJsonSchemaBranch(getJsonSchemaProperty(claudeBranch ?? {}, "binaryPath")),
"Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH.",
);
for (const selectionBranch of getJsonSchemaAnyOfBranches(
getNullableJsonSchemaBranch(getJsonSchemaProperty(schema, "textGenerationModelSelection")),
)) {
const providerProperty = getJsonSchemaProperty(selectionBranch, "provider");
const providerBranch = getNullableJsonSchemaBranch(providerProperty);
const providerName =
Array.isArray(providerBranch?.enum) && typeof providerBranch.enum[0] === "string"
? providerBranch.enum[0]
: null;
if (providerName === "codex") {
setJsonSchemaDescription(
getJsonSchemaProperty(selectionBranch, "model"),
"The Codex model slug to use for text generation.",
);
} else if (providerName === "claudeAgent") {
setJsonSchemaDescription(
getJsonSchemaProperty(selectionBranch, "model"),
"The Claude model slug to use for text generation.",
);
}
}
return {
...schema,
properties: {
$schema: {
type: "string",
description:
"Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL.",
},
...properties,
},
};
}
export function writeServerSettingsJsonSchemas(options?: {
readonly rootDir?: string;
readonly version?: string;
}): {
readonly changed: boolean;
} {
return writeJsonSchemaArtifacts({
latestRelativePath: SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
getVersionedRelativePath: getVersionedServerSettingsSchemaRelativePath,
document: buildServerSettingsJsonSchema(),
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
...(options?.version === undefined ? {} : { version: options.version }),
});
}
+2 -56
View File
@@ -1,13 +1,5 @@
import { execFileSync } from "node:child_process";
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { cpSync, 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";
@@ -89,7 +81,7 @@ try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
"bun",
process.execPath,
[
resolve(repoRoot, "scripts/update-release-package-versions.ts"),
"9.9.9-smoke.0",
@@ -114,52 +106,6 @@ 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,
@@ -1,101 +0,0 @@
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 });
}
});
});
+1 -7
View File
@@ -2,9 +2,6 @@ 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",
@@ -40,9 +37,6 @@ export function updateReleasePackageVersions(
changed = true;
}
changed = writeServerSettingsJsonSchemas({ rootDir, version }).changed || changed;
changed = writeKeybindingsJsonSchemas({ rootDir, version }).changed || changed;
return { changed };
}
@@ -105,7 +99,7 @@ if (isMain) {
);
if (!changed) {
console.log("All release version artifacts already match the requested version.");
console.log("All package.json versions already match release version.");
}
if (writeGithubOutput) {