Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
346402e6ea | ||
|
|
c13fc4f6f8 | ||
|
|
56f56f5506 | ||
|
|
9d475dd325 | ||
|
|
a43922f5c9 | ||
|
|
c3097ba5d7 | ||
|
|
32f1d4c34f | ||
|
|
80475e854c | ||
|
|
aeaf31ff6d | ||
|
|
8b9cf23ec7 | ||
|
|
68ff6d8578 | ||
|
|
8f5078c6d5 | ||
|
|
f1793ad2eb | ||
|
|
805c68dd0e | ||
|
|
e835adeb16 |
No files matched your search
@@ -126,7 +126,7 @@ jobs:
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
@@ -248,7 +248,7 @@ jobs:
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
@@ -348,7 +348,7 @@ jobs:
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
|
||||
run: bun scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -364,7 +364,7 @@ jobs:
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
@@ -372,6 +372,6 @@ jobs:
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
+2
-1
@@ -9,7 +9,8 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/marketing/public/schemas"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -15,6 +15,29 @@ The file must be a JSON array of rules:
|
||||
|
||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
||||
|
||||
## Editor Schema Support
|
||||
|
||||
`keybindings.json` is intentionally a top-level JSON array, so it cannot carry an inline `$schema` property the way `settings.json` can.
|
||||
|
||||
To get autocomplete and hover docs in editors like VS Code, associate the file externally with the published schema:
|
||||
|
||||
```json
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["**/.t3/keybindings.json", "**/keybindings.json"],
|
||||
"url": "https://t3.codes/schemas/keybindings.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If you want a pinned schema instead of the latest stable one, use a versioned URL such as:
|
||||
|
||||
```text
|
||||
https://t3.codes/schemas/keybindings/0.0.15.json
|
||||
```
|
||||
|
||||
## Defaults
|
||||
|
||||
```json
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Keybindings",
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Keyboard shortcut to listen for."
|
||||
},
|
||||
"command": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"diff.toggle",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
"thread.previous",
|
||||
"thread.next",
|
||||
"thread.jump.1",
|
||||
"thread.jump.2",
|
||||
"thread.jump.3",
|
||||
"thread.jump.4",
|
||||
"thread.jump.5",
|
||||
"thread.jump.6",
|
||||
"thread.jump.7",
|
||||
"thread.jump.8",
|
||||
"thread.jump.9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^script\\.[\\s\\S]*?\\.run$",
|
||||
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
|
||||
}
|
||||
],
|
||||
"description": "Command to execute when the shortcut matches."
|
||||
},
|
||||
"when": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional expression limiting when the shortcut is active."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"command"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"description": "Single keybinding rule entry in `keybindings.json`."
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"maxItems": 256,
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Keybindings",
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Keyboard shortcut to listen for."
|
||||
},
|
||||
"command": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"diff.toggle",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
"thread.previous",
|
||||
"thread.next",
|
||||
"thread.jump.1",
|
||||
"thread.jump.2",
|
||||
"thread.jump.3",
|
||||
"thread.jump.4",
|
||||
"thread.jump.5",
|
||||
"thread.jump.6",
|
||||
"thread.jump.7",
|
||||
"thread.jump.8",
|
||||
"thread.jump.9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^script\\.[\\s\\S]*?\\.run$",
|
||||
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
|
||||
}
|
||||
],
|
||||
"description": "Command to execute when the shortcut matches."
|
||||
},
|
||||
"when": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional expression limiting when the shortcut is active."
|
||||
}
|
||||
},
|
||||
"required": ["key", "command"],
|
||||
"additionalProperties": false,
|
||||
"description": "Single keybinding rule entry in `keybindings.json`."
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"maxItems": 256,
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Server Settings",
|
||||
"description": "Server-authoritative settings persisted in `settings.json`.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
|
||||
},
|
||||
"enableAssistantStreaming": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Show token-by-token output while a response is in progress."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Show token-by-token output while a response is in progress."
|
||||
},
|
||||
"defaultThreadEnvMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"local",
|
||||
"worktree"
|
||||
],
|
||||
"description": "Pick the default workspace mode for newly created draft threads."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Pick the default workspace mode for newly created draft threads."
|
||||
},
|
||||
"textGenerationModelSelection": {
|
||||
"anyOf": [
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"codex"
|
||||
],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Codex model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reasoningEffort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"xhigh",
|
||||
"high",
|
||||
"medium",
|
||||
"low"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Codex fast mode when the selected model supports it."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Codex-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider",
|
||||
"model"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"claudeAgent"
|
||||
],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Claude model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"thinking": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether Claude should enable extended thinking for the selected model."
|
||||
},
|
||||
"effort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"max",
|
||||
"ultrathink"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Claude fast mode when the selected model supports it."
|
||||
},
|
||||
"contextWindow": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional Claude context window preset to request for the selected model, if supported."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Claude-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider",
|
||||
"model"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Claude provider."
|
||||
}
|
||||
],
|
||||
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
},
|
||||
"providers": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"codex": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Codex binary"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Codex binary"
|
||||
},
|
||||
"homePath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Optional custom Codex home and config directory."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional custom Codex home and config directory."
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
"claudeAgent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Claude binary"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Claude binary"
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Claude provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Claude provider."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Provider-specific server configuration."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Provider-specific server configuration."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Server Settings",
|
||||
"description": "Server-authoritative settings persisted in `settings.json`.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
|
||||
},
|
||||
"enableAssistantStreaming": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Show token-by-token output while a response is in progress."
|
||||
},
|
||||
"defaultThreadEnvMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["local", "worktree"],
|
||||
"description": "Default execution environment to use when creating new threads."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Pick the default workspace mode for newly created draft threads."
|
||||
},
|
||||
"textGenerationModelSelection": {
|
||||
"anyOf": [
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["codex"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Codex model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reasoningEffort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["xhigh", "high", "medium", "low"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Codex fast mode when the selected model supports it."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Codex-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["claudeAgent"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Claude model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"thinking": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether Claude should enable extended thinking for the selected model."
|
||||
},
|
||||
"effort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high", "max", "ultrathink"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Claude fast mode when the selected model supports it."
|
||||
},
|
||||
"contextWindow": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional Claude context window preset to request for the selected model, if supported."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Claude-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Claude provider."
|
||||
}
|
||||
],
|
||||
"description": "Default provider and model to use for server-side text generation features."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
},
|
||||
"providers": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"codex": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Codex binary"
|
||||
},
|
||||
"homePath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional custom Codex home and config directory."
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
"claudeAgent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Claude binary"
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Claude provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Claude provider."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Provider-specific server configuration."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Provider-specific server configuration."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
@@ -27,7 +28,6 @@ import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { CodexModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -26,7 +27,6 @@ import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
@@ -14,15 +14,6 @@ export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
|
||||
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
|
||||
export function toJsonSchemaObject(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return { ...document.schema, $defs: document.definitions };
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
|
||||
export function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
|
||||
@@ -35,7 +35,6 @@ import {
|
||||
Predicate,
|
||||
PubSub,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
Ref,
|
||||
@@ -45,7 +44,7 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
@@ -406,16 +405,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||
|
||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
);
|
||||
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
|
||||
|
||||
export interface KeybindingsConfigState {
|
||||
readonly keybindings: ResolvedKeybindingsConfig;
|
||||
@@ -664,7 +654,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
|
||||
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
|
||||
return encodeKeybindingsConfigPrettyJson(rules).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
|
||||
@@ -216,4 +216,50 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves a top-level $schema declaration when rewriting settings", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/usr/local/bin/codex",
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
yield* serverSettings.start;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(JSON.parse(raw), {
|
||||
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/usr/local/bin/codex",
|
||||
},
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
});
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface ServerSettingsShape {
|
||||
/** Start the settings runtime and attach file watching. */
|
||||
@@ -90,6 +90,9 @@ export class ServerSettingsService extends ServiceMap.Service<
|
||||
}
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const UnknownJson = fromLenientJson(Schema.Unknown);
|
||||
const encodeServerSettingsDocument = encodePrettyJsonEffect(Schema.Unknown);
|
||||
const SETTINGS_SCHEMA_DECLARATION_KEY = "$schema";
|
||||
|
||||
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
|
||||
|
||||
@@ -166,6 +169,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
|
||||
const startedRef = yield* Ref.make(false);
|
||||
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
|
||||
const schemaDeclarationRef = yield* Ref.make<string | undefined>(undefined);
|
||||
const watcherScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
|
||||
|
||||
@@ -196,10 +200,25 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
|
||||
const loadSettingsFromDisk = Effect.gen(function* () {
|
||||
if (!(yield* readConfigExists)) {
|
||||
yield* Ref.set(schemaDeclarationRef, undefined);
|
||||
return DEFAULT_SERVER_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = yield* readRawConfig;
|
||||
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
|
||||
if (rawJson._tag === "Success") {
|
||||
const value = rawJson.value;
|
||||
const valueRecord =
|
||||
value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
const schemaDeclaration =
|
||||
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
|
||||
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
|
||||
: undefined;
|
||||
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
|
||||
}
|
||||
|
||||
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
|
||||
if (decoded._tag === "Failure") {
|
||||
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
|
||||
@@ -222,7 +241,17 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
|
||||
|
||||
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
|
||||
return Ref.get(schemaDeclarationRef).pipe(
|
||||
Effect.map((schemaDeclaration) =>
|
||||
schemaDeclaration
|
||||
? {
|
||||
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
|
||||
...sparseSettings,
|
||||
}
|
||||
: sparseSettings,
|
||||
),
|
||||
Effect.flatMap(encodeServerSettingsDocument),
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||
|
||||
@@ -21,5 +21,12 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||
"include": [
|
||||
"src",
|
||||
"tsdown.config.ts",
|
||||
"scripts",
|
||||
"integration",
|
||||
"../../scripts/lib/brand-assets.ts",
|
||||
"../../scripts/lib/resolve-catalog.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { type GitBranch } from "@t3tools/contracts";
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
type CSSProperties,
|
||||
@@ -16,14 +14,14 @@ import {
|
||||
useTransition,
|
||||
} from "react";
|
||||
|
||||
import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { REACTIVITY_KEYS } from "../rpc/client";
|
||||
import {
|
||||
gitBranchesAtom,
|
||||
gitCheckoutMutationAtom,
|
||||
gitCreateBranchMutationAtom,
|
||||
gitStatusAtom,
|
||||
} from "../rpc/gitAtoms";
|
||||
gitBranchesQueryOptions,
|
||||
gitQueryKeys,
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
@@ -86,23 +84,19 @@ export function BranchToolbarBranchSelector({
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const deferredBranchQuery = useDeferredValue(branchQuery);
|
||||
const branchesResult = useAtomValue(gitBranchesAtom(branchCwd));
|
||||
const branchStatusResult = useAtomValue(gitStatusAtom(branchCwd));
|
||||
const refreshBranches = useAtomRefresh(gitBranchesAtom(branchCwd));
|
||||
const refreshBranchStatus = useAtomRefresh(gitStatusAtom(branchCwd));
|
||||
const checkoutBranch = useAtomSet(gitCheckoutMutationAtom, { mode: "promise" });
|
||||
const createGitBranch = useAtomSet(gitCreateBranchMutationAtom, { mode: "promise" });
|
||||
const branchesData = Option.getOrUndefined(AsyncResult.value(branchesResult));
|
||||
const branchStatus = Option.getOrUndefined(AsyncResult.value(branchStatusResult));
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
|
||||
const branches = useMemo(
|
||||
() => dedupeRemoteBranchesWithLocalMatches(branchesData?.branches ?? []),
|
||||
[branchesData?.branches],
|
||||
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
|
||||
[branchesQuery.data?.branches],
|
||||
);
|
||||
const currentGitBranch =
|
||||
branchStatus?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
||||
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -161,18 +155,18 @@ export function BranchToolbarBranchSelector({
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const isBranchesLoading =
|
||||
branches.length === 0 && (AsyncResult.isInitial(branchesResult) || branchesResult.waiting);
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
if (!branchCwd || isBranchActionPending) return;
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || isBranchActionPending) return;
|
||||
|
||||
// In new-worktree mode, selecting a branch sets the base branch.
|
||||
if (isSelectingWorktreeBase) {
|
||||
@@ -206,13 +200,8 @@ export function BranchToolbarBranchSelector({
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
await checkoutBranch({
|
||||
payload: {
|
||||
cwd: selectionTarget.checkoutCwd,
|
||||
branch: branch.name,
|
||||
},
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(selectionTarget.checkoutCwd)],
|
||||
});
|
||||
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
|
||||
await invalidateGitQueries(queryClient);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -222,14 +211,23 @@ export function BranchToolbarBranchSelector({
|
||||
return;
|
||||
}
|
||||
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
onSetThreadBranch(selectedBranchName, selectionTarget.nextWorktreePath);
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
|
||||
setOptimisticBranch(nextBranchName);
|
||||
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
if (!branchCwd || !name || isBranchActionPending) return;
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
@@ -238,14 +236,9 @@ export function BranchToolbarBranchSelector({
|
||||
setOptimisticBranch(name);
|
||||
|
||||
try {
|
||||
await createGitBranch({
|
||||
payload: { cwd: branchCwd, branch: name },
|
||||
});
|
||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||
try {
|
||||
await checkoutBranch({
|
||||
payload: { cwd: branchCwd, branch: name },
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(branchCwd)],
|
||||
});
|
||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -294,12 +287,11 @@ export function BranchToolbarBranchSelector({
|
||||
setBranchQuery("");
|
||||
return;
|
||||
}
|
||||
if (branchCwd) {
|
||||
refreshBranches();
|
||||
refreshBranchStatus();
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: gitQueryKeys.branches(branchCwd),
|
||||
});
|
||||
},
|
||||
[branchCwd, refreshBranchStatus, refreshBranches],
|
||||
[branchCwd, queryClient],
|
||||
);
|
||||
|
||||
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -433,7 +425,7 @@ export function BranchToolbarBranchSelector({
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isBranchesLoading || isBranchActionPending}
|
||||
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon />
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
import { getRouter } from "../router";
|
||||
import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
|
||||
import { useStore } from "../store";
|
||||
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
@@ -1122,7 +1121,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
},
|
||||
});
|
||||
__resetNativeApiForTests();
|
||||
resetAppAtomRegistryForTests();
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
@@ -1145,7 +1143,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
afterEach(() => {
|
||||
customWsRpcResolver = null;
|
||||
document.body.innerHTML = "";
|
||||
resetAppAtomRegistryForTests();
|
||||
});
|
||||
|
||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
@@ -22,13 +21,12 @@ import {
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import * as Option from "effect/Option";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { isElectron } from "../env";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
@@ -108,8 +106,6 @@ import { Separator } from "./ui/separator";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { gitBranchesAtom, gitCreateWorktreeMutationAtom } from "~/rpc/gitAtoms";
|
||||
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
@@ -427,7 +423,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
select: (params) => parseDiffRouteSearch(params),
|
||||
});
|
||||
const { resolvedTheme } = useTheme();
|
||||
const createWorktree = useAtomSet(gitCreateWorktreeMutationAtom, { mode: "promise" });
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
@@ -1204,8 +1201,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesResult = useAtomValue(gitBranchesAtom(gitCwd));
|
||||
const branches = Option.getOrUndefined(AsyncResult.value(branchesResult));
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
const keybindings = useServerKeybindings();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const modelOptionsByProvider = useMemo(
|
||||
@@ -1342,7 +1338,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}, [activeProjectCwd, activeThreadWorktreePath]);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = branches?.isRepo ?? true;
|
||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
@@ -2791,17 +2787,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (baseBranchForWorktree) {
|
||||
beginLocalDispatch({ preparingWorktree: true });
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktree({
|
||||
payload: {
|
||||
cwd: activeProject.cwd,
|
||||
branch: baseBranchForWorktree,
|
||||
path: null,
|
||||
newBranch,
|
||||
},
|
||||
reactivityKeys: [
|
||||
REACTIVITY_KEYS.git(activeProject.cwd),
|
||||
REACTIVITY_KEYS.project(activeProject.cwd),
|
||||
],
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
branch: baseBranchForWorktree,
|
||||
newBranch,
|
||||
});
|
||||
nextThreadBranch = result.worktree.branch;
|
||||
nextThreadWorktreePath = result.worktree.path;
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
@@ -22,10 +19,10 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { gitBranchesAtom } from "../rpc/gitAtoms";
|
||||
import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -192,9 +189,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const gitBranchesResult = useAtomValue(gitBranchesAtom(activeCwd ?? null));
|
||||
const gitBranches = Option.getOrUndefined(AsyncResult.value(gitBranchesResult));
|
||||
const isGitRepo = gitBranches?.isRepo ?? true;
|
||||
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
|
||||
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
GitRunStackedActionInput,
|
||||
GitActionProgressEvent,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause } from "effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
@@ -41,18 +38,18 @@ import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { openInPreferredEditor } from "~/editorPreferences";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitInitMutationOptions,
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import {
|
||||
gitBranchesAtom,
|
||||
gitInitMutationAtom,
|
||||
gitPullMutationAtom,
|
||||
gitRunStackedActionMutationAtom,
|
||||
gitRunStackedActionProgressAtom,
|
||||
gitStatusAtom,
|
||||
} from "~/rpc/gitAtoms";
|
||||
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
gitCwd: string | null;
|
||||
@@ -115,13 +112,6 @@ function resolveProgressDescription(progress: ActiveGitActionProgress): string |
|
||||
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
|
||||
}
|
||||
|
||||
function toError(error: unknown): Error {
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
}
|
||||
return new Error(typeof error === "string" ? error : "Unknown error");
|
||||
}
|
||||
|
||||
function getMenuActionDisabledReason({
|
||||
item,
|
||||
gitStatus,
|
||||
@@ -218,6 +208,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
);
|
||||
const queryClient = useQueryClient();
|
||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
||||
@@ -240,22 +231,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}, [threadToastData]);
|
||||
|
||||
const gitStatusResult = useAtomValue(gitStatusAtom(gitCwd));
|
||||
const branchesResult = useAtomValue(gitBranchesAtom(gitCwd));
|
||||
const refreshGitStatus = useAtomRefresh(gitStatusAtom(gitCwd));
|
||||
const refreshGitBranches = useAtomRefresh(gitBranchesAtom(gitCwd));
|
||||
const initGit = useAtomSet(gitInitMutationAtom, { mode: "promise" });
|
||||
const pullGit = useAtomSet(gitPullMutationAtom, { mode: "promise" });
|
||||
const runStackedAction = useAtomSet(gitRunStackedActionMutationAtom, { mode: "promise" });
|
||||
const runStackedActionResult = useAtomValue(gitRunStackedActionMutationAtom);
|
||||
const stackedActionProgressEvent = useAtomValue(gitRunStackedActionProgressAtom);
|
||||
const [isInitPending, setIsInitPending] = useState(false);
|
||||
const [isPullRunning, setIsPullRunning] = useState(false);
|
||||
const gitStatus = Option.getOrNull(AsyncResult.value(gitStatusResult));
|
||||
const gitStatusError = Option.getOrNull(
|
||||
Option.map(AsyncResult.cause(gitStatusResult), (cause) => toError(Cause.squash(cause))),
|
||||
);
|
||||
const branchList = Option.getOrNull(AsyncResult.value(branchesResult));
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||
|
||||
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
// Default to true while loading so we don't flash init controls.
|
||||
const isRepo = branchList?.isRepo ?? true;
|
||||
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
|
||||
@@ -264,10 +242,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGitStatusOutOfSync || !gitCwd) return;
|
||||
refreshGitStatus();
|
||||
refreshGitBranches();
|
||||
}, [gitCwd, isGitStatusOutOfSync, refreshGitBranches, refreshGitStatus]);
|
||||
if (!isGitStatusOutOfSync) return;
|
||||
void invalidateGitQueries(queryClient);
|
||||
}, [isGitStatusOutOfSync, queryClient]);
|
||||
|
||||
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
|
||||
|
||||
@@ -275,40 +252,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
||||
const allSelected = excludedFiles.size === 0;
|
||||
const noneSelected = selectedFiles.length === 0;
|
||||
const isRunStackedActionRunning = runStackedActionResult.waiting;
|
||||
|
||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const runImmediateGitAction = useCallback(
|
||||
(input: GitRunStackedActionInput) => runStackedAction(input),
|
||||
[runStackedAction],
|
||||
);
|
||||
const pullCurrentBranch = useCallback(
|
||||
async (cwd: string) => {
|
||||
setIsPullRunning(true);
|
||||
try {
|
||||
return await pullGit({
|
||||
payload: { cwd },
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||
});
|
||||
} finally {
|
||||
setIsPullRunning(false);
|
||||
}
|
||||
},
|
||||
[pullGit],
|
||||
);
|
||||
const initializeGit = useCallback(
|
||||
async (cwd: string) => {
|
||||
setIsInitPending(true);
|
||||
try {
|
||||
await initGit({
|
||||
payload: { cwd },
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||
});
|
||||
} finally {
|
||||
setIsInitPending(false);
|
||||
}
|
||||
},
|
||||
[initGit],
|
||||
);
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
const branchName = gitStatusForActions?.branch;
|
||||
if (!branchName) return false;
|
||||
@@ -349,59 +307,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
};
|
||||
}, [updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
const event = stackedActionProgressEvent;
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!event || !progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
return;
|
||||
case "action_failed":
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
}, [gitCwd, stackedActionProgressEvent, updateActiveProgressToast]);
|
||||
|
||||
const openExistingPr = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
@@ -510,17 +415,69 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}
|
||||
|
||||
if (!gitCwd) {
|
||||
return;
|
||||
}
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const promise = runImmediateGitAction({
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Let the resolved mutation update the toast so we keep the
|
||||
// elapsed description visible until the final success state renders.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Let the rejected mutation publish the error toast to avoid a
|
||||
// transient intermediate state before the final failure message.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
actionId,
|
||||
cwd: gitCwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
onProgress: applyProgressEvent,
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -667,10 +624,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
return;
|
||||
}
|
||||
if (quickAction.kind === "run_pull") {
|
||||
if (!gitCwd) {
|
||||
return;
|
||||
}
|
||||
const promise = pullCurrentBranch(gitCwd);
|
||||
const promise = pullMutation.mutateAsync();
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Pulling...", data: threadToastData },
|
||||
success: (result) => ({
|
||||
@@ -702,7 +656,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
if (quickAction.action) {
|
||||
void runGitActionWithToast({ action: quickAction.action });
|
||||
}
|
||||
}, [gitCwd, openExistingPr, pullCurrentBranch, quickAction, threadToastData]);
|
||||
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
|
||||
|
||||
const openDialogForMenuItem = useCallback(
|
||||
(item: GitActionMenuItem) => {
|
||||
@@ -779,15 +733,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={isInitPending}
|
||||
onClick={() => {
|
||||
if (!gitCwd) {
|
||||
return;
|
||||
}
|
||||
void initializeGit(gitCwd).catch(() => undefined);
|
||||
}}
|
||||
disabled={initMutation.isPending}
|
||||
onClick={() => initMutation.mutate()}
|
||||
>
|
||||
{isInitPending ? "Initializing..." : "Initialize Git"}
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : (
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
@@ -829,10 +778,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu
|
||||
onOpenChange={(open) => {
|
||||
if (open && gitCwd) {
|
||||
refreshGitStatus();
|
||||
refreshGitBranches();
|
||||
}
|
||||
if (open) void invalidateGitQueries(queryClient);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { Cause, Option } from "effect";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
gitPreparePullRequestThreadMutationOptions,
|
||||
gitResolvePullRequestQueryOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parsePullRequestReference } from "~/pullRequestReference";
|
||||
import { gitResolvePullRequestAtom, gitPreparePullRequestThreadMutationAtom } from "~/rpc/gitAtoms";
|
||||
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -29,10 +30,6 @@ interface PullRequestThreadDialogProps {
|
||||
onPrepared: (input: { branch: string; worktreePath: string | null }) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function toErrorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
export function PullRequestThreadDialog({
|
||||
open,
|
||||
cwd,
|
||||
@@ -40,28 +37,23 @@ export function PullRequestThreadDialog({
|
||||
onOpenChange,
|
||||
onPrepared,
|
||||
}: PullRequestThreadDialogProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const referenceInputRef = useRef<HTMLInputElement>(null);
|
||||
const [reference, setReference] = useState(initialReference ?? "");
|
||||
const [referenceDirty, setReferenceDirty] = useState(false);
|
||||
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
|
||||
const [prepareFollowupErrorMessage, setPrepareFollowupErrorMessage] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
|
||||
reference,
|
||||
{ wait: 450 },
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const resetPreparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setReference(initialReference ?? "");
|
||||
setReferenceDirty(false);
|
||||
setPreparingMode(null);
|
||||
setPrepareFollowupErrorMessage(null);
|
||||
resetPreparePullRequestThread(Atom.Reset);
|
||||
}, [initialReference, open, resetPreparePullRequestThread]);
|
||||
}, [initialReference, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -76,35 +68,41 @@ export function PullRequestThreadDialog({
|
||||
|
||||
const parsedReference = parsePullRequestReference(reference);
|
||||
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
|
||||
const resolvePullRequestResult = useAtomValue(
|
||||
gitResolvePullRequestAtom({
|
||||
cwd: open ? cwd : null,
|
||||
const resolvePullRequestQuery = useQuery(
|
||||
gitResolvePullRequestQueryOptions({
|
||||
cwd,
|
||||
reference: open ? parsedDebouncedReference : null,
|
||||
}),
|
||||
);
|
||||
const preparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom, {
|
||||
mode: "promise",
|
||||
});
|
||||
const preparePullRequestThreadResult = useAtomValue(gitPreparePullRequestThreadMutationAtom);
|
||||
const resolvePullRequestData = Option.getOrUndefined(AsyncResult.value(resolvePullRequestResult));
|
||||
const resolvePullRequestError = Option.getOrNull(
|
||||
Option.map(AsyncResult.cause(resolvePullRequestResult), (cause) => Cause.squash(cause)),
|
||||
const cachedPullRequest = useMemo(() => {
|
||||
if (!cwd || !parsedReference) {
|
||||
return null;
|
||||
}
|
||||
const cached = queryClient.getQueryData<GitResolvePullRequestResult>([
|
||||
"git",
|
||||
"pull-request",
|
||||
cwd,
|
||||
parsedReference,
|
||||
]);
|
||||
return cached?.pullRequest ?? null;
|
||||
}, [cwd, parsedReference, queryClient]);
|
||||
const preparePullRequestThreadMutation = useMutation(
|
||||
gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }),
|
||||
);
|
||||
const isPreparingPullRequestThread = preparingMode !== null;
|
||||
|
||||
const liveResolvedPullRequest =
|
||||
parsedReference !== null && parsedReference === parsedDebouncedReference
|
||||
? (resolvePullRequestData?.pullRequest ?? null)
|
||||
? (resolvePullRequestQuery.data?.pullRequest ?? null)
|
||||
: null;
|
||||
const resolvedPullRequest = liveResolvedPullRequest;
|
||||
const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
|
||||
const isResolving =
|
||||
open &&
|
||||
parsedReference !== null &&
|
||||
resolvedPullRequest === null &&
|
||||
(referenceDebouncer.state.isPending ||
|
||||
parsedReference !== parsedDebouncedReference ||
|
||||
AsyncResult.isInitial(resolvePullRequestResult) ||
|
||||
resolvePullRequestResult.waiting);
|
||||
resolvePullRequestQuery.isPending ||
|
||||
resolvePullRequestQuery.isFetching);
|
||||
const statusTone = useMemo(() => {
|
||||
switch (resolvedPullRequest?.state) {
|
||||
case "merged":
|
||||
@@ -117,11 +115,6 @@ export function PullRequestThreadDialog({
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
}, [resolvedPullRequest?.state]);
|
||||
const preparePullRequestThreadErrorMessage = AsyncResult.match(preparePullRequestThreadResult, {
|
||||
onInitial: () => null,
|
||||
onSuccess: () => null,
|
||||
onFailure: (error) => Cause.pretty(error.cause),
|
||||
});
|
||||
|
||||
const handleConfirm = useCallback(
|
||||
async (mode: "local" | "worktree") => {
|
||||
@@ -132,36 +125,29 @@ export function PullRequestThreadDialog({
|
||||
if (!parsedReference || !resolvedPullRequest || !cwd) {
|
||||
return;
|
||||
}
|
||||
setPrepareFollowupErrorMessage(null);
|
||||
setPreparingMode(mode);
|
||||
try {
|
||||
const result = await preparePullRequestThread({
|
||||
payload: {
|
||||
cwd,
|
||||
reference: parsedReference,
|
||||
mode,
|
||||
},
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||
const result = await preparePullRequestThreadMutation.mutateAsync({
|
||||
reference: parsedReference,
|
||||
mode,
|
||||
});
|
||||
|
||||
try {
|
||||
await onPrepared({
|
||||
branch: result.branch,
|
||||
worktreePath: result.worktreePath,
|
||||
});
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
setPrepareFollowupErrorMessage(
|
||||
toErrorMessage(error, "Failed to prepare pull request thread."),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
await onPrepared({
|
||||
branch: result.branch,
|
||||
worktreePath: result.worktreePath,
|
||||
});
|
||||
onOpenChange(false);
|
||||
} finally {
|
||||
setPreparingMode(null);
|
||||
}
|
||||
},
|
||||
[cwd, onOpenChange, onPrepared, parsedReference, preparePullRequestThread, resolvedPullRequest],
|
||||
[
|
||||
cwd,
|
||||
onOpenChange,
|
||||
onPrepared,
|
||||
parsedReference,
|
||||
preparePullRequestThreadMutation,
|
||||
resolvedPullRequest,
|
||||
],
|
||||
);
|
||||
|
||||
const validationMessage = !referenceDirty
|
||||
@@ -173,17 +159,21 @@ export function PullRequestThreadDialog({
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
(resolvedPullRequest === null && AsyncResult.isFailure(resolvePullRequestResult)
|
||||
? resolvePullRequestError instanceof Error
|
||||
? resolvePullRequestError.message
|
||||
(resolvedPullRequest === null && resolvePullRequestQuery.isError
|
||||
? resolvePullRequestQuery.error instanceof Error
|
||||
? resolvePullRequestQuery.error.message
|
||||
: "Failed to resolve pull request."
|
||||
: (prepareFollowupErrorMessage ?? preparePullRequestThreadErrorMessage));
|
||||
: preparePullRequestThreadMutation.error instanceof Error
|
||||
? preparePullRequestThreadMutation.error.message
|
||||
: preparePullRequestThreadMutation.error
|
||||
? "Failed to prepare pull request thread."
|
||||
: null);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!isPreparingPullRequestThread) {
|
||||
if (!preparePullRequestThreadMutation.isPending) {
|
||||
onOpenChange(nextOpen);
|
||||
}
|
||||
}}
|
||||
@@ -212,7 +202,7 @@ export function PullRequestThreadDialog({
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (!isResolving && !isPreparingPullRequestThread) {
|
||||
if (!isResolving && !preparePullRequestThreadMutation.isPending) {
|
||||
void handleConfirm("local");
|
||||
}
|
||||
}}
|
||||
@@ -251,7 +241,7 @@ export function PullRequestThreadDialog({
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isPreparingPullRequestThread}
|
||||
disabled={preparePullRequestThreadMutation.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
@@ -262,7 +252,12 @@ export function PullRequestThreadDialog({
|
||||
onClick={() => {
|
||||
void handleConfirm("local");
|
||||
}}
|
||||
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
|
||||
disabled={
|
||||
!cwd ||
|
||||
!resolvedPullRequest ||
|
||||
isResolving ||
|
||||
preparePullRequestThreadMutation.isPending
|
||||
}
|
||||
>
|
||||
{preparingMode === "local" ? "Preparing local..." : "Local"}
|
||||
</Button>
|
||||
@@ -272,7 +267,12 @@ export function PullRequestThreadDialog({
|
||||
onClick={() => {
|
||||
void handleConfirm("worktree");
|
||||
}}
|
||||
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
|
||||
disabled={
|
||||
!cwd ||
|
||||
!resolvedPullRequest ||
|
||||
isResolving ||
|
||||
preparePullRequestThreadMutation.isPending
|
||||
}
|
||||
>
|
||||
{preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"}
|
||||
</Button>
|
||||
|
||||
@@ -12,8 +12,6 @@ import {
|
||||
} from "lucide-react";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { autoAnimate } from "@formkit/auto-animate";
|
||||
import { Option } from "effect";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -46,6 +44,7 @@ import {
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQueries } from "@tanstack/react-query";
|
||||
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
type SidebarProjectSortOrder,
|
||||
@@ -66,8 +65,8 @@ import {
|
||||
threadTraversalDirectionFromCommand,
|
||||
} from "../keybindings";
|
||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useGitStatuses } from "../rpc/gitAtoms";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
|
||||
@@ -557,15 +556,19 @@ export default function Sidebar() {
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusResults = useGitStatuses(threadGitStatusCwds);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
queries: threadGitStatusCwds.map((cwd) => ({
|
||||
...gitStatusQueryOptions(cwd),
|
||||
staleTime: 30_000,
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
if (!cwd) continue;
|
||||
const status = threadGitStatusResults[index]
|
||||
? Option.getOrUndefined(AsyncResult.value(threadGitStatusResults[index]!))
|
||||
: undefined;
|
||||
const status = threadGitStatusQueries[index]?.data;
|
||||
if (status) {
|
||||
statusByCwd.set(cwd, status);
|
||||
}
|
||||
@@ -579,7 +582,7 @@ export default function Sidebar() {
|
||||
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusResults, threadGitTargets]);
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -12,14 +12,19 @@ import {
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ClaudeSettings,
|
||||
ClientSettingsSchema,
|
||||
CodexSettings,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ProviderKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
ServerSettings,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getSchemaDescription } from "@t3tools/shared/schemaJson";
|
||||
import { Equal } from "effect";
|
||||
import { APP_VERSION } from "../../branding";
|
||||
import {
|
||||
@@ -85,6 +90,52 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
function requireSchemaDescription(
|
||||
schema: Parameters<typeof getSchemaDescription>[0],
|
||||
label: string,
|
||||
) {
|
||||
const description = getSchemaDescription(schema);
|
||||
if (!description) {
|
||||
throw new Error(`Missing schema description for ${label}`);
|
||||
}
|
||||
return description;
|
||||
}
|
||||
|
||||
const SETTINGS_DESCRIPTIONS = {
|
||||
timestampFormat: requireSchemaDescription(
|
||||
ClientSettingsSchema.fields.timestampFormat,
|
||||
"ClientSettings.timestampFormat",
|
||||
),
|
||||
diffWordWrap: requireSchemaDescription(
|
||||
ClientSettingsSchema.fields.diffWordWrap,
|
||||
"ClientSettings.diffWordWrap",
|
||||
),
|
||||
confirmThreadArchive: requireSchemaDescription(
|
||||
ClientSettingsSchema.fields.confirmThreadArchive,
|
||||
"ClientSettings.confirmThreadArchive",
|
||||
),
|
||||
confirmThreadDelete: requireSchemaDescription(
|
||||
ClientSettingsSchema.fields.confirmThreadDelete,
|
||||
"ClientSettings.confirmThreadDelete",
|
||||
),
|
||||
enableAssistantStreaming: requireSchemaDescription(
|
||||
ServerSettings.fields.enableAssistantStreaming,
|
||||
"ServerSettings.enableAssistantStreaming",
|
||||
),
|
||||
defaultThreadEnvMode: requireSchemaDescription(
|
||||
ServerSettings.fields.defaultThreadEnvMode,
|
||||
"ServerSettings.defaultThreadEnvMode",
|
||||
),
|
||||
textGenerationModelSelection: requireSchemaDescription(
|
||||
ServerSettings.fields.textGenerationModelSelection,
|
||||
"ServerSettings.textGenerationModelSelection",
|
||||
),
|
||||
codexBinaryPath: requireSchemaDescription(CodexSettings.fields.binaryPath, "Codex.binaryPath"),
|
||||
codexHomePath: requireSchemaDescription(CodexSettings.fields.homePath, "Codex.homePath"),
|
||||
claudeBinaryPath: requireSchemaDescription(ClaudeSettings.fields.binaryPath, "Claude.binaryPath"),
|
||||
} as const;
|
||||
|
||||
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
type InstallProviderSettings = {
|
||||
provider: ProviderKind;
|
||||
title: string;
|
||||
@@ -100,16 +151,16 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
|
||||
provider: "codex",
|
||||
title: "Codex",
|
||||
binaryPlaceholder: "Codex binary path",
|
||||
binaryDescription: "Path to the Codex binary",
|
||||
binaryDescription: SETTINGS_DESCRIPTIONS.codexBinaryPath,
|
||||
homePathKey: "codexHomePath",
|
||||
homePlaceholder: "CODEX_HOME",
|
||||
homeDescription: "Optional custom Codex home and config directory.",
|
||||
homeDescription: SETTINGS_DESCRIPTIONS.codexHomePath,
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
title: "Claude",
|
||||
binaryPlaceholder: "Claude binary path",
|
||||
binaryDescription: "Path to the Claude binary",
|
||||
binaryDescription: SETTINGS_DESCRIPTIONS.claudeBinaryPath,
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -773,7 +824,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Time format"
|
||||
description="System default follows your browser or OS clock preference."
|
||||
description={SETTINGS_DESCRIPTIONS.timestampFormat}
|
||||
resetAction={
|
||||
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
|
||||
<SettingResetButton
|
||||
@@ -815,7 +866,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Diff line wrapping"
|
||||
description="Set the default wrap state when the diff panel opens."
|
||||
description={SETTINGS_DESCRIPTIONS.diffWordWrap}
|
||||
resetAction={
|
||||
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
|
||||
<SettingResetButton
|
||||
@@ -839,7 +890,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Assistant output"
|
||||
description="Show token-by-token output while a response is in progress."
|
||||
description={SETTINGS_DESCRIPTIONS.enableAssistantStreaming}
|
||||
resetAction={
|
||||
settings.enableAssistantStreaming !==
|
||||
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
|
||||
@@ -866,7 +917,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="New threads"
|
||||
description="Pick the default workspace mode for newly created draft threads."
|
||||
description={SETTINGS_DESCRIPTIONS.defaultThreadEnvMode}
|
||||
resetAction={
|
||||
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
|
||||
<SettingResetButton
|
||||
@@ -907,7 +958,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Archive confirmation"
|
||||
description="Require a second click on the inline archive action before a thread is archived."
|
||||
description={SETTINGS_DESCRIPTIONS.confirmThreadArchive}
|
||||
resetAction={
|
||||
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
|
||||
<SettingResetButton
|
||||
@@ -933,7 +984,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Delete confirmation"
|
||||
description="Ask before deleting a thread and its chat history."
|
||||
description={SETTINGS_DESCRIPTIONS.confirmThreadDelete}
|
||||
resetAction={
|
||||
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
|
||||
<SettingResetButton
|
||||
@@ -959,7 +1010,7 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Text generation model"
|
||||
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
description={SETTINGS_DESCRIPTIONS.textGenerationModelSelection}
|
||||
resetAction={
|
||||
isGitWritingModelDirty ? (
|
||||
<SettingResetButton
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { useAtomSet } from "@effect/atom-react";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "./useHandleNewThread";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { gitRemoveWorktreeMutationAtom } from "../rpc/gitAtoms";
|
||||
import { REACTIVITY_KEYS } from "../rpc/client";
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
@@ -29,7 +28,8 @@ export function useThreadActions() {
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
const { handleNewThread } = useHandleNewThread();
|
||||
const removeWorktree = useAtomSet(gitRemoveWorktreeMutationAtom, { mode: "promise" });
|
||||
const queryClient = useQueryClient();
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
||||
|
||||
const archiveThread = useCallback(
|
||||
async (threadId: ThreadId) => {
|
||||
@@ -144,16 +144,10 @@ export function useThreadActions() {
|
||||
}
|
||||
|
||||
try {
|
||||
await removeWorktree({
|
||||
payload: {
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
force: true,
|
||||
},
|
||||
reactivityKeys: [
|
||||
REACTIVITY_KEYS.git(threadProject.cwd),
|
||||
REACTIVITY_KEYS.project(threadProject.cwd),
|
||||
],
|
||||
await removeWorktreeMutation.mutateAsync({
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
force: true,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
||||
@@ -176,7 +170,7 @@ export function useThreadActions() {
|
||||
clearTerminalState,
|
||||
appSettings.sidebarThreadSortOrder,
|
||||
navigate,
|
||||
removeWorktree,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
gitMutationKeys,
|
||||
gitPreparePullRequestThreadMutationOptions,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
} from "./gitReactQuery";
|
||||
|
||||
describe("gitMutationKeys", () => {
|
||||
it("scopes stacked action keys by cwd", () => {
|
||||
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
|
||||
gitMutationKeys.runStackedAction("/repo/b"),
|
||||
);
|
||||
});
|
||||
|
||||
it("scopes pull keys by cwd", () => {
|
||||
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
|
||||
});
|
||||
|
||||
it("scopes pull request thread preparation keys by cwd", () => {
|
||||
expect(gitMutationKeys.preparePullRequestThread("/repo/a")).not.toEqual(
|
||||
gitMutationKeys.preparePullRequestThread("/repo/b"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("git mutation options", () => {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
it("attaches cwd-scoped mutation key for runStackedAction", () => {
|
||||
const options = gitRunStackedActionMutationOptions({
|
||||
cwd: "/repo/a",
|
||||
queryClient,
|
||||
});
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
||||
});
|
||||
|
||||
it("attaches cwd-scoped mutation key for pull", () => {
|
||||
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
|
||||
});
|
||||
|
||||
it("attaches cwd-scoped mutation key for preparePullRequestThread", () => {
|
||||
const options = gitPreparePullRequestThreadMutationOptions({
|
||||
cwd: "/repo/a",
|
||||
queryClient,
|
||||
});
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.preparePullRequestThread("/repo/a"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
import { getWsRpcClient } from "../wsRpcClient";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
||||
};
|
||||
|
||||
export const gitMutationKeys = {
|
||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
||||
preparePullRequestThread: (cwd: string | null) =>
|
||||
["git", "mutation", "prepare-pull-request-thread", cwd] as const,
|
||||
};
|
||||
|
||||
export function invalidateGitQueries(queryClient: QueryClient) {
|
||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
||||
}
|
||||
|
||||
export function gitStatusQueryOptions(cwd: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: gitQueryKeys.status(cwd),
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!cwd) throw new Error("Git status is unavailable.");
|
||||
return api.git.status({ cwd });
|
||||
},
|
||||
enabled: cwd !== null,
|
||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: "always",
|
||||
refetchOnReconnect: "always",
|
||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export function gitBranchesQueryOptions(cwd: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: gitQueryKeys.branches(cwd),
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!cwd) throw new Error("Git branches are unavailable.");
|
||||
return api.git.listBranches({ cwd });
|
||||
},
|
||||
enabled: cwd !== null,
|
||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export function gitResolvePullRequestQueryOptions(input: {
|
||||
cwd: string | null;
|
||||
reference: string | null;
|
||||
}) {
|
||||
return queryOptions({
|
||||
queryKey: ["git", "pull-request", input.cwd, input.reference] as const,
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd || !input.reference) {
|
||||
throw new Error("Pull request lookup is unavailable.");
|
||||
}
|
||||
return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
|
||||
},
|
||||
enabled: input.cwd !== null && input.reference !== null,
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.init(input.cwd),
|
||||
mutationFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git init is unavailable.");
|
||||
return api.git.init({ cwd: input.cwd });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitCheckoutMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.checkout(input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git checkout is unavailable.");
|
||||
return api.git.checkout({ cwd: input.cwd, branch });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
mutationFn: async ({
|
||||
actionId,
|
||||
action,
|
||||
commitMessage,
|
||||
featureBranch,
|
||||
filePaths,
|
||||
onProgress,
|
||||
}: {
|
||||
actionId: string;
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
filePaths?: string[];
|
||||
onProgress?: (event: GitActionProgressEvent) => void;
|
||||
}) => {
|
||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||
return getWsRpcClient().git.runStackedAction(
|
||||
{
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
},
|
||||
...(onProgress ? [{ onProgress }] : []),
|
||||
);
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.pull(input.cwd),
|
||||
mutationFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git pull is unavailable.");
|
||||
return api.git.pull({ cwd: input.cwd });
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({
|
||||
cwd,
|
||||
branch,
|
||||
newBranch,
|
||||
path,
|
||||
}: {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
newBranch: string;
|
||||
path?: string | null;
|
||||
}) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!cwd) throw new Error("Git worktree creation is unavailable.");
|
||||
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
|
||||
},
|
||||
mutationKey: ["git", "mutation", "create-worktree"] as const,
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClient }) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!cwd) throw new Error("Git worktree removal is unavailable.");
|
||||
return api.git.removeWorktree({ cwd, path, force });
|
||||
},
|
||||
mutationKey: ["git", "mutation", "remove-worktree"] as const,
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitPreparePullRequestThreadMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
|
||||
return api.git.preparePullRequestThread({
|
||||
cwd: input.cwd,
|
||||
reference,
|
||||
mode,
|
||||
});
|
||||
},
|
||||
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import { WsRpcAtomClient } from "./client";
|
||||
import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
|
||||
@@ -110,11 +110,62 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetWsRpcAtomClientForTests();
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("WsRpcAtomClient", () => {
|
||||
it("runs unary requests through the AtomRpc service", async () => {
|
||||
const expectedSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
enableAssistantStreaming: true,
|
||||
defaultThreadEnvMode: "worktree" as const,
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
providers: {
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
homePath: "/tmp/codex-home",
|
||||
},
|
||||
claudeAgent: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: expectedSettings,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(expectedSettings);
|
||||
});
|
||||
|
||||
it("exposes atom-backed query state for unary RPC methods", async () => {
|
||||
const expectedSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
|
||||
+24
-22
@@ -1,31 +1,33 @@
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Layer } from "effect";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
import { AtomRpc } from "effect/unstable/reactivity";
|
||||
|
||||
import { createWsRpcProtocolLayer } from "./protocol";
|
||||
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { Duration } from "effect";
|
||||
|
||||
export const REACTIVITY_KEYS = {
|
||||
git: (cwd: string) => `git:${cwd}` as const,
|
||||
project: (cwd: string) => `project:${cwd}` as const,
|
||||
} as const;
|
||||
|
||||
export const refreshIntervalSignalAtom = Atom.family((interval: Duration.Duration) =>
|
||||
Atom.readable((get) => {
|
||||
let count = 0;
|
||||
const intervalId = window.setInterval(() => {
|
||||
get.setSelf(++count);
|
||||
}, Duration.toMillis(interval));
|
||||
get.addFinalizer(() => {
|
||||
window.clearInterval(intervalId);
|
||||
});
|
||||
return count;
|
||||
}),
|
||||
);
|
||||
|
||||
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
||||
group: WsRpcGroup,
|
||||
protocol: Layer.suspend(() => createWsRpcProtocolLayer()),
|
||||
}) {}
|
||||
|
||||
let sharedRuntime: ManagedRuntime.ManagedRuntime<WsRpcAtomClient, never> | null = null;
|
||||
|
||||
function getRuntime() {
|
||||
if (sharedRuntime !== null) {
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
export function runRpc<TSuccess, TError = never>(
|
||||
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
|
||||
}
|
||||
|
||||
export async function __resetWsRpcAtomClientForTests() {
|
||||
const runtime = sharedRuntime;
|
||||
sharedRuntime = null;
|
||||
await runtime?.dispose();
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
type GitListBranchesResult,
|
||||
type GitResolvePullRequestResult,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusResult,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { Duration, Effect, Stream } from "effect";
|
||||
import { AsyncResult, Atom, Reactivity } from "effect/unstable/reactivity";
|
||||
|
||||
import { refreshIntervalSignalAtom, WsRpcAtomClient } from "./client";
|
||||
import { REACTIVITY_KEYS } from "./client";
|
||||
import { useMemo } from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
|
||||
const GIT_ACTION_RESULT_MISSING_ERROR = {
|
||||
_tag: "GitActionResultMissing",
|
||||
message: "Git action stream completed without a final result.",
|
||||
} as const;
|
||||
export const gitRunStackedActionProgressAtom = Atom.make<GitActionProgressEvent | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("git-run-stacked-action-progress"),
|
||||
);
|
||||
|
||||
const gitStatusQueryAtom = Atom.family((cwd: string) =>
|
||||
WsRpcAtomClient.query(
|
||||
WS_METHODS.gitStatus,
|
||||
{ cwd },
|
||||
{
|
||||
timeToLive: "5 minutes",
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export const gitStatusAtom = Atom.family((cwd: string | null) =>
|
||||
Atom.readable(
|
||||
(get): AsyncResult.AsyncResult<GitStatusResult, unknown> => {
|
||||
if (cwd === null) {
|
||||
return AsyncResult.initial();
|
||||
}
|
||||
return get(gitStatusQueryAtom(cwd));
|
||||
},
|
||||
(refresh) => {
|
||||
if (cwd !== null) {
|
||||
refresh(gitStatusQueryAtom(cwd));
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const gitBranchesQueryAtom = Atom.family((cwd: string) =>
|
||||
WsRpcAtomClient.query(
|
||||
WS_METHODS.gitListBranches,
|
||||
{ cwd },
|
||||
{
|
||||
timeToLive: "5 minutes",
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export const gitBranchesAtom = Atom.family((cwd: string | null) =>
|
||||
Atom.readable(
|
||||
(get): AsyncResult.AsyncResult<GitListBranchesResult, unknown> => {
|
||||
if (cwd === null) {
|
||||
return AsyncResult.initial();
|
||||
}
|
||||
return get(gitBranchesQueryAtom(cwd));
|
||||
},
|
||||
(refresh) => {
|
||||
if (cwd !== null) {
|
||||
refresh(gitBranchesQueryAtom(cwd));
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export const gitCheckoutMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCheckout);
|
||||
|
||||
export const gitCreateBranchMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCreateBranch);
|
||||
|
||||
export const gitCreateWorktreeMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCreateWorktree);
|
||||
|
||||
export const gitInitMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitInit);
|
||||
|
||||
export const gitPreparePullRequestThreadMutationAtom = WsRpcAtomClient.mutation(
|
||||
WS_METHODS.gitPreparePullRequestThread,
|
||||
);
|
||||
|
||||
export const gitPullMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitPull);
|
||||
|
||||
export const gitRemoveWorktreeMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitRemoveWorktree);
|
||||
|
||||
export const gitRunStackedActionMutationAtom = WsRpcAtomClient.runtime
|
||||
.fn<GitRunStackedActionInput>()(
|
||||
Effect.fn(
|
||||
function* (input, get) {
|
||||
get.set(gitRunStackedActionProgressAtom, null);
|
||||
const client = yield* WsRpcAtomClient;
|
||||
return yield* client(WS_METHODS.gitRunStackedAction, input).pipe(
|
||||
Stream.runFoldEffect(
|
||||
() => null as GitRunStackedActionResult | null,
|
||||
(result, event) =>
|
||||
Effect.sync(() => {
|
||||
get.set(gitRunStackedActionProgressAtom, event);
|
||||
return event.kind === "action_finished" ? event.result : result;
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((result) =>
|
||||
result !== null ? Effect.succeed(result) : Effect.fail(GIT_ACTION_RESULT_MISSING_ERROR),
|
||||
),
|
||||
);
|
||||
},
|
||||
(effect, input) =>
|
||||
Effect.ensuring(effect, Reactivity.invalidate([REACTIVITY_KEYS.git(input.cwd)])),
|
||||
),
|
||||
)
|
||||
.pipe(Atom.withLabel("git-run-stacked-action"));
|
||||
|
||||
const gitResolvePullRequestQueryAtom = Atom.family(
|
||||
(key: { readonly cwd: string; readonly reference: string }) =>
|
||||
WsRpcAtomClient.query(WS_METHODS.gitResolvePullRequest, key, {
|
||||
timeToLive: "30 minutes",
|
||||
reactivityKeys: [REACTIVITY_KEYS.git(key.cwd)],
|
||||
}),
|
||||
);
|
||||
|
||||
export const gitResolvePullRequestAtom = Atom.family(
|
||||
(input: { readonly cwd: string | null; readonly reference: string | null }) =>
|
||||
Atom.readable(
|
||||
(get): AsyncResult.AsyncResult<GitResolvePullRequestResult, unknown> => {
|
||||
if (input.cwd === null || input.reference === null) {
|
||||
return AsyncResult.initial();
|
||||
}
|
||||
return get(
|
||||
gitResolvePullRequestQueryAtom({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
}),
|
||||
);
|
||||
},
|
||||
(refresh) => {
|
||||
if (input.cwd !== null && input.reference !== null) {
|
||||
refresh(
|
||||
gitResolvePullRequestQueryAtom({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export function useGitStatuses(
|
||||
cwds: ReadonlyArray<string>,
|
||||
): ReadonlyArray<AsyncResult.AsyncResult<GitStatusResult, unknown>> {
|
||||
const atoms = useMemo(() => {
|
||||
const refreshInterval = refreshIntervalSignalAtom(Duration.seconds(60));
|
||||
return cwds.map((cwd) => gitStatusAtom(cwd).pipe(Atom.makeRefreshOnSignal(refreshInterval)));
|
||||
}, [cwds]);
|
||||
const statusesAtom = useMemo(
|
||||
() => Atom.readable((get) => atoms.map((atom) => get(atom))),
|
||||
[atoms],
|
||||
);
|
||||
return useAtomValue(statusesAtom);
|
||||
}
|
||||
@@ -55,6 +55,7 @@ const rpcClientMock = {
|
||||
git: {
|
||||
pull: vi.fn(),
|
||||
status: vi.fn(),
|
||||
runStackedAction: vi.fn(),
|
||||
listBranches: vi.fn(),
|
||||
createWorktree: vi.fn(),
|
||||
removeWorktree: vi.fn(),
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type NativeApi,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ServerSettingsPatch,
|
||||
@@ -28,6 +31,10 @@ type RpcStreamMethod<TTag extends RpcTag> =
|
||||
? (listener: (event: TEvent) => void) => () => void
|
||||
: never;
|
||||
|
||||
interface GitRunStackedActionOptions {
|
||||
readonly onProgress?: (event: GitActionProgressEvent) => void;
|
||||
}
|
||||
|
||||
export interface WsRpcClient {
|
||||
readonly dispose: () => Promise<void>;
|
||||
readonly terminal: {
|
||||
@@ -52,6 +59,10 @@ export interface WsRpcClient {
|
||||
readonly git: {
|
||||
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
|
||||
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Promise<GitRunStackedActionResult>;
|
||||
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
|
||||
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
|
||||
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
|
||||
@@ -125,6 +136,25 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
git: {
|
||||
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
|
||||
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
|
||||
runStackedAction: async (input, options) => {
|
||||
let result: GitRunStackedActionResult | null = null;
|
||||
|
||||
await transport.requestStream(
|
||||
(client) => client[WS_METHODS.gitRunStackedAction](input),
|
||||
(event) => {
|
||||
options?.onProgress?.(event);
|
||||
if (event.kind === "action_finished") {
|
||||
result = event.result;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new Error("Git action stream completed without a final result.");
|
||||
},
|
||||
listBranches: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
|
||||
createWorktree: (input) =>
|
||||
|
||||
@@ -17,6 +17,8 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
- Refreshes the marketing-site JSON Schemas for `settings.json` and `keybindings.json` at `/schemas/settings.json` and `/schemas/keybindings.json`.
|
||||
- Commits immutable versioned JSON Schema copies at `/schemas/settings/<version>.json` and `/schemas/keybindings/<version>.json`.
|
||||
|
||||
## Desktop auto-update notes
|
||||
|
||||
|
||||
@@ -46,33 +46,55 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
|
||||
Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
|
||||
),
|
||||
Schema.Literal(".run"),
|
||||
]);
|
||||
]).annotate({
|
||||
description: "Command identifier for running a project script, formatted as `script.<id>.run`.",
|
||||
});
|
||||
|
||||
export const KeybindingCommand = Schema.Union([
|
||||
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
|
||||
SCRIPT_RUN_COMMAND_PATTERN,
|
||||
]);
|
||||
]).annotate({
|
||||
description: "Command invoked when the keybinding is triggered.",
|
||||
});
|
||||
export type KeybindingCommand = typeof KeybindingCommand.Type;
|
||||
|
||||
const KeybindingValue = TrimmedString.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
|
||||
);
|
||||
const KeybindingValue = TrimmedString.annotate({
|
||||
description:
|
||||
"Keyboard shortcut string such as `mod+j`, `ctrl+k`, or `shift+space`, using the T3 Code keybinding syntax.",
|
||||
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH));
|
||||
|
||||
const KeybindingWhen = TrimmedString.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
|
||||
);
|
||||
const KeybindingWhen = TrimmedString.annotate({
|
||||
description:
|
||||
"Optional context expression controlling when the keybinding is active, such as `terminalFocus` or `!terminalFocus`.",
|
||||
}).check(Schema.isMinLength(1), Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH));
|
||||
export const KeybindingRule = Schema.Struct({
|
||||
key: KeybindingValue,
|
||||
command: KeybindingCommand,
|
||||
when: Schema.optional(KeybindingWhen),
|
||||
key: KeybindingValue.pipe(
|
||||
Schema.flip,
|
||||
Schema.annotate({
|
||||
description: "Keyboard shortcut to listen for.",
|
||||
}),
|
||||
Schema.flip,
|
||||
),
|
||||
command: KeybindingCommand.pipe(
|
||||
Schema.annotate({
|
||||
description: "Command to execute when the shortcut matches.",
|
||||
}),
|
||||
),
|
||||
when: Schema.optional(KeybindingWhen).pipe(
|
||||
Schema.annotate({
|
||||
description: "Optional expression limiting when the shortcut is active.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description: "Single keybinding rule entry in `keybindings.json`.",
|
||||
});
|
||||
export type KeybindingRule = typeof KeybindingRule.Type;
|
||||
|
||||
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
|
||||
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
|
||||
);
|
||||
export const KeybindingsConfig = Schema.Array(KeybindingRule)
|
||||
.check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT))
|
||||
.annotate({
|
||||
description: "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
|
||||
});
|
||||
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
|
||||
|
||||
export const KeybindingShortcut = Schema.Struct({
|
||||
|
||||
@@ -9,16 +9,47 @@ export type ClaudeCodeEffort = (typeof CLAUDE_CODE_EFFORT_OPTIONS)[number];
|
||||
export type ProviderReasoningEffort = CodexReasoningEffort | ClaudeCodeEffort;
|
||||
|
||||
export const CodexModelOptions = Schema.Struct({
|
||||
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
reasoningEffort: Schema.optional(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)).pipe(
|
||||
Schema.annotate({
|
||||
description:
|
||||
"Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning.",
|
||||
}),
|
||||
),
|
||||
fastMode: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.annotate({
|
||||
description: "Whether to prefer Codex fast mode when the selected model supports it.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description: "Provider-specific text generation options for Codex models.",
|
||||
});
|
||||
export type CodexModelOptions = typeof CodexModelOptions.Type;
|
||||
|
||||
export const ClaudeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
contextWindow: Schema.optional(Schema.String),
|
||||
thinking: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.annotate({
|
||||
description: "Whether Claude should enable extended thinking for the selected model.",
|
||||
}),
|
||||
),
|
||||
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)).pipe(
|
||||
Schema.annotate({
|
||||
description:
|
||||
"Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning.",
|
||||
}),
|
||||
),
|
||||
fastMode: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.annotate({
|
||||
description: "Whether to prefer Claude fast mode when the selected model supports it.",
|
||||
}),
|
||||
),
|
||||
contextWindow: Schema.optional(Schema.String).pipe(
|
||||
Schema.annotate({
|
||||
description:
|
||||
"Optional Claude context window preset to request for the selected model, if supported.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description: "Provider-specific text generation options for Claude models.",
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
|
||||
@@ -42,20 +42,54 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
|
||||
export const CodexModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("codex"),
|
||||
model: TrimmedNonEmptyString,
|
||||
options: Schema.optionalKey(CodexModelOptions),
|
||||
provider: Schema.Literal("codex").pipe(
|
||||
Schema.annotate({
|
||||
description: "The provider used for text generation.",
|
||||
}),
|
||||
),
|
||||
model: TrimmedNonEmptyString.pipe(
|
||||
Schema.flip,
|
||||
Schema.annotate({
|
||||
description: "The Codex model slug to use for text generation.",
|
||||
}),
|
||||
Schema.flip,
|
||||
),
|
||||
options: Schema.optionalKey(CodexModelOptions).pipe(
|
||||
Schema.annotate({
|
||||
description: "Optional Codex-specific tuning knobs for the selected model.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description: "Text generation model selection for the Codex provider.",
|
||||
});
|
||||
export type CodexModelSelection = typeof CodexModelSelection.Type;
|
||||
|
||||
export const ClaudeModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("claudeAgent"),
|
||||
model: TrimmedNonEmptyString,
|
||||
options: Schema.optionalKey(ClaudeModelOptions),
|
||||
provider: Schema.Literal("claudeAgent").pipe(
|
||||
Schema.annotate({
|
||||
description: "The provider used for text generation.",
|
||||
}),
|
||||
),
|
||||
model: TrimmedNonEmptyString.pipe(
|
||||
Schema.flip,
|
||||
Schema.annotate({
|
||||
description: "The Claude model slug to use for text generation.",
|
||||
}),
|
||||
Schema.flip,
|
||||
),
|
||||
options: Schema.optionalKey(ClaudeModelOptions).pipe(
|
||||
Schema.annotate({
|
||||
description: "Optional Claude-specific tuning knobs for the selected model.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description: "Text generation model selection for the Claude provider.",
|
||||
});
|
||||
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
|
||||
|
||||
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
|
||||
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]).annotate({
|
||||
description: "Selects which provider and model T3 Code should use for text generation.",
|
||||
});
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
|
||||
@@ -23,17 +23,32 @@ export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at
|
||||
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
|
||||
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
|
||||
|
||||
const makeTrimmedStringSetting = (description: string) =>
|
||||
Schema.String.annotate({ description }).pipe(
|
||||
Schema.decodeTo(TrimmedString, SchemaTransformation.passthrough()),
|
||||
);
|
||||
|
||||
export const ClientSettingsSchema = Schema.Struct({
|
||||
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
|
||||
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
|
||||
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
|
||||
),
|
||||
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
|
||||
),
|
||||
timestampFormat: TimestampFormat.pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
confirmThreadArchive: Schema.Boolean.annotate({
|
||||
description: "Require a second click on the inline archive action before a thread is archived.",
|
||||
}).pipe(Schema.withDecodingDefault(() => false)),
|
||||
confirmThreadDelete: Schema.Boolean.annotate({
|
||||
description: "Ask before deleting a thread and its chat history.",
|
||||
}).pipe(Schema.withDecodingDefault(() => true)),
|
||||
diffWordWrap: Schema.Boolean.annotate({
|
||||
description: "Set the default wrap state when the diff panel opens.",
|
||||
}).pipe(Schema.withDecodingDefault(() => false)),
|
||||
sidebarProjectSortOrder: SidebarProjectSortOrder.annotate({
|
||||
description: "Choose how projects are ordered in the sidebar.",
|
||||
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
|
||||
sidebarThreadSortOrder: SidebarThreadSortOrder.annotate({
|
||||
description: "Choose how threads are ordered inside the selected project.",
|
||||
}).pipe(Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
|
||||
timestampFormat: TimestampFormat.annotate({
|
||||
description: "System default follows your browser or OS clock preference.",
|
||||
}).pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
}).annotate({
|
||||
description: "Client-only settings persisted locally in the browser.",
|
||||
});
|
||||
export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||
|
||||
@@ -41,11 +56,13 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS
|
||||
|
||||
// ── Server Settings (server-authoritative) ────────────────────
|
||||
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]).annotate({
|
||||
description: "Pick the default workspace mode for newly created draft threads.",
|
||||
});
|
||||
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
|
||||
|
||||
const makeBinaryPathSetting = (fallback: string) =>
|
||||
TrimmedString.pipe(
|
||||
const makeBinaryPathSetting = (fallback: string, description: string) =>
|
||||
makeTrimmedStringSetting(description).pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.String,
|
||||
SchemaTransformation.transformOrFail({
|
||||
@@ -57,26 +74,51 @@ const makeBinaryPathSetting = (fallback: string) =>
|
||||
);
|
||||
|
||||
export const CodexSettings = Schema.Struct({
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
|
||||
binaryPath: makeBinaryPathSetting("codex"),
|
||||
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
|
||||
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||
enabled: Schema.Boolean.annotate({
|
||||
description: "Whether the Codex provider is enabled and available for selection.",
|
||||
}).pipe(Schema.withDecodingDefault(() => true)),
|
||||
binaryPath: makeBinaryPathSetting("codex", "Path to the Codex binary"),
|
||||
homePath: makeTrimmedStringSetting("Optional custom Codex home and config directory.").pipe(
|
||||
Schema.withDecodingDefault(() => ""),
|
||||
),
|
||||
customModels: Schema.Array(Schema.String)
|
||||
.annotate({
|
||||
description:
|
||||
"Additional Codex model slugs to surface in the UI alongside discovered defaults.",
|
||||
})
|
||||
.pipe(Schema.withDecodingDefault(() => [])),
|
||||
}).annotate({
|
||||
description: "Server-side configuration for the Codex provider.",
|
||||
});
|
||||
export type CodexSettings = typeof CodexSettings.Type;
|
||||
|
||||
export const ClaudeSettings = Schema.Struct({
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
|
||||
binaryPath: makeBinaryPathSetting("claude"),
|
||||
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||
enabled: Schema.Boolean.annotate({
|
||||
description: "Whether the Claude provider is enabled and available for selection.",
|
||||
}).pipe(Schema.withDecodingDefault(() => true)),
|
||||
binaryPath: makeBinaryPathSetting("claude", "Path to the Claude binary"),
|
||||
customModels: Schema.Array(Schema.String)
|
||||
.annotate({
|
||||
description:
|
||||
"Additional Claude model slugs to surface in the UI alongside discovered defaults.",
|
||||
})
|
||||
.pipe(Schema.withDecodingDefault(() => [])),
|
||||
}).annotate({
|
||||
description: "Server-side configuration for the Claude provider.",
|
||||
});
|
||||
export type ClaudeSettings = typeof ClaudeSettings.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
|
||||
),
|
||||
textGenerationModelSelection: ModelSelection.pipe(
|
||||
enableAssistantStreaming: Schema.Boolean.annotate({
|
||||
description: "Show token-by-token output while a response is in progress.",
|
||||
}).pipe(Schema.withDecodingDefault(() => false)),
|
||||
defaultThreadEnvMode: ThreadEnvMode.annotate({
|
||||
description: "Pick the default workspace mode for newly created draft threads.",
|
||||
}).pipe(Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode)),
|
||||
textGenerationModelSelection: ModelSelection.annotate({
|
||||
description:
|
||||
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
|
||||
}).pipe(
|
||||
Schema.withDecodingDefault(() => ({
|
||||
provider: "codex" as const,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||
@@ -85,9 +127,19 @@ export const ServerSettings = Schema.Struct({
|
||||
|
||||
// Provider specific settings
|
||||
providers: Schema.Struct({
|
||||
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
}).pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
codex: CodexSettings.annotate({
|
||||
description: "Configuration for the Codex provider.",
|
||||
}).pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
claudeAgent: ClaudeSettings.annotate({
|
||||
description: "Configuration for the Claude provider.",
|
||||
}).pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
})
|
||||
.annotate({
|
||||
description: "Provider-specific server configuration.",
|
||||
})
|
||||
.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
}).annotate({
|
||||
description: "Server-authoritative settings persisted in `settings.json`.",
|
||||
});
|
||||
export type ServerSettings = typeof ServerSettings.Type;
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Schema } from "effect";
|
||||
import { encodePrettyJsonEffect, getSchemaDescription, toJsonSchemaObject } from "./schemaJson";
|
||||
|
||||
it.effect("encodePrettyJsonEffect writes indented JSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const encodePrettyJson = encodePrettyJsonEffect(
|
||||
Schema.Struct({
|
||||
provider: Schema.String,
|
||||
options: Schema.Struct({
|
||||
enabled: Schema.Boolean,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const encoded = yield* encodePrettyJson({
|
||||
provider: "codex",
|
||||
options: {
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(
|
||||
encoded,
|
||||
`{
|
||||
"provider": "codex",
|
||||
"options": {
|
||||
"enabled": true
|
||||
}
|
||||
}`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("toJsonSchemaObject hoists descriptions from wrapper nodes", () =>
|
||||
Effect.sync(() => {
|
||||
const schema = toJsonSchemaObject(
|
||||
Schema.Struct({
|
||||
enabled: Schema.Boolean.annotate({
|
||||
description: "Whether the feature is enabled.",
|
||||
}).pipe(Schema.withDecodingDefault(() => false)),
|
||||
name: Schema.String.annotate({
|
||||
description: "Human-readable display name.",
|
||||
}).check(Schema.isMinLength(1)),
|
||||
}),
|
||||
) as Record<string, unknown>;
|
||||
|
||||
const properties = schema.properties as Record<string, Record<string, unknown>>;
|
||||
const enabled = properties.enabled;
|
||||
const name = properties.name;
|
||||
|
||||
assert.isDefined(enabled);
|
||||
assert.isDefined(name);
|
||||
assert.strictEqual(enabled.description, "Whether the feature is enabled.");
|
||||
assert.strictEqual(name.description, "Human-readable display name.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("getSchemaDescription reads hoisted descriptions from wrapped schemas", () =>
|
||||
Effect.sync(() => {
|
||||
const enabled = Schema.Boolean.annotate({
|
||||
description: "Whether the feature is enabled.",
|
||||
}).pipe(Schema.withDecodingDefault(() => false));
|
||||
|
||||
assert.strictEqual(getSchemaDescription(enabled), "Whether the feature is enabled.");
|
||||
}),
|
||||
);
|
||||
@@ -36,6 +36,22 @@ export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown,
|
||||
};
|
||||
};
|
||||
|
||||
const schemaDescriptionCache = new WeakMap<object, string | undefined>();
|
||||
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
|
||||
export const encodePrettyJsonEffect = <S extends Schema.Top>(schema: S) =>
|
||||
Schema.encodeEffect(
|
||||
Schema.fromJsonString(schema).pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
|
||||
const squashed = Cause.squash(cause);
|
||||
return Schema.isSchemaError(squashed)
|
||||
@@ -43,6 +59,72 @@ export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
|
||||
: Cause.pretty(cause);
|
||||
};
|
||||
|
||||
function hoistJsonSchemaDescriptions(value: unknown): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(hoistJsonSchemaDescriptions);
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") {
|
||||
return value;
|
||||
}
|
||||
|
||||
const record = Object.fromEntries(
|
||||
Object.entries(value).map(([key, entry]) => [key, hoistJsonSchemaDescriptions(entry)]),
|
||||
) as Record<string, unknown>;
|
||||
|
||||
if (typeof record.description !== "string") {
|
||||
const candidates = ["allOf", "anyOf", "oneOf"]
|
||||
.flatMap((key) => (Array.isArray(record[key]) ? (record[key] as ReadonlyArray<unknown>) : []))
|
||||
.filter((candidate): candidate is Record<string, unknown> => {
|
||||
return !!candidate && typeof candidate === "object" && !Array.isArray(candidate);
|
||||
});
|
||||
|
||||
const description = candidates.find(
|
||||
(candidate) =>
|
||||
typeof candidate.description === "string" &&
|
||||
!(candidate.type === "null" && Object.keys(candidate).length <= 1),
|
||||
)?.description;
|
||||
|
||||
if (typeof description === "string") {
|
||||
record.description = description;
|
||||
}
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
|
||||
export const toJsonSchemaObject = (schema: Schema.Top): unknown => {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return hoistJsonSchemaDescriptions({ ...document.schema, $defs: document.definitions });
|
||||
}
|
||||
return hoistJsonSchemaDescriptions(document.schema);
|
||||
};
|
||||
|
||||
export const getSchemaDescription = (schema: Schema.Top): string | undefined => {
|
||||
if (schema && typeof schema === "object") {
|
||||
const cached = schemaDescriptionCache.get(schema);
|
||||
if (cached !== undefined || schemaDescriptionCache.has(schema)) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
const jsonSchema = toJsonSchemaObject(schema);
|
||||
const description =
|
||||
jsonSchema && typeof jsonSchema === "object" && !Array.isArray(jsonSchema)
|
||||
? typeof (jsonSchema as Record<string, unknown>).description === "string"
|
||||
? ((jsonSchema as Record<string, unknown>).description as string)
|
||||
: undefined
|
||||
: undefined;
|
||||
|
||||
if (schema && typeof schema === "object") {
|
||||
schemaDescriptionCache.set(schema, description);
|
||||
}
|
||||
|
||||
return description;
|
||||
};
|
||||
|
||||
/**
|
||||
* A `Getter` that parses a lenient JSON string (tolerating trailing commas
|
||||
* and JS-style comments) into an unknown value.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import {
|
||||
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
|
||||
writeKeybindingsJsonSchemas,
|
||||
} from "./lib/keybindings-schema.ts";
|
||||
import {
|
||||
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
|
||||
writeServerSettingsJsonSchemas,
|
||||
} from "./lib/server-settings-schema.ts";
|
||||
|
||||
const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
writeServerSettingsJsonSchemas({ rootDir });
|
||||
writeKeybindingsJsonSchemas({ rootDir });
|
||||
|
||||
console.log(`Wrote ${SERVER_SETTINGS_SCHEMA_RELATIVE_PATH}`);
|
||||
console.log(`Wrote ${KEYBINDINGS_SCHEMA_RELATIVE_PATH}`);
|
||||
@@ -0,0 +1,76 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
import { type Schema } from "effect";
|
||||
|
||||
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
const JSON_SCHEMA_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";
|
||||
|
||||
export function buildJsonSchemaDocument(
|
||||
schema: Schema.Top,
|
||||
options: {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
},
|
||||
): Record<string, unknown> {
|
||||
const jsonSchema = toJsonSchemaObject(schema);
|
||||
if (!jsonSchema || typeof jsonSchema !== "object" || Array.isArray(jsonSchema)) {
|
||||
throw new Error(
|
||||
`${options.title} JSON schema must be an object or array JSON schema document.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
$schema: JSON_SCHEMA_DRAFT_2020_12,
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
...jsonSchema,
|
||||
};
|
||||
}
|
||||
|
||||
function writeJsonFileIfChanged(filePath: string, document: Record<string, unknown>): boolean {
|
||||
const nextContent = `${JSON.stringify(document, null, 2)}\n`;
|
||||
const previousContent = (() => {
|
||||
try {
|
||||
return readFileSync(filePath, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
if (previousContent === nextContent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
writeFileSync(filePath, nextContent);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function writeJsonSchemaArtifacts(options: {
|
||||
readonly rootDir?: string;
|
||||
readonly version?: string;
|
||||
readonly latestRelativePath: string;
|
||||
readonly getVersionedRelativePath: (version: string) => string;
|
||||
readonly document: Record<string, unknown>;
|
||||
}): {
|
||||
readonly changed: boolean;
|
||||
} {
|
||||
const rootDir = resolve(options.rootDir ?? process.cwd());
|
||||
const latestChanged = writeJsonFileIfChanged(
|
||||
resolve(rootDir, options.latestRelativePath),
|
||||
options.document,
|
||||
);
|
||||
let changed = latestChanged;
|
||||
|
||||
if (options.version && latestChanged) {
|
||||
changed =
|
||||
writeJsonFileIfChanged(
|
||||
resolve(rootDir, options.getVersionedRelativePath(options.version)),
|
||||
options.document,
|
||||
) || changed;
|
||||
}
|
||||
|
||||
return { changed };
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildKeybindingsJsonSchema,
|
||||
getVersionedKeybindingsSchemaRelativePath,
|
||||
KEYBINDINGS_SCHEMA_RELATIVE_PATH,
|
||||
writeKeybindingsJsonSchemas,
|
||||
} from "./keybindings-schema";
|
||||
|
||||
describe("buildKeybindingsJsonSchema", () => {
|
||||
it("builds a JSON schema document for keybindings.json", () => {
|
||||
const schema = buildKeybindingsJsonSchema();
|
||||
|
||||
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
|
||||
expect(schema.title).toBe("T3 Code Keybindings");
|
||||
expect(schema.type).toBe("array");
|
||||
expect(schema.items).toMatchObject({
|
||||
description: expect.stringContaining("keybinding rule"),
|
||||
type: "object",
|
||||
properties: {
|
||||
key: {
|
||||
description: expect.stringContaining("shortcut"),
|
||||
},
|
||||
command: {
|
||||
description: expect.stringContaining("execute"),
|
||||
},
|
||||
when: {
|
||||
description: expect.stringContaining("active"),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("writes latest and versioned schema files", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
|
||||
|
||||
try {
|
||||
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
|
||||
expect(result.changed).toBe(true);
|
||||
|
||||
const latestSchema = JSON.parse(
|
||||
readFileSync(resolve(rootDir, KEYBINDINGS_SCHEMA_RELATIVE_PATH), "utf8"),
|
||||
) as Record<string, unknown>;
|
||||
const versionedSchema = JSON.parse(
|
||||
readFileSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")), "utf8"),
|
||||
) as Record<string, unknown>;
|
||||
|
||||
expect(latestSchema).toEqual(versionedSchema);
|
||||
expect(latestSchema.title).toBe("T3 Code Keybindings");
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-keybindings-schema-"));
|
||||
|
||||
try {
|
||||
const latestOnly = writeKeybindingsJsonSchemas({ rootDir });
|
||||
expect(latestOnly.changed).toBe(true);
|
||||
|
||||
const result = writeKeybindingsJsonSchemas({ rootDir, version: "1.2.3" });
|
||||
expect(result.changed).toBe(false);
|
||||
expect(existsSync(resolve(rootDir, getVersionedKeybindingsSchemaRelativePath("1.2.3")))).toBe(
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { KeybindingsConfig } from "../../packages/contracts/src/keybindings.ts";
|
||||
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
|
||||
|
||||
export const KEYBINDINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/keybindings.json";
|
||||
export const KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
|
||||
"apps/marketing/public/schemas/keybindings";
|
||||
|
||||
export const getVersionedKeybindingsSchemaRelativePath = (version: string) =>
|
||||
`${KEYBINDINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
|
||||
|
||||
export function buildKeybindingsJsonSchema(): Record<string, unknown> {
|
||||
return buildJsonSchemaDocument(KeybindingsConfig, {
|
||||
title: "T3 Code Keybindings",
|
||||
description: "JSON Schema for the keybindings.json file consumed by T3 Code.",
|
||||
});
|
||||
}
|
||||
|
||||
export function writeKeybindingsJsonSchemas(options?: {
|
||||
readonly rootDir?: string;
|
||||
readonly version?: string;
|
||||
}): {
|
||||
readonly changed: boolean;
|
||||
} {
|
||||
return writeJsonSchemaArtifacts({
|
||||
latestRelativePath: KEYBINDINGS_SCHEMA_RELATIVE_PATH,
|
||||
getVersionedRelativePath: getVersionedKeybindingsSchemaRelativePath,
|
||||
document: buildKeybindingsJsonSchema(),
|
||||
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
|
||||
...(options?.version === undefined ? {} : { version: options.version }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildServerSettingsJsonSchema,
|
||||
getVersionedServerSettingsSchemaRelativePath,
|
||||
SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
|
||||
writeServerSettingsJsonSchemas,
|
||||
} from "./server-settings-schema";
|
||||
|
||||
describe("buildServerSettingsJsonSchema", () => {
|
||||
it("builds a JSON schema document for settings.json", () => {
|
||||
const schema = buildServerSettingsJsonSchema();
|
||||
|
||||
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
|
||||
expect(schema.title).toBe("T3 Code Server Settings");
|
||||
expect(schema.type).toBe("object");
|
||||
expect(schema.additionalProperties).toBe(false);
|
||||
expect(schema.properties).toMatchObject({
|
||||
$schema: {
|
||||
type: "string",
|
||||
},
|
||||
enableAssistantStreaming: {
|
||||
description: "Show token-by-token output while a response is in progress.",
|
||||
},
|
||||
defaultThreadEnvMode: {
|
||||
description: "Pick the default workspace mode for newly created draft threads.",
|
||||
},
|
||||
textGenerationModelSelection: {
|
||||
description:
|
||||
"Configure the model used for generated commit messages, PR titles, and similar Git text.",
|
||||
},
|
||||
providers: {
|
||||
description: expect.stringContaining("Provider-specific"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("writes latest and versioned schema files", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
|
||||
|
||||
try {
|
||||
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
|
||||
expect(result.changed).toBe(true);
|
||||
|
||||
const latestSchema = JSON.parse(
|
||||
readFileSync(resolve(rootDir, SERVER_SETTINGS_SCHEMA_RELATIVE_PATH), "utf8"),
|
||||
) as Record<string, unknown>;
|
||||
const versionedSchema = JSON.parse(
|
||||
readFileSync(
|
||||
resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3")),
|
||||
"utf8",
|
||||
),
|
||||
) as Record<string, unknown>;
|
||||
|
||||
expect(latestSchema).toEqual(versionedSchema);
|
||||
expect(latestSchema.title).toBe("T3 Code Server Settings");
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("skips writing a versioned schema file when the latest schema is unchanged", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-server-settings-schema-"));
|
||||
|
||||
try {
|
||||
const latestOnly = writeServerSettingsJsonSchemas({ rootDir });
|
||||
expect(latestOnly.changed).toBe(true);
|
||||
|
||||
const result = writeServerSettingsJsonSchemas({ rootDir, version: "1.2.3" });
|
||||
expect(result.changed).toBe(false);
|
||||
expect(
|
||||
existsSync(resolve(rootDir, getVersionedServerSettingsSchemaRelativePath("1.2.3"))),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ServerSettings } from "@t3tools/contracts/settings";
|
||||
import { buildJsonSchemaDocument, writeJsonSchemaArtifacts } from "./json-schema";
|
||||
|
||||
export const SERVER_SETTINGS_SCHEMA_RELATIVE_PATH = "apps/marketing/public/schemas/settings.json";
|
||||
export const SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH =
|
||||
"apps/marketing/public/schemas/settings";
|
||||
|
||||
export const getVersionedServerSettingsSchemaRelativePath = (version: string) =>
|
||||
`${SERVER_SETTINGS_VERSIONED_SCHEMA_DIRECTORY_RELATIVE_PATH}/${version}.json`;
|
||||
|
||||
export function buildServerSettingsJsonSchema(): Record<string, unknown> {
|
||||
const schema = buildJsonSchemaDocument(ServerSettings, {
|
||||
title: "T3 Code Server Settings",
|
||||
description: "JSON Schema for the server-authoritative settings.json file consumed by T3 Code.",
|
||||
});
|
||||
|
||||
const properties =
|
||||
schema.type === "object" &&
|
||||
schema.properties &&
|
||||
typeof schema.properties === "object" &&
|
||||
!Array.isArray(schema.properties)
|
||||
? schema.properties
|
||||
: null;
|
||||
|
||||
if (!properties) {
|
||||
throw new Error("ServerSettings JSON schema must expose object properties.");
|
||||
}
|
||||
|
||||
return {
|
||||
...schema,
|
||||
properties: {
|
||||
$schema: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL.",
|
||||
},
|
||||
...properties,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function writeServerSettingsJsonSchemas(options?: {
|
||||
readonly rootDir?: string;
|
||||
readonly version?: string;
|
||||
}): {
|
||||
readonly changed: boolean;
|
||||
} {
|
||||
return writeJsonSchemaArtifacts({
|
||||
latestRelativePath: SERVER_SETTINGS_SCHEMA_RELATIVE_PATH,
|
||||
getVersionedRelativePath: getVersionedServerSettingsSchemaRelativePath,
|
||||
document: buildServerSettingsJsonSchema(),
|
||||
...(options?.rootDir === undefined ? {} : { rootDir: options.rootDir }),
|
||||
...(options?.version === undefined ? {} : { version: options.version }),
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -81,7 +89,7 @@ try {
|
||||
copyWorkspaceManifestFixture(tempRoot);
|
||||
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
"bun",
|
||||
[
|
||||
resolve(repoRoot, "scripts/update-release-package-versions.ts"),
|
||||
"9.9.9-smoke.0",
|
||||
@@ -106,6 +114,52 @@ try {
|
||||
"Expected bun.lock to contain the smoke version.",
|
||||
);
|
||||
|
||||
const latestSchemaPath = resolve(tempRoot, "apps/marketing/public/schemas/settings.json");
|
||||
const versionedSchemaPath = resolve(
|
||||
tempRoot,
|
||||
"apps/marketing/public/schemas/settings/9.9.9-smoke.0.json",
|
||||
);
|
||||
const latestKeybindingsSchemaPath = resolve(
|
||||
tempRoot,
|
||||
"apps/marketing/public/schemas/keybindings.json",
|
||||
);
|
||||
const versionedKeybindingsSchemaPath = resolve(
|
||||
tempRoot,
|
||||
"apps/marketing/public/schemas/keybindings/9.9.9-smoke.0.json",
|
||||
);
|
||||
if (!existsSync(latestSchemaPath)) {
|
||||
throw new Error(
|
||||
"Expected release version alignment to generate the latest server settings schema.",
|
||||
);
|
||||
}
|
||||
if (!existsSync(versionedSchemaPath)) {
|
||||
throw new Error(
|
||||
"Expected release version alignment to generate the versioned server settings schema.",
|
||||
);
|
||||
}
|
||||
if (!existsSync(latestKeybindingsSchemaPath)) {
|
||||
throw new Error(
|
||||
"Expected release version alignment to generate the latest keybindings schema.",
|
||||
);
|
||||
}
|
||||
if (!existsSync(versionedKeybindingsSchemaPath)) {
|
||||
throw new Error(
|
||||
"Expected release version alignment to generate the versioned keybindings schema.",
|
||||
);
|
||||
}
|
||||
const versionedSchema = readFileSync(versionedSchemaPath, "utf8");
|
||||
assertContains(
|
||||
versionedSchema,
|
||||
'"title": "T3 Code Server Settings"',
|
||||
"Expected versioned server settings schema to contain schema metadata.",
|
||||
);
|
||||
const versionedKeybindingsSchema = readFileSync(versionedKeybindingsSchemaPath, "utf8");
|
||||
assertContains(
|
||||
versionedKeybindingsSchema,
|
||||
'"title": "T3 Code Keybindings"',
|
||||
"Expected versioned keybindings schema to contain schema metadata.",
|
||||
);
|
||||
|
||||
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
|
||||
@@ -12,5 +12,9 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"../packages/contracts/src/baseSchemas.ts",
|
||||
"../packages/contracts/src/keybindings.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
releasePackageFiles,
|
||||
updateReleasePackageVersions,
|
||||
} from "./update-release-package-versions";
|
||||
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema";
|
||||
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema";
|
||||
|
||||
describe("updateReleasePackageVersions", () => {
|
||||
it("updates package versions and writes latest plus versioned config schemas", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
|
||||
|
||||
try {
|
||||
for (const relativePath of releasePackageFiles) {
|
||||
const filePath = resolve(rootDir, relativePath);
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
writeFileSync(
|
||||
filePath,
|
||||
`${JSON.stringify({ name: relativePath, version: "0.0.0" }, null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = updateReleasePackageVersions("1.2.3", { rootDir });
|
||||
expect(result.changed).toBe(true);
|
||||
|
||||
for (const relativePath of releasePackageFiles) {
|
||||
const packageJson = JSON.parse(readFileSync(resolve(rootDir, relativePath), "utf8")) as {
|
||||
version?: string;
|
||||
};
|
||||
expect(packageJson.version).toBe("1.2.3");
|
||||
}
|
||||
|
||||
expect(
|
||||
JSON.parse(
|
||||
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/settings.json"), "utf8"),
|
||||
),
|
||||
).toMatchObject({ title: "T3 Code Server Settings" });
|
||||
|
||||
expect(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json"),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).toMatchObject({ title: "T3 Code Server Settings" });
|
||||
|
||||
expect(
|
||||
JSON.parse(
|
||||
readFileSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings.json"), "utf8"),
|
||||
),
|
||||
).toMatchObject({ title: "T3 Code Keybindings" });
|
||||
|
||||
expect(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json"),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).toMatchObject({ title: "T3 Code Keybindings" });
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("skips versioned schema snapshots when the latest schemas are unchanged", () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "t3-release-version-bump-"));
|
||||
|
||||
try {
|
||||
for (const relativePath of releasePackageFiles) {
|
||||
const filePath = resolve(rootDir, relativePath);
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
writeFileSync(
|
||||
filePath,
|
||||
`${JSON.stringify({ name: relativePath, version: "1.2.3" }, null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
writeServerSettingsJsonSchemas({ rootDir });
|
||||
writeKeybindingsJsonSchemas({ rootDir });
|
||||
|
||||
const result = updateReleasePackageVersions("1.2.3", { rootDir });
|
||||
expect(result.changed).toBe(false);
|
||||
|
||||
expect(
|
||||
existsSync(resolve(rootDir, "apps/marketing/public/schemas/settings/1.2.3.json")),
|
||||
).toBe(false);
|
||||
expect(
|
||||
existsSync(resolve(rootDir, "apps/marketing/public/schemas/keybindings/1.2.3.json")),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,9 @@ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { writeKeybindingsJsonSchemas } from "./lib/keybindings-schema.ts";
|
||||
import { writeServerSettingsJsonSchemas } from "./lib/server-settings-schema.ts";
|
||||
|
||||
export const releasePackageFiles = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
@@ -37,6 +40,9 @@ export function updateReleasePackageVersions(
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed = writeServerSettingsJsonSchemas({ rootDir, version }).changed || changed;
|
||||
changed = writeKeybindingsJsonSchemas({ rootDir, version }).changed || changed;
|
||||
|
||||
return { changed };
|
||||
}
|
||||
|
||||
@@ -99,7 +105,7 @@ if (isMain) {
|
||||
);
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
console.log("All release version artifacts already match the requested version.");
|
||||
}
|
||||
|
||||
if (writeGithubOutput) {
|
||||
|
||||
Reference in new issue
Block a user