Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11091bf337 | ||
|
|
49dda48a4f |
No files matched your search
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||||
`bun run dev -- --base-dir ~/.t3-2`
|
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
|
||||||
* text=auto eol=lf
|
|
||||||
@@ -96,19 +96,10 @@ body:
|
|||||||
- type: textarea
|
- type: textarea
|
||||||
id: logs
|
id: logs
|
||||||
attributes:
|
attributes:
|
||||||
label: Logs or stack traces
|
label: Logs, stack traces, or screenshots
|
||||||
description: Paste the most relevant output only. Redact secrets.
|
description: Paste the most relevant output only. Redact secrets.
|
||||||
render: shell
|
render: shell
|
||||||
|
|
||||||
- type: upload
|
|
||||||
id: attachments
|
|
||||||
attributes:
|
|
||||||
label: Screenshots, recordings, or supporting files
|
|
||||||
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
|
|
||||||
|
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: workaround
|
id: workaround
|
||||||
attributes:
|
attributes:
|
||||||
|
|||||||
+1
-2
@@ -28,5 +28,4 @@ github:realAhmedRoach
|
|||||||
github:shiroyasha9
|
github:shiroyasha9
|
||||||
github:Yash-Singh1
|
github:Yash-Singh1
|
||||||
github:eggfriedrice24
|
github:eggfriedrice24
|
||||||
github:Ymit24
|
github:Ymit24
|
||||||
github:shivamhwp
|
|
||||||
+11
-101
@@ -24,32 +24,32 @@ jobs:
|
|||||||
{
|
{
|
||||||
name: "size:XS",
|
name: "size:XS",
|
||||||
color: "0e8a16",
|
color: "0e8a16",
|
||||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
description: "0-9 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:S",
|
name: "size:S",
|
||||||
color: "5ebd3e",
|
color: "5ebd3e",
|
||||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
description: "10-29 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:M",
|
name: "size:M",
|
||||||
color: "fbca04",
|
color: "fbca04",
|
||||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
description: "30-99 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:L",
|
name: "size:L",
|
||||||
color: "fe7d37",
|
color: "fe7d37",
|
||||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
description: "100-499 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XL",
|
name: "size:XL",
|
||||||
color: "d93f0b",
|
color: "d93f0b",
|
||||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
description: "500-999 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XXL",
|
name: "size:XXL",
|
||||||
color: "b60205",
|
color: "b60205",
|
||||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
description: "1,000+ changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -124,49 +124,19 @@ jobs:
|
|||||||
group: pr-size-${{ github.event.pull_request.number }}
|
group: pr-size-${{ github.event.pull_request.number }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout base repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Sync PR size label
|
- name: Sync PR size label
|
||||||
uses: actions/github-script@v8
|
uses: actions/github-script@v8
|
||||||
env:
|
env:
|
||||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const { execFileSync } = require("node:child_process");
|
|
||||||
|
|
||||||
const issueNumber = context.payload.pull_request.number;
|
const issueNumber = context.payload.pull_request.number;
|
||||||
const baseSha = context.payload.pull_request.base.sha;
|
const additions = context.payload.pull_request.additions ?? 0;
|
||||||
const headSha = context.payload.pull_request.head.sha;
|
const deletions = context.payload.pull_request.deletions ?? 0;
|
||||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
const changedLines = additions + deletions;
|
||||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||||
|
|
||||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
|
||||||
const testExcludePathspecs = [
|
|
||||||
":(glob,exclude)**/__tests__/**",
|
|
||||||
":(glob,exclude)**/test/**",
|
|
||||||
":(glob,exclude)**/tests/**",
|
|
||||||
":(glob,exclude)apps/server/integration/**",
|
|
||||||
":(glob,exclude)**/*.test.*",
|
|
||||||
":(glob,exclude)**/*.spec.*",
|
|
||||||
":(glob,exclude)**/*.browser.*",
|
|
||||||
":(glob,exclude)**/*.integration.*",
|
|
||||||
];
|
|
||||||
|
|
||||||
const sumNumstat = (text) =>
|
|
||||||
text
|
|
||||||
.split("\n")
|
|
||||||
.filter(Boolean)
|
|
||||||
.reduce((total, line) => {
|
|
||||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
|
||||||
const additions =
|
|
||||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
|
||||||
const deletions =
|
|
||||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
|
||||||
|
|
||||||
return total + additions + deletions;
|
|
||||||
}, 0);
|
|
||||||
|
|
||||||
const resolveSizeLabel = (totalChangedLines) => {
|
const resolveSizeLabel = (totalChangedLines) => {
|
||||||
if (totalChangedLines < 10) {
|
if (totalChangedLines < 10) {
|
||||||
@@ -192,55 +162,6 @@ jobs:
|
|||||||
return "size:XXL";
|
return "size:XXL";
|
||||||
};
|
};
|
||||||
|
|
||||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
|
||||||
stdio: "inherit",
|
|
||||||
});
|
|
||||||
|
|
||||||
execFileSync(
|
|
||||||
"git",
|
|
||||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
|
||||||
{
|
|
||||||
stdio: "inherit",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
|
||||||
encoding: "utf8",
|
|
||||||
}).trim();
|
|
||||||
|
|
||||||
if (resolvedHeadSha !== headSha) {
|
|
||||||
core.warning(
|
|
||||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
|
||||||
stdio: "inherit",
|
|
||||||
});
|
|
||||||
|
|
||||||
const diffArgs = [
|
|
||||||
"diff",
|
|
||||||
"--numstat",
|
|
||||||
"--ignore-all-space",
|
|
||||||
"--ignore-blank-lines",
|
|
||||||
`${baseSha}...${resolvedHeadSha}`,
|
|
||||||
];
|
|
||||||
|
|
||||||
const totalChangedLines = sumNumstat(
|
|
||||||
execFileSync(
|
|
||||||
"git",
|
|
||||||
diffArgs,
|
|
||||||
{ encoding: "utf8" },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const nonTestChangedLines = sumNumstat(
|
|
||||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
|
||||||
encoding: "utf8",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
|
||||||
|
|
||||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
|
||||||
const nextLabelName = resolveSizeLabel(changedLines);
|
const nextLabelName = resolveSizeLabel(changedLines);
|
||||||
|
|
||||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||||
@@ -278,15 +199,4 @@ jobs:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const classification =
|
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
||||||
nonTestChangedLines === 0
|
|
||||||
? testChangedLines > 0
|
|
||||||
? "test-only PR"
|
|
||||||
: "no line changes"
|
|
||||||
: testChangedLines > 0
|
|
||||||
? "test lines excluded"
|
|
||||||
: "all non-test changes";
|
|
||||||
|
|
||||||
core.info(
|
|
||||||
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
|
||||||
);
|
|
||||||
@@ -308,31 +308,11 @@ jobs:
|
|||||||
needs: [preflight, release]
|
needs: [preflight, release]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
steps:
|
steps:
|
||||||
- id: app_token
|
|
||||||
name: Mint release app token
|
|
||||||
uses: actions/create-github-app-token@v2
|
|
||||||
with:
|
|
||||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
|
||||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
|
||||||
owner: ${{ github.repository_owner }}
|
|
||||||
|
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
with:
|
with:
|
||||||
ref: main
|
ref: main
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
token: ${{ steps.app_token.outputs.token }}
|
|
||||||
persist-credentials: true
|
|
||||||
|
|
||||||
- id: app_bot
|
|
||||||
name: Resolve GitHub App bot identity
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ steps.app_token.outputs.token }}
|
|
||||||
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
|
|
||||||
run: |
|
|
||||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
|
||||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Setup Bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v2
|
uses: oven-sh/setup-bun@v2
|
||||||
@@ -369,8 +349,8 @@ jobs:
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
git config user.name "github-actions[bot]"
|
||||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
|
||||||
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 bun.lock
|
||||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||||
|
|||||||
@@ -12,12 +12,7 @@ packages/*/dist
|
|||||||
build/
|
build/
|
||||||
.logs/
|
.logs/
|
||||||
release/
|
release/
|
||||||
release-mock/
|
|
||||||
.t3
|
.t3
|
||||||
.idea/
|
|
||||||
apps/web/.playwright
|
apps/web/.playwright
|
||||||
apps/web/playwright-report
|
apps/web/playwright-report
|
||||||
apps/web/src/components/__screenshots__
|
apps/web/src/components/__screenshots__
|
||||||
.vitest-*
|
|
||||||
__screenshots__/
|
|
||||||
.tanstack
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||||
"ignorePatterns": [
|
"ignorePatterns": [
|
||||||
".reference",
|
|
||||||
".plans",
|
".plans",
|
||||||
"dist",
|
"dist",
|
||||||
"dist-electron",
|
"dist-electron",
|
||||||
|
|||||||
@@ -1,441 +0,0 @@
|
|||||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
|
||||||
|
|
||||||
## Why this plan was rewritten
|
|
||||||
|
|
||||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
|
||||||
|
|
||||||
1. `orchestration.dispatchCommand` (client intent)
|
|
||||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
|
||||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
|
||||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
|
||||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
|
||||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
|
||||||
|
|
||||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Current constraints to design around (post-Stage 1)
|
|
||||||
|
|
||||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
|
||||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
|
||||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
|
||||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
|
||||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
|
||||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Architecture target
|
|
||||||
|
|
||||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
|
||||||
|
|
||||||
Key decisions:
|
|
||||||
|
|
||||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
|
||||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
|
||||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
|
||||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 1: Contracts and command shape updates
|
|
||||||
|
|
||||||
### 1.1 Provider-aware model contract
|
|
||||||
|
|
||||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
|
||||||
|
|
||||||
Expected outcomes:
|
|
||||||
|
|
||||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
|
||||||
2. Add helpers that resolve model by provider.
|
|
||||||
3. Preserve backwards compatibility for existing Codex defaults.
|
|
||||||
|
|
||||||
### 1.2 Turn-start provider intent
|
|
||||||
|
|
||||||
Update `packages/contracts/src/orchestration.ts`:
|
|
||||||
|
|
||||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
|
||||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
|
||||||
3. Keep existing command valid when provider is omitted.
|
|
||||||
|
|
||||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
|
||||||
|
|
||||||
### 1.3 Provider session start input for Claude runtime knobs (completed)
|
|
||||||
|
|
||||||
Update `packages/contracts/src/provider.ts`:
|
|
||||||
|
|
||||||
1. Move provider-specific start fields into typed `providerOptions`:
|
|
||||||
- `providerOptions.codex`
|
|
||||||
- `providerOptions.claudeCode`
|
|
||||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
|
||||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
|
||||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
|
||||||
|
|
||||||
### 1.4 Contract tests (completed)
|
|
||||||
|
|
||||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
|
||||||
|
|
||||||
1. New command payload shape.
|
|
||||||
2. Provider-aware model resolution behavior.
|
|
||||||
3. Breaking-change expectations for removed top-level provider fields.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 2: Claude adapter implementation
|
|
||||||
|
|
||||||
### 2.1 Add adapter service + layer
|
|
||||||
|
|
||||||
Create:
|
|
||||||
|
|
||||||
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
|
|
||||||
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
|
|
||||||
|
|
||||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
|
||||||
|
|
||||||
### 2.1.a SDK dependency and baseline config
|
|
||||||
|
|
||||||
Add server dependency:
|
|
||||||
|
|
||||||
1. `@anthropic-ai/claude-agent-sdk`
|
|
||||||
|
|
||||||
Baseline adapter options to support from day one:
|
|
||||||
|
|
||||||
1. `cwd`
|
|
||||||
2. `model`
|
|
||||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
|
||||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
|
||||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
|
||||||
6. `resume`
|
|
||||||
7. `resumeSessionAt`
|
|
||||||
8. `includePartialMessages`
|
|
||||||
9. `canUseTool`
|
|
||||||
10. `hooks`
|
|
||||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
|
||||||
|
|
||||||
### 2.2 Claude runtime bridge
|
|
||||||
|
|
||||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
|
||||||
|
|
||||||
Required capabilities:
|
|
||||||
|
|
||||||
1. Long-lived session context per adapter session.
|
|
||||||
2. Multi-turn input queue.
|
|
||||||
3. Interrupt support.
|
|
||||||
4. Approval request/response bridge.
|
|
||||||
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
|
|
||||||
|
|
||||||
#### 2.2.a Agent SDK details to preserve
|
|
||||||
|
|
||||||
The adapter should explicitly rely on these SDK capabilities:
|
|
||||||
|
|
||||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
|
||||||
2. Multi-turn input is supported via async-iterable prompt input.
|
|
||||||
3. Tool approval decisions are provided via `canUseTool`.
|
|
||||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
|
||||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
|
||||||
|
|
||||||
#### 2.2.b Effect-native session lifecycle skeleton
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
||||||
import { Effect } from "effect";
|
|
||||||
|
|
||||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
|
||||||
Effect.acquireRelease(
|
|
||||||
Effect.tryPromise({
|
|
||||||
try: async () => {
|
|
||||||
const claudeOptions = input.providerOptions?.claudeCode;
|
|
||||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
|
||||||
const abortController = new AbortController();
|
|
||||||
const result = query({
|
|
||||||
prompt: makePromptAsyncIterable(),
|
|
||||||
options: {
|
|
||||||
cwd: input.cwd,
|
|
||||||
model: input.model,
|
|
||||||
permissionMode: claudeOptions?.permissionMode,
|
|
||||||
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
|
|
||||||
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
|
|
||||||
resume: resumeState?.threadId,
|
|
||||||
resumeSessionAt: resumeState?.sessionAt,
|
|
||||||
signal: abortController.signal,
|
|
||||||
includePartialMessages: true,
|
|
||||||
canUseTool: makeCanUseTool(),
|
|
||||||
hooks: makeClaudeHooks(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return { abortController, result };
|
|
||||||
},
|
|
||||||
catch: (cause) =>
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId: "pending",
|
|
||||||
detail: "Failed to start Claude runtime session.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
|
||||||
|
|
||||||
Preferred when available in the pinned Effect version:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
|
||||||
session.result,
|
|
||||||
(cause) =>
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId,
|
|
||||||
detail: "Claude runtime stream failed.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Portable fallback (already aligned with current server patterns):
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
|
|
||||||
let cancelled = false;
|
|
||||||
void (async () => {
|
|
||||||
try {
|
|
||||||
for await (const message of session.result) {
|
|
||||||
if (cancelled) break;
|
|
||||||
emit.single(message);
|
|
||||||
}
|
|
||||||
emit.end();
|
|
||||||
} catch (cause) {
|
|
||||||
emit.fail(
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId,
|
|
||||||
detail: "Claude runtime stream failed.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return Effect.sync(() => {
|
|
||||||
cancelled = true;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.3 Canonical event mapping
|
|
||||||
|
|
||||||
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
|
|
||||||
|
|
||||||
Initial mapping target:
|
|
||||||
|
|
||||||
1. assistant text deltas -> `content.delta`
|
|
||||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
|
||||||
3. approval requests -> `request.opened`
|
|
||||||
4. approval results -> `request.resolved`
|
|
||||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
|
||||||
6. errors -> `runtime.error`
|
|
||||||
7. plan/proposed-plan content when derivable
|
|
||||||
|
|
||||||
Implementation note:
|
|
||||||
|
|
||||||
1. Keep raw Claude message on `raw` for debugging.
|
|
||||||
2. Prefer canonical item/request kinds over provider-native enums.
|
|
||||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
|
||||||
|
|
||||||
### 2.4 Resume cursor strategy
|
|
||||||
|
|
||||||
Define Claude-owned opaque resume state, e.g.:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface ClaudeResumeCursor {
|
|
||||||
readonly version: 1;
|
|
||||||
readonly threadId?: string;
|
|
||||||
readonly sessionAt?: string;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
|
||||||
2. Parse/validate only inside Claude adapter.
|
|
||||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
|
||||||
4. Never overload orchestration thread id as Claude thread id.
|
|
||||||
|
|
||||||
### 2.5 Interrupt and stop semantics
|
|
||||||
|
|
||||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
|
||||||
|
|
||||||
1. `interruptTurn()` -> active query interrupt.
|
|
||||||
2. `stopSession()` -> close session resources and prevent future sends.
|
|
||||||
3. `rollbackThread()` -> see Phase 4.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 3: Provider service and composition
|
|
||||||
|
|
||||||
### 3.1 Register Claude adapter
|
|
||||||
|
|
||||||
Update provider registry layer to include Claude:
|
|
||||||
|
|
||||||
1. add `claudeCode` -> `ClaudeAdapter`
|
|
||||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
|
||||||
|
|
||||||
### 3.2 Persist provider binding
|
|
||||||
|
|
||||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
|
||||||
|
|
||||||
Required validation:
|
|
||||||
|
|
||||||
1. Claude bindings survive restart.
|
|
||||||
2. resume cursor remains opaque and round-trips untouched.
|
|
||||||
3. stopAll + restart can recover Claude sessions when possible.
|
|
||||||
|
|
||||||
### 3.3 Provider start routing
|
|
||||||
|
|
||||||
Update `ProviderCommandReactor` / orchestration flow:
|
|
||||||
|
|
||||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
|
||||||
2. If a thread already has Claude session binding, reuse it.
|
|
||||||
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 4: Checkpoint and revert strategy
|
|
||||||
|
|
||||||
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
|
|
||||||
|
|
||||||
Pick one explicit strategy:
|
|
||||||
|
|
||||||
### Option A: provider-native rewind
|
|
||||||
|
|
||||||
If SDK/runtime supports safe rewind:
|
|
||||||
|
|
||||||
1. implement in Claude adapter
|
|
||||||
2. keep `CheckpointReactor` unchanged
|
|
||||||
|
|
||||||
### Option B: session restart + state truncation shim
|
|
||||||
|
|
||||||
If no native rewind exists:
|
|
||||||
|
|
||||||
1. Claude adapter returns successful rollback by:
|
|
||||||
- stopping current Claude session
|
|
||||||
- clearing/rewriting stored Claude resume cursor to last safe resumable point
|
|
||||||
- forcing next turn to recreate session from persisted orchestration state
|
|
||||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
|
||||||
|
|
||||||
Whichever option is chosen:
|
|
||||||
|
|
||||||
1. behavior must be deterministic
|
|
||||||
2. checkpoint revert tests must pass under orchestration expectations
|
|
||||||
3. user-visible activity log should explain failures clearly when provider rollback is impossible
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 5: Web integration
|
|
||||||
|
|
||||||
### 5.1 Provider picker and model picker
|
|
||||||
|
|
||||||
Update web state/UI:
|
|
||||||
|
|
||||||
1. allow choosing Claude as thread provider before first turn
|
|
||||||
2. show Claude model list from provider-aware model helpers
|
|
||||||
3. preserve existing Codex default behavior when provider omitted
|
|
||||||
|
|
||||||
Likely touch points:
|
|
||||||
|
|
||||||
1. `apps/web/src/store.ts`
|
|
||||||
2. `apps/web/src/components/ChatView.tsx`
|
|
||||||
3. `apps/web/src/types.ts`
|
|
||||||
4. `packages/shared/src/model.ts`
|
|
||||||
|
|
||||||
### 5.2 Settings for Claude executable/options
|
|
||||||
|
|
||||||
Add app settings if needed for:
|
|
||||||
|
|
||||||
1. Claude binary path
|
|
||||||
2. default permission mode
|
|
||||||
3. default max thinking tokens
|
|
||||||
|
|
||||||
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
|
|
||||||
|
|
||||||
### 5.3 Session rendering
|
|
||||||
|
|
||||||
No new WS channel should be needed. Claude should appear through existing:
|
|
||||||
|
|
||||||
1. thread messages
|
|
||||||
2. activities/worklog
|
|
||||||
3. approvals
|
|
||||||
4. session state
|
|
||||||
5. checkpoints/diffs
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 6: Testing strategy
|
|
||||||
|
|
||||||
### 6.1 Contract tests
|
|
||||||
|
|
||||||
Cover:
|
|
||||||
|
|
||||||
1. provider-aware model schemas
|
|
||||||
2. provider field on turn-start command
|
|
||||||
3. provider-specific start options schema
|
|
||||||
|
|
||||||
### 6.2 Adapter layer tests
|
|
||||||
|
|
||||||
Add `ClaudeAdapter.test.ts` covering:
|
|
||||||
|
|
||||||
1. session start
|
|
||||||
2. event mapping
|
|
||||||
3. approval bridge
|
|
||||||
4. resume cursor parse/serialize
|
|
||||||
5. interrupt behavior
|
|
||||||
6. rollback behavior or explicit unsupported error path
|
|
||||||
|
|
||||||
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
|
|
||||||
|
|
||||||
### 6.3 Provider service integration tests
|
|
||||||
|
|
||||||
Extend provider integration coverage so Claude is exercised through `ProviderService`:
|
|
||||||
|
|
||||||
1. start Claude session
|
|
||||||
2. send turn
|
|
||||||
3. receive canonical runtime events
|
|
||||||
4. restart/recover using persisted binding
|
|
||||||
|
|
||||||
### 6.4 Orchestration integration tests
|
|
||||||
|
|
||||||
Add/extend integration tests around:
|
|
||||||
|
|
||||||
1. first-turn provider selection
|
|
||||||
2. Claude approval requests routed through orchestration
|
|
||||||
3. Claude runtime ingestion -> messages/activities/session updates
|
|
||||||
4. checkpoint revert behavior under Claude
|
|
||||||
5. stopAll/restart recovery
|
|
||||||
|
|
||||||
These should validate real orchestration flows, not just adapter behavior.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 7: Rollout order
|
|
||||||
|
|
||||||
Recommended implementation order:
|
|
||||||
|
|
||||||
1. contracts/provider-aware models
|
|
||||||
2. provider field on turn-start
|
|
||||||
3. Claude adapter skeleton + start/send/stream
|
|
||||||
4. canonical event mapping
|
|
||||||
5. provider registry/service wiring
|
|
||||||
6. orchestration recovery + checkpoint strategy
|
|
||||||
7. web provider/model picker
|
|
||||||
8. full integration tests
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Non-goals
|
|
||||||
|
|
||||||
1. Reintroducing provider-specific WS methods/channels.
|
|
||||||
2. Storing provider-native thread ids as orchestration ids.
|
|
||||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
|
||||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
# Replace React Query With AtomRpc + Atom State
|
|
||||||
|
|
||||||
## Summary
|
|
||||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
|
||||||
- Keep Zustand for orchestration read model and UI state.
|
|
||||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
|
||||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
|
||||||
|
|
||||||
## Target Architecture
|
|
||||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
|
||||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
|
||||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
|
||||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
|
||||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
|
||||||
|
|
||||||
## Phase 1: Infrastructure First
|
|
||||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
|
||||||
2. Build the AtomRpc client on top of that layer.
|
|
||||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
|
||||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
|
||||||
5. Land this as a no-behavior-change PR.
|
|
||||||
|
|
||||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
|
||||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
|
||||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
|
||||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
|
||||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
|
||||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
|
||||||
|
|
||||||
## Phase 3: Replace React Query Domain By Domain
|
|
||||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
|
||||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
|
||||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
|
||||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
|
||||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
|
||||||
6. Defer the desktop updater until the last phase.
|
|
||||||
|
|
||||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
|
||||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
|
||||||
2. Keep Zustand orchestration/event application unchanged.
|
|
||||||
3. Map current effects exactly:
|
|
||||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
|
||||||
- file creation/deletion/restoration touches `project:${cwd}`
|
|
||||||
- config-affecting server events touch `server-config`
|
|
||||||
|
|
||||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
|
||||||
1. Create narrow modules instead of a replacement mega-facade:
|
|
||||||
- `rpc/orchestrationActions.ts`
|
|
||||||
- `rpc/terminalActions.ts`
|
|
||||||
- `rpc/gitActions.ts`
|
|
||||||
- `rpc/projectActions.ts`
|
|
||||||
- `platform/desktopBridge.ts`
|
|
||||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
|
||||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
|
||||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
|
||||||
|
|
||||||
## Phase 6: Remove React Query Completely
|
|
||||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
|
||||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
|
||||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
|
||||||
4. Delete the old query-option tests.
|
|
||||||
|
|
||||||
## Public Interfaces And Types
|
|
||||||
- Preserve the current server-state hook names during the transition.
|
|
||||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
|
||||||
- Do not expose raw AtomRpc clients to components.
|
|
||||||
- Do not add Suspense as part of this migration.
|
|
||||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
|
||||||
|
|
||||||
## Test Plan
|
|
||||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
|
||||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
|
||||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
|
||||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
|
||||||
- Acceptance scenarios:
|
|
||||||
- welcome still bootstraps snapshot and navigation
|
|
||||||
- keybindings toast still responds to config stream updates
|
|
||||||
- git status/branches refresh after checkout/pull/worktree actions
|
|
||||||
- PR resolve dialog keeps cached result while typing
|
|
||||||
- `@` path search refreshes after file mutations and orchestration events
|
|
||||||
- diff panel refreshes when checkpoints arrive
|
|
||||||
- desktop updater still reflects push events and button actions
|
|
||||||
|
|
||||||
## Assumptions And Defaults
|
|
||||||
- Zustand stays in scope; only `react-query` is being removed.
|
|
||||||
- `desktopBridge` remains the only non-RPC boundary.
|
|
||||||
- The migration lands as 5-6 small PRs, each green independently.
|
|
||||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
|
||||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
|
||||||
@@ -3,11 +3,11 @@
|
|||||||
## Task Completion Requirements
|
## Task Completion Requirements
|
||||||
|
|
||||||
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
||||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest)..
|
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||||
|
|
||||||
## Project Snapshot
|
## Project Snapshot
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||||
|
|
||||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
|
|||||||
|
|
||||||
## Maintainability
|
## Maintainability
|
||||||
|
|
||||||
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||||
|
|
||||||
## Package Roles
|
## Package Roles
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +1,19 @@
|
|||||||
# T3 Code
|
# T3 Code
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||||
|
|
||||||
## Installation
|
## How to use
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> T3 Code currently supports Codex and Claude.
|
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||||
> Install and authenticate at least one provider before use:
|
|
||||||
>
|
|
||||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
|
||||||
> - Claude: install Claude Code and run `claude auth login`
|
|
||||||
|
|
||||||
### Run without installing
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx t3
|
npx t3
|
||||||
```
|
```
|
||||||
|
|
||||||
### Desktop app
|
You can also just install the desktop app. It's cooler.
|
||||||
|
|
||||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||||
|
|
||||||
#### Windows (`winget`)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
winget install T3Tools.T3Code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### macOS (Homebrew)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
brew install --cask t3-code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Arch Linux (AUR)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
yay -S t3code-bin
|
|
||||||
```
|
|
||||||
|
|
||||||
## Some notes
|
## Some notes
|
||||||
|
|
||||||
|
|||||||
@@ -6,24 +6,21 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
|
|||||||
|
|
||||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||||
|
|
||||||
| CLI flag | Env var | Notes |
|
| CLI flag | Env var | Notes |
|
||||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
| ----------------------- | --------------------- | ---------------------------------- |
|
||||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
|
||||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
|
||||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
|
||||||
|
|
||||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||||
|
|
||||||
## Security First
|
## Security First
|
||||||
|
|
||||||
- Always set `--auth-token` before exposing the server outside localhost.
|
- Always set `--auth-token` before exposing the server outside localhost.
|
||||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
|
||||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
|
||||||
- Treat the token like a password.
|
- Treat the token like a password.
|
||||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@t3tools/desktop",
|
"name": "@t3tools/desktop",
|
||||||
"version": "0.0.15",
|
"version": "0.0.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -24,7 +24,8 @@
|
|||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:"
|
"vitest": "catalog:",
|
||||||
|
"wait-on": "^8.0.2"
|
||||||
},
|
},
|
||||||
"productName": "T3 Code (Alpha)"
|
"productName": "T3 Code (Alpha)"
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,27 @@
|
|||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
import { watch } from "node:fs";
|
import { watch } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
import waitOn from "wait-on";
|
||||||
|
|
||||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||||
import { waitForResources } from "./wait-for-resources.mjs";
|
|
||||||
|
|
||||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||||
const devServerUrl = `http://localhost:${port}`;
|
const devServerUrl = `http://localhost:${port}`;
|
||||||
const requiredFiles = [
|
const requiredFiles = [
|
||||||
"dist-electron/main.js",
|
"dist-electron/main.js",
|
||||||
"dist-electron/preload.js",
|
"dist-electron/preload.js",
|
||||||
"../server/dist/bin.mjs",
|
"../server/dist/index.mjs",
|
||||||
];
|
];
|
||||||
const watchedDirectories = [
|
const watchedDirectories = [
|
||||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||||
];
|
];
|
||||||
const forcedShutdownTimeoutMs = 1_500;
|
const forcedShutdownTimeoutMs = 1_500;
|
||||||
const restartDebounceMs = 120;
|
const restartDebounceMs = 120;
|
||||||
const childTreeGracePeriodMs = 1_200;
|
const childTreeGracePeriodMs = 1_200;
|
||||||
|
|
||||||
await waitForResources({
|
await waitOn({
|
||||||
baseDir: desktopDir,
|
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||||
files: requiredFiles,
|
|
||||||
tcpPort: port,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const childEnv = { ...process.env };
|
const childEnv = { ...process.env };
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
import * as FileSystem from "node:fs/promises";
|
|
||||||
import * as Net from "node:net";
|
|
||||||
import * as Path from "node:path";
|
|
||||||
import * as Timers from "node:timers/promises";
|
|
||||||
|
|
||||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
|
||||||
|
|
||||||
async function fileExists(filePath) {
|
|
||||||
try {
|
|
||||||
await FileSystem.access(filePath);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
|
||||||
return new Promise((resolveReady) => {
|
|
||||||
const socket = Net.createConnection({ host, port });
|
|
||||||
let settled = false;
|
|
||||||
|
|
||||||
const finish = (ready) => {
|
|
||||||
if (settled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
settled = true;
|
|
||||||
socket.removeAllListeners();
|
|
||||||
socket.destroy();
|
|
||||||
resolveReady(ready);
|
|
||||||
};
|
|
||||||
|
|
||||||
socket.once("connect", () => {
|
|
||||||
finish(true);
|
|
||||||
});
|
|
||||||
socket.once("timeout", () => {
|
|
||||||
finish(false);
|
|
||||||
});
|
|
||||||
socket.once("error", () => {
|
|
||||||
finish(false);
|
|
||||||
});
|
|
||||||
socket.setTimeout(connectTimeoutMs);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
|
||||||
const pendingFiles = [];
|
|
||||||
|
|
||||||
for (const relativeFilePath of files) {
|
|
||||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
|
||||||
if (!ready) {
|
|
||||||
pendingFiles.push(relativeFilePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let tcpReady = false;
|
|
||||||
for (const host of tcpHosts) {
|
|
||||||
tcpReady = await tcpPortIsReady({
|
|
||||||
host,
|
|
||||||
port: tcpPort,
|
|
||||||
connectTimeoutMs,
|
|
||||||
});
|
|
||||||
if (tcpReady) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
pendingFiles,
|
|
||||||
tcpReady,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitForResources({
|
|
||||||
baseDir,
|
|
||||||
files = [],
|
|
||||||
intervalMs = 100,
|
|
||||||
timeoutMs = 120_000,
|
|
||||||
tcpHost,
|
|
||||||
tcpPort,
|
|
||||||
connectTimeoutMs = 500,
|
|
||||||
}) {
|
|
||||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
|
||||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
|
||||||
}
|
|
||||||
|
|
||||||
const startedAt = Date.now();
|
|
||||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
|
||||||
baseDir,
|
|
||||||
files,
|
|
||||||
tcpPort,
|
|
||||||
tcpHosts,
|
|
||||||
connectTimeoutMs,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (pendingFiles.length === 0 && tcpReady) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Date.now() - startedAt >= timeoutMs) {
|
|
||||||
const pendingResources = [];
|
|
||||||
if (!tcpReady) {
|
|
||||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
|
||||||
}
|
|
||||||
for (const filePath of pendingFiles) {
|
|
||||||
pendingResources.push(`file:${filePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(
|
|
||||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await Timers.setTimeout(intervalMs);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
|||||||
const options = {
|
const options = {
|
||||||
type: "question" as const,
|
type: "question" as const,
|
||||||
buttons: ["No", "Yes"],
|
buttons: ["No", "Yes"],
|
||||||
defaultId: 0,
|
defaultId: CONFIRM_BUTTON_INDEX,
|
||||||
cancelId: 0,
|
cancelId: 0,
|
||||||
noLink: true,
|
noLink: true,
|
||||||
message: normalizedMessage,
|
message: normalizedMessage,
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||||
|
|
||||||
|
export function fixPath(): void {
|
||||||
|
if (process.platform !== "darwin") return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||||
|
const result = readPathFromLoginShell(shell);
|
||||||
|
if (result) {
|
||||||
|
process.env.PATH = result;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Keep inherited PATH if shell lookup fails.
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
-113
@@ -20,7 +20,6 @@ import * as Effect from "effect/Effect";
|
|||||||
import type {
|
import type {
|
||||||
DesktopTheme,
|
DesktopTheme,
|
||||||
DesktopUpdateActionResult,
|
DesktopUpdateActionResult,
|
||||||
DesktopUpdateCheckResult,
|
|
||||||
DesktopUpdateState,
|
DesktopUpdateState,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { autoUpdater } from "electron-updater";
|
import { autoUpdater } from "electron-updater";
|
||||||
@@ -29,7 +28,7 @@ import type { ContextMenuItem } from "@t3tools/contracts";
|
|||||||
import { NetService } from "@t3tools/shared/Net";
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
import { fixPath } from "./fixPath";
|
||||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||||
import {
|
import {
|
||||||
createInitialDesktopUpdateState,
|
createInitialDesktopUpdateState,
|
||||||
@@ -45,7 +44,7 @@ import {
|
|||||||
} from "./updateMachine";
|
} from "./updateMachine";
|
||||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||||
|
|
||||||
syncShellEnvironment();
|
fixPath();
|
||||||
|
|
||||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||||
@@ -57,17 +56,13 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
|||||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
const STATE_DIR =
|
||||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
|
||||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
|
||||||
const DESKTOP_SCHEME = "t3";
|
const DESKTOP_SCHEME = "t3";
|
||||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
|
||||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
|
||||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||||
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||||
@@ -82,9 +77,6 @@ const DESKTOP_UPDATE_CHANNEL = "latest";
|
|||||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||||
|
|
||||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||||
type LinuxDesktopNamedApp = Electron.App & {
|
|
||||||
setDesktopName?: (desktopName: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
let mainWindow: BrowserWindow | null = null;
|
let mainWindow: BrowserWindow | null = null;
|
||||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||||
@@ -121,17 +113,6 @@ function sanitizeLogValue(value: string): string {
|
|||||||
return value.replace(/\s+/g, " ").trim();
|
return value.replace(/\s+/g, " ").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function backendChildEnv(): NodeJS.ProcessEnv {
|
|
||||||
const env = { ...process.env };
|
|
||||||
delete env.T3CODE_PORT;
|
|
||||||
delete env.T3CODE_AUTH_TOKEN;
|
|
||||||
delete env.T3CODE_MODE;
|
|
||||||
delete env.T3CODE_NO_BROWSER;
|
|
||||||
delete env.T3CODE_HOST;
|
|
||||||
delete env.T3CODE_DESKTOP_WS_URL;
|
|
||||||
return env;
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeDesktopLogHeader(message: string): void {
|
function writeDesktopLogHeader(message: string): void {
|
||||||
if (!desktopLogSink) return;
|
if (!desktopLogSink) return;
|
||||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||||
@@ -268,10 +249,6 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
|||||||
|
|
||||||
initializePackagedLogging();
|
initializePackagedLogging();
|
||||||
|
|
||||||
if (process.platform === "linux") {
|
|
||||||
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||||
if (process.platform !== "darwin") return undefined;
|
if (process.platform !== "darwin") return undefined;
|
||||||
if (destructiveMenuIconCache !== undefined) {
|
if (destructiveMenuIconCache !== undefined) {
|
||||||
@@ -298,12 +275,10 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
|||||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let updateCheckInFlight = false;
|
let updateCheckInFlight = false;
|
||||||
let updateDownloadInFlight = false;
|
let updateDownloadInFlight = false;
|
||||||
let updateInstallInFlight = false;
|
|
||||||
let updaterConfigured = false;
|
let updaterConfigured = false;
|
||||||
let updateState: DesktopUpdateState = initialUpdateState();
|
let updateState: DesktopUpdateState = initialUpdateState();
|
||||||
|
|
||||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||||
if (updateInstallInFlight) return "install";
|
|
||||||
if (updateDownloadInFlight) return "download";
|
if (updateDownloadInFlight) return "download";
|
||||||
if (updateCheckInFlight) return "check";
|
if (updateCheckInFlight) return "check";
|
||||||
return updateState.errorContext;
|
return updateState.errorContext;
|
||||||
@@ -399,7 +374,7 @@ function resolveAboutCommitHash(): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveBackendEntry(): string {
|
function resolveBackendEntry(): string {
|
||||||
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
|
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveBackendCwd(): string {
|
function resolveBackendCwd(): string {
|
||||||
@@ -724,10 +699,6 @@ function configureAppIdentity(): void {
|
|||||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.platform === "linux") {
|
|
||||||
(app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.platform === "darwin" && app.dock) {
|
if (process.platform === "darwin" && app.dock) {
|
||||||
const iconPath = resolveIconPath("png");
|
const iconPath = resolveIconPath("png");
|
||||||
if (iconPath) {
|
if (iconPath) {
|
||||||
@@ -771,13 +742,13 @@ function shouldEnableAutoUpdates(): boolean {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkForUpdates(reason: string): Promise<boolean> {
|
async function checkForUpdates(reason: string): Promise<void> {
|
||||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
|
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||||
console.info(
|
console.info(
|
||||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||||
);
|
);
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
updateCheckInFlight = true;
|
updateCheckInFlight = true;
|
||||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||||
@@ -785,14 +756,12 @@ async function checkForUpdates(reason: string): Promise<boolean> {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await autoUpdater.checkForUpdates();
|
await autoUpdater.checkForUpdates();
|
||||||
return true;
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
setUpdateState(
|
setUpdateState(
|
||||||
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
||||||
);
|
);
|
||||||
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
||||||
return true;
|
|
||||||
} finally {
|
} finally {
|
||||||
updateCheckInFlight = false;
|
updateCheckInFlight = false;
|
||||||
}
|
}
|
||||||
@@ -826,22 +795,13 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
|||||||
}
|
}
|
||||||
|
|
||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
updateInstallInFlight = true;
|
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
try {
|
try {
|
||||||
await stopBackendAndWaitForExit();
|
await stopBackendAndWaitForExit();
|
||||||
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
|
autoUpdater.quitAndInstall();
|
||||||
for (const win of BrowserWindow.getAllWindows()) {
|
return { accepted: true, completed: true };
|
||||||
win.destroy();
|
|
||||||
}
|
|
||||||
// `quitAndInstall()` only starts the handoff to the updater. The actual
|
|
||||||
// install may still fail asynchronously, so keep the action incomplete
|
|
||||||
// until we either quit or receive an updater error.
|
|
||||||
autoUpdater.quitAndInstall(true, true);
|
|
||||||
return { accepted: true, completed: false };
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = formatErrorMessage(error);
|
const message = formatErrorMessage(error);
|
||||||
updateInstallInFlight = false;
|
|
||||||
isQuitting = false;
|
isQuitting = false;
|
||||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||||
@@ -878,13 +838,6 @@ function configureAutoUpdater(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
|
|
||||||
autoUpdater.setFeedURL({
|
|
||||||
provider: "generic",
|
|
||||||
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
autoUpdater.autoDownload = false;
|
autoUpdater.autoDownload = false;
|
||||||
autoUpdater.autoInstallOnAppQuit = false;
|
autoUpdater.autoInstallOnAppQuit = false;
|
||||||
// Keep alpha branding, but force all installs onto the stable update track.
|
// Keep alpha branding, but force all installs onto the stable update track.
|
||||||
@@ -921,13 +874,6 @@ function configureAutoUpdater(): void {
|
|||||||
});
|
});
|
||||||
autoUpdater.on("error", (error) => {
|
autoUpdater.on("error", (error) => {
|
||||||
const message = formatErrorMessage(error);
|
const message = formatErrorMessage(error);
|
||||||
if (updateInstallInFlight) {
|
|
||||||
updateInstallInFlight = false;
|
|
||||||
isQuitting = false;
|
|
||||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
|
||||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||||
setUpdateState({
|
setUpdateState({
|
||||||
status: "error",
|
status: "error",
|
||||||
@@ -972,6 +918,17 @@ function configureAutoUpdater(): void {
|
|||||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||||
updatePollTimer.unref();
|
updatePollTimer.unref();
|
||||||
}
|
}
|
||||||
|
function backendEnv(): NodeJS.ProcessEnv {
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_NO_BROWSER: "1",
|
||||||
|
T3CODE_PORT: String(backendPort),
|
||||||
|
T3CODE_STATE_DIR: STATE_DIR,
|
||||||
|
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function scheduleBackendRestart(reason: string): void {
|
function scheduleBackendRestart(reason: string): void {
|
||||||
if (isQuitting || restartTimer) return;
|
if (isQuitting || restartTimer) return;
|
||||||
|
|
||||||
@@ -995,35 +952,16 @@ function startBackend(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||||
cwd: resolveBackendCwd(),
|
cwd: resolveBackendCwd(),
|
||||||
// In Electron main, process.execPath points to the Electron binary.
|
// In Electron main, process.execPath points to the Electron binary.
|
||||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||||
env: {
|
env: {
|
||||||
...backendChildEnv(),
|
...backendEnv(),
|
||||||
ELECTRON_RUN_AS_NODE: "1",
|
ELECTRON_RUN_AS_NODE: "1",
|
||||||
},
|
},
|
||||||
stdio: captureBackendLogs
|
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||||
? ["ignore", "pipe", "pipe", "pipe"]
|
|
||||||
: ["ignore", "inherit", "inherit", "pipe"],
|
|
||||||
});
|
});
|
||||||
const bootstrapStream = child.stdio[3];
|
|
||||||
if (bootstrapStream && "write" in bootstrapStream) {
|
|
||||||
bootstrapStream.write(
|
|
||||||
`${JSON.stringify({
|
|
||||||
mode: "desktop",
|
|
||||||
noBrowser: true,
|
|
||||||
port: backendPort,
|
|
||||||
t3Home: BASE_DIR,
|
|
||||||
authToken: backendAuthToken,
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
bootstrapStream.end();
|
|
||||||
} else {
|
|
||||||
child.kill("SIGTERM");
|
|
||||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
backendProcess = child;
|
backendProcess = child;
|
||||||
let backendSessionClosed = false;
|
let backendSessionClosed = false;
|
||||||
const closeBackendSession = (details: string) => {
|
const closeBackendSession = (details: string) => {
|
||||||
@@ -1134,11 +1072,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function registerIpcHandlers(): void {
|
function registerIpcHandlers(): void {
|
||||||
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
|
|
||||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
|
||||||
event.returnValue = backendWsUrl;
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||||
@@ -1183,7 +1116,6 @@ function registerIpcHandlers(): void {
|
|||||||
id: item.id,
|
id: item.id,
|
||||||
label: item.label,
|
label: item.label,
|
||||||
destructive: item.destructive === true,
|
destructive: item.destructive === true,
|
||||||
disabled: item.disabled === true,
|
|
||||||
}));
|
}));
|
||||||
if (normalizedItems.length === 0) {
|
if (normalizedItems.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -1214,7 +1146,6 @@ function registerIpcHandlers(): void {
|
|||||||
}
|
}
|
||||||
const itemOption: MenuItemConstructorOptions = {
|
const itemOption: MenuItemConstructorOptions = {
|
||||||
label: item.label,
|
label: item.label,
|
||||||
enabled: !item.disabled,
|
|
||||||
click: () => resolve(item.id),
|
click: () => resolve(item.id),
|
||||||
};
|
};
|
||||||
if (item.destructive) {
|
if (item.destructive) {
|
||||||
@@ -1280,21 +1211,6 @@ function registerIpcHandlers(): void {
|
|||||||
state: updateState,
|
state: updateState,
|
||||||
} satisfies DesktopUpdateActionResult;
|
} satisfies DesktopUpdateActionResult;
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
|
|
||||||
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
|
|
||||||
if (!updaterConfigured) {
|
|
||||||
return {
|
|
||||||
checked: false,
|
|
||||||
state: updateState,
|
|
||||||
} satisfies DesktopUpdateCheckResult;
|
|
||||||
}
|
|
||||||
const checked = await checkForUpdates("web-ui");
|
|
||||||
return {
|
|
||||||
checked,
|
|
||||||
state: updateState,
|
|
||||||
} satisfies DesktopUpdateCheckResult;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getIconOption(): { icon: string } | Record<string, never> {
|
function getIconOption(): { icon: string } | Record<string, never> {
|
||||||
@@ -1404,9 +1320,9 @@ async function bootstrap(): Promise<void> {
|
|||||||
);
|
);
|
||||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||||
|
|
||||||
registerIpcHandlers();
|
registerIpcHandlers();
|
||||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||||
@@ -1418,7 +1334,6 @@ async function bootstrap(): Promise<void> {
|
|||||||
|
|
||||||
app.on("before-quit", () => {
|
app.on("before-quit", () => {
|
||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
updateInstallInFlight = false;
|
|
||||||
writeDesktopLogHeader("before-quit received");
|
writeDesktopLogHeader("before-quit received");
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
stopBackend();
|
stopBackend();
|
||||||
@@ -1448,7 +1363,7 @@ app
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.on("window-all-closed", () => {
|
app.on("window-all-closed", () => {
|
||||||
if (process.platform !== "darwin" && !isQuitting) {
|
if (process.platform !== "darwin") {
|
||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,16 +9,12 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
|||||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
|
||||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getWsUrl: () => {
|
getWsUrl: () => wsUrl,
|
||||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
|
||||||
return typeof result === "string" ? result : null;
|
|
||||||
},
|
|
||||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||||
@@ -36,7 +32,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
|
||||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||||
onUpdateState: (listener) => {
|
onUpdateState: (listener) => {
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
|
||||||
|
|
||||||
describe("syncShellEnvironment", () => {
|
|
||||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "/bin/zsh",
|
|
||||||
PATH: "/usr/bin",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "darwin",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
|
||||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "/bin/zsh",
|
|
||||||
PATH: "/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "darwin",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves inherited values when the login shell omits them", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "/bin/zsh",
|
|
||||||
PATH: "/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "darwin",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "/bin/zsh",
|
|
||||||
PATH: "/usr/bin",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "linux",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
|
||||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does nothing outside macOS and linux", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
|
||||||
PATH: "C:\\Windows\\System32",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/usr/local/bin:/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "win32",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(readEnvironment).not.toHaveBeenCalled();
|
|
||||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import {
|
|
||||||
readEnvironmentFromLoginShell,
|
|
||||||
resolveLoginShell,
|
|
||||||
ShellEnvironmentReader,
|
|
||||||
} from "@t3tools/shared/shell";
|
|
||||||
|
|
||||||
export function syncShellEnvironment(
|
|
||||||
env: NodeJS.ProcessEnv = process.env,
|
|
||||||
options: {
|
|
||||||
platform?: NodeJS.Platform;
|
|
||||||
readEnvironment?: ShellEnvironmentReader;
|
|
||||||
} = {},
|
|
||||||
): void {
|
|
||||||
const platform = options.platform ?? process.platform;
|
|
||||||
if (platform !== "darwin" && platform !== "linux") return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const shell = resolveLoginShell(platform, env.SHELL);
|
|
||||||
if (!shell) return;
|
|
||||||
|
|
||||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
|
||||||
"PATH",
|
|
||||||
"SSH_AUTH_SOCK",
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (shellEnvironment.PATH) {
|
|
||||||
env.PATH = shellEnvironment.PATH;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
|
||||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Keep inherited environment if shell lookup fails.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
ProviderKind,
|
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
Effect,
|
Effect,
|
||||||
Exit,
|
Exit,
|
||||||
FileSystem,
|
|
||||||
Layer,
|
Layer,
|
||||||
ManagedRuntime,
|
ManagedRuntime,
|
||||||
Option,
|
Option,
|
||||||
Path,
|
|
||||||
Ref,
|
Ref,
|
||||||
Schedule,
|
Schedule,
|
||||||
Schema,
|
Schema,
|
||||||
@@ -24,7 +24,6 @@ import {
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
|
||||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
@@ -38,7 +37,6 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
|||||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
|
||||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||||
@@ -67,9 +65,7 @@ import {
|
|||||||
makeTestProviderAdapterHarness,
|
makeTestProviderAdapterHarness,
|
||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
import { ServerConfig } from "../src/config.ts";
|
||||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
|
||||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -79,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
function initializeGitWorkspace(cwd: string) {
|
||||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
|
||||||
runGit(cwd, ["add", "."]);
|
runGit(cwd, ["add", "."]);
|
||||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||||
});
|
}
|
||||||
|
|
||||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||||
try {
|
try {
|
||||||
@@ -126,7 +120,7 @@ function waitFor<A, E>(
|
|||||||
read: Effect.Effect<A, E>,
|
read: Effect.Effect<A, E>,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 40_000,
|
timeoutMs = 10_000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
const RETRY_SIGNAL = "wait_for_retry";
|
const RETRY_SIGNAL = "wait_for_retry";
|
||||||
const retryIntervalMs = 10;
|
const retryIntervalMs = 10;
|
||||||
@@ -211,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||||
readonly provider?: ProviderKind;
|
readonly provider?: "codex";
|
||||||
readonly realCodex?: boolean;
|
readonly realCodex?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const path = yield* Path.Path;
|
const sleep = (ms: number) => Effect.sleep(ms);
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
const provider = options?.provider ?? "codex";
|
const provider = options?.provider ?? "codex";
|
||||||
const useRealCodex = options?.realCodex === true;
|
const useRealCodex = options?.realCodex === true;
|
||||||
const adapterHarness = useRealCodex
|
const adapterHarness = useRealCodex
|
||||||
@@ -238,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||||
} as typeof ProviderAdapterRegistry.Service)
|
} as typeof ProviderAdapterRegistry.Service)
|
||||||
: null;
|
: null;
|
||||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||||
prefix: "t3-orchestration-integration-",
|
|
||||||
});
|
|
||||||
const workspaceDir = path.join(rootDir, "workspace");
|
const workspaceDir = path.join(rootDir, "workspace");
|
||||||
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
const stateDir = path.join(rootDir, "state");
|
||||||
Effect.provideService(Path.Path, path),
|
const dbPath = path.join(stateDir, "state.sqlite");
|
||||||
);
|
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||||
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
fs.mkdirSync(stateDir, { recursive: true });
|
||||||
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
initializeGitWorkspace(workspaceDir);
|
||||||
yield* initializeGitWorkspace(workspaceDir);
|
|
||||||
|
|
||||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
@@ -272,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}),
|
}),
|
||||||
).pipe(
|
).pipe(
|
||||||
Layer.provide(makeCodexAdapterLive()),
|
Layer.provide(makeCodexAdapterLive()),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
);
|
);
|
||||||
@@ -288,45 +277,32 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provide(AnalyticsService.layerTest),
|
Layer.provide(AnalyticsService.layerTest),
|
||||||
);
|
);
|
||||||
|
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
ProjectionCheckpointRepositoryLive,
|
ProjectionCheckpointRepositoryLive,
|
||||||
ProjectionPendingApprovalRepositoryLive,
|
ProjectionPendingApprovalRepositoryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
RuntimeReceiptBusLive,
|
RuntimeReceiptBusLive,
|
||||||
);
|
);
|
||||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
|
||||||
);
|
);
|
||||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
Effect.succeed({ branch: input.newBranch }),
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
} as unknown as GitCoreShape);
|
} as unknown as GitCoreShape);
|
||||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
|
||||||
} as unknown as TextGenerationShape);
|
} as unknown as TextGenerationShape);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(textGenerationLayer),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(
|
|
||||||
WorkspaceEntriesLive.pipe(
|
|
||||||
Layer.provide(WorkspacePathsLive),
|
|
||||||
Layer.provideMerge(gitCoreLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(WorkspacePathsLive),
|
|
||||||
);
|
);
|
||||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeIngestionLayer),
|
Layer.provideMerge(runtimeIngestionLayer),
|
||||||
@@ -335,8 +311,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
);
|
);
|
||||||
const layer = orchestrationReactorLayer.pipe(
|
const layer = orchestrationReactorLayer.pipe(
|
||||||
Layer.provide(persistenceLayer),
|
Layer.provide(persistenceLayer),
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -370,13 +345,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
|
|
||||||
const scope = yield* Scope.make("sequential");
|
const scope = yield* Scope.make("sequential");
|
||||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||||
).pipe(Effect.orDie);
|
).pipe(Effect.orDie);
|
||||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||||
).pipe(Effect.forkIn(scope));
|
).pipe(Effect.forkIn(scope));
|
||||||
yield* Effect.sleep(10);
|
yield* sleep(10);
|
||||||
|
|
||||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||||
threadId,
|
threadId,
|
||||||
@@ -493,7 +468,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* shutdown;
|
yield* shutdown.pipe(
|
||||||
|
Effect.ensuring(
|
||||||
|
Effect.sync(() => {
|
||||||
|
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
ProviderTurnStartResult,
|
ProviderTurnStartResult,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
ProviderKind,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Queue, Stream } from "effect";
|
import { Effect, Queue, Stream } from "effect";
|
||||||
|
|
||||||
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
|
|||||||
export type FixtureProviderRuntimeEvent = {
|
export type FixtureProviderRuntimeEvent = {
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
readonly eventId: EventId;
|
readonly eventId: EventId;
|
||||||
readonly provider: ProviderKind;
|
readonly provider: "codex";
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
readonly threadId: string;
|
readonly threadId: string;
|
||||||
readonly turnId?: string | undefined;
|
readonly turnId?: string | undefined;
|
||||||
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
|||||||
|
|
||||||
export interface TestProviderAdapterHarness {
|
export interface TestProviderAdapterHarness {
|
||||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||||
readonly provider: ProviderKind;
|
readonly provider: "codex";
|
||||||
readonly queueTurnResponse: (
|
readonly queueTurnResponse: (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
response: TestTurnResponse,
|
response: TestTurnResponse,
|
||||||
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeTestProviderAdapterHarnessOptions {
|
interface MakeTestProviderAdapterHarnessOptions {
|
||||||
readonly provider?: ProviderKind;
|
readonly provider?: "codex";
|
||||||
}
|
}
|
||||||
|
|
||||||
function nowIso(): string {
|
function nowIso(): string {
|
||||||
@@ -206,7 +205,7 @@ function nowIso(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function sessionNotFound(
|
function sessionNotFound(
|
||||||
provider: ProviderKind,
|
provider: "codex",
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): ProviderAdapterSessionNotFoundError {
|
): ProviderAdapterSessionNotFoundError {
|
||||||
return new ProviderAdapterSessionNotFoundError({
|
return new ProviderAdapterSessionNotFoundError({
|
||||||
@@ -216,7 +215,7 @@ function sessionNotFound(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function missingSessionEffect(
|
function missingSessionEffect(
|
||||||
provider: ProviderKind,
|
provider: "codex",
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): Effect.Effect<never, ProviderAdapterError> {
|
): Effect.Effect<never, ProviderAdapterError> {
|
||||||
return Effect.fail(sessionNotFound(provider, threadId));
|
return Effect.fail(sessionNotFound(provider, threadId));
|
||||||
|
|||||||
@@ -5,13 +5,10 @@ import {
|
|||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
DEFAULT_MODEL_BY_PROVIDER,
|
|
||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderKind,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
ModelSelection,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Option, Schema } from "effect";
|
import { Effect, Option, Schema } from "effect";
|
||||||
@@ -28,7 +25,6 @@ import type {
|
|||||||
CheckpointDiffFinalizedReceipt,
|
CheckpointDiffFinalizedReceipt,
|
||||||
TurnProcessingQuiescedReceipt,
|
TurnProcessingQuiescedReceipt,
|
||||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
|
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
@@ -40,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
|
|||||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||||
const FIXTURE_TURN_ID = "fixture-turn";
|
const FIXTURE_TURN_ID = "fixture-turn";
|
||||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||||
type IntegrationProvider = ProviderKind;
|
type IntegrationProvider = "codex";
|
||||||
|
|
||||||
function nowIso() {
|
function nowIso() {
|
||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
@@ -53,11 +49,13 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
|
|||||||
},
|
},
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
const sleep = (ms: number) => Effect.sleep(ms);
|
||||||
|
|
||||||
function waitForSync<A>(
|
function waitForSync<A>(
|
||||||
read: () => A,
|
read: () => A,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 10_000,
|
timeoutMs = 3000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
@@ -70,7 +68,7 @@ function waitForSync<A>(
|
|||||||
if (Date.now() >= deadline) {
|
if (Date.now() >= deadline) {
|
||||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||||
}
|
}
|
||||||
yield* Effect.sleep(10);
|
yield* sleep(10);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -91,7 +89,7 @@ function withHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider }),
|
makeOrchestrationIntegrationHarness({ provider }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
).pipe(Effect.provide(NodeServices.layer));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function withRealCodexHarness<A, E>(
|
function withRealCodexHarness<A, E>(
|
||||||
@@ -101,14 +99,12 @@ function withRealCodexHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
).pipe(Effect.provide(NodeServices.layer));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const createdAt = nowIso();
|
const createdAt = nowIso();
|
||||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
|
||||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
@@ -116,10 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider,
|
|
||||||
model: defaultModel,
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -129,10 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider,
|
|
||||||
model: defaultModel,
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -146,7 +136,7 @@ const startTurn = (input: {
|
|||||||
readonly commandId: string;
|
readonly commandId: string;
|
||||||
readonly messageId: string;
|
readonly messageId: string;
|
||||||
readonly text: string;
|
readonly text: string;
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly provider?: IntegrationProvider;
|
||||||
}) =>
|
}) =>
|
||||||
input.harness.engine.dispatch({
|
input.harness.engine.dispatch({
|
||||||
type: "thread.turn.start",
|
type: "thread.turn.start",
|
||||||
@@ -158,11 +148,7 @@ const startTurn = (input: {
|
|||||||
text: input.text,
|
text: input.text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
...(input.modelSelection !== undefined
|
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||||
? {
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
@@ -265,10 +251,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -278,10 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
model: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -902,435 +882,3 @@ it.live(
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Claude first turn.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-initial",
|
|
||||||
messageId: "msg-user-claude-initial",
|
|
||||||
text: "Use Claude",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.session?.providerName === "claudeAgent" &&
|
|
||||||
entry.session.status === "ready" &&
|
|
||||||
entry.messages.some(
|
|
||||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Turn before restart.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-recover-1",
|
|
||||||
messageId: "msg-user-claude-recover-1",
|
|
||||||
text: "Before restart",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.adapter.stopAll();
|
|
||||||
yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.listActiveSessionIds(),
|
|
||||||
(sessionIds) => sessionIds.length === 0,
|
|
||||||
"provider stopAll",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Turn after restart.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-recover-2",
|
|
||||||
messageId: "msg-user-claude-recover-2",
|
|
||||||
text: "After restart",
|
|
||||||
});
|
|
||||||
yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getStartCount(),
|
|
||||||
(count) => count === 2,
|
|
||||||
"claude provider recovery start",
|
|
||||||
);
|
|
||||||
|
|
||||||
const recoveredThread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.session?.providerName === "claudeAgent" &&
|
|
||||||
entry.messages.some(
|
|
||||||
(message) => message.role === "user" && message.text === "After restart",
|
|
||||||
) &&
|
|
||||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
);
|
|
||||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
|
||||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "approval.requested",
|
|
||||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
|
||||||
requestKind: "command",
|
|
||||||
detail: "Approve Claude tool call",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-approval",
|
|
||||||
messageId: "msg-user-claude-approval",
|
|
||||||
text: "Need approval",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
|
||||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.threadId, "thread-1");
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.approval.respond",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
|
||||||
decision: "accept",
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForPendingApproval(
|
|
||||||
"req-approval-1",
|
|
||||||
(row) => row.status === "resolved" && row.decision === "accept",
|
|
||||||
);
|
|
||||||
|
|
||||||
const approvalResponses = yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
|
||||||
(responses) => responses.length === 1,
|
|
||||||
"claude provider approval response",
|
|
||||||
);
|
|
||||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Long running output.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-interrupt",
|
|
||||||
messageId: "msg-user-claude-interrupt",
|
|
||||||
text: "Start long turn",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) => entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.threadId, "thread-1");
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.turn.interrupt",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
yield* harness.waitForDomainEvent(
|
|
||||||
(event) => event.type === "thread.turn-interrupt-requested",
|
|
||||||
);
|
|
||||||
|
|
||||||
const interruptCalls = yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
|
|
||||||
(calls) => calls.length === 1,
|
|
||||||
"claude provider interrupt call",
|
|
||||||
);
|
|
||||||
assert.equal(interruptCalls.length, 1);
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "README -> v2\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
mutateWorkspace: ({ cwd }) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-revert-1",
|
|
||||||
messageId: "msg-user-claude-revert-1",
|
|
||||||
text: "First Claude edit",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "README -> v3\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
mutateWorkspace: ({ cwd }) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-revert-2",
|
|
||||||
messageId: "msg-user-claude-revert-2",
|
|
||||||
text: "Second Claude edit",
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-2" &&
|
|
||||||
entry.checkpoints.length === 2 &&
|
|
||||||
entry.session?.providerName === "claudeAgent",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.checkpoint.revert",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnCount: 1,
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const revertedThread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
|
||||||
);
|
|
||||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
|
||||||
assert.equal(
|
|
||||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it, assert } from "@effect/vitest";
|
import { it, assert } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||||
@@ -13,7 +12,6 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../src/provider/Services/ProviderService.ts";
|
} from "../src/provider/Services/ProviderService.ts";
|
||||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||||
@@ -62,7 +60,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
|||||||
const shared = Layer.mergeAll(
|
const shared = Layer.mergeAll(
|
||||||
directoryLayer,
|
directoryLayer,
|
||||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
|
||||||
AnalyticsService.layerTest,
|
AnalyticsService.layerTest,
|
||||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||||
|
|
||||||
|
|||||||
@@ -1,36 +1,34 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.0.15",
|
"version": "0.0.10",
|
||||||
"license": "MIT",
|
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/pingdotgg/t3code",
|
"url": "https://github.com/pingdotgg/t3code",
|
||||||
"directory": "apps/server"
|
"directory": "apps/server"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"t3": "./dist/bin.mjs"
|
"t3": "./dist/index.mjs"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
],
|
],
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun run src/bin.ts",
|
"dev": "bun run src/index.ts",
|
||||||
"build": "node scripts/cli.ts build",
|
"build": "node scripts/cli.ts build",
|
||||||
"start": "node dist/bin.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run"
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
|
||||||
"@effect/platform-bun": "catalog:",
|
|
||||||
"@effect/platform-node": "catalog:",
|
"@effect/platform-node": "catalog:",
|
||||||
"@effect/sql-sqlite-bun": "catalog:",
|
"@effect/sql-sqlite-bun": "catalog:",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
"@pierre/diffs": "^1.1.0-beta.16",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"node-pty": "^1.1.0",
|
"node-pty": "^1.1.0",
|
||||||
"open": "^10.1.0"
|
"open": "^10.1.0",
|
||||||
|
"ws": "^8.18.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@effect/language-service": "catalog:",
|
"@effect/language-service": "catalog:",
|
||||||
@@ -40,11 +38,12 @@
|
|||||||
"@t3tools/web": "workspace:*",
|
"@t3tools/web": "workspace:*",
|
||||||
"@types/bun": "catalog:",
|
"@types/bun": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
|
"@types/ws": "^8.5.13",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:"
|
"vitest": "catalog:"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^22.16 || ^23.11 || >=24.10"
|
"node": "^22.13 || ^23.4 || >=24.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentRelativePath(input: {
|
export function resolveAttachmentRelativePath(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||||
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const attachmentId = "thread-1-attachment";
|
const attachmentId = "thread-1-attachment";
|
||||||
|
const attachmentsDir = path.join(stateDir, "attachments");
|
||||||
|
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
attachmentsDir,
|
stateDir,
|
||||||
attachmentId,
|
attachmentId,
|
||||||
});
|
});
|
||||||
expect(resolved).toBe(pngPath);
|
expect(resolved).toBe(pngPath);
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when no attachment file exists for the id", () => {
|
it("returns null when no attachment file exists for the id", () => {
|
||||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
attachmentsDir,
|
stateDir,
|
||||||
attachmentId: "thread-1-missing",
|
attachmentId: "thread-1-missing",
|
||||||
});
|
});
|
||||||
expect(resolved).toBeNull();
|
expect(resolved).toBeNull();
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPath(input: {
|
export function resolveAttachmentPath(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly attachment: ChatAttachment;
|
readonly attachment: ChatAttachment;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
return resolveAttachmentRelativePath({
|
return resolveAttachmentRelativePath({
|
||||||
attachmentsDir: input.attachmentsDir,
|
stateDir: input.stateDir,
|
||||||
relativePath: attachmentRelativePath(input.attachment),
|
relativePath: attachmentRelativePath(input.attachment),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPathById(input: {
|
export function resolveAttachmentPathById(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly attachmentId: string;
|
readonly attachmentId: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||||
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
|
|||||||
}
|
}
|
||||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||||
const maybePath = resolveAttachmentRelativePath({
|
const maybePath = resolveAttachmentRelativePath({
|
||||||
attachmentsDir: input.attachmentsDir,
|
stateDir: input.stateDir,
|
||||||
relativePath: `${normalizedId}${extension}`,
|
relativePath: `${normalizedId}${extension}`,
|
||||||
});
|
});
|
||||||
if (maybePath && existsSync(maybePath)) {
|
if (maybePath && existsSync(maybePath)) {
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Layer from "effect/Layer";
|
|
||||||
import { Command } from "effect/unstable/cli";
|
|
||||||
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import { cli } from "./cli";
|
|
||||||
import { version } from "../package.json" with { type: "json" };
|
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
|
||||||
|
|
||||||
Command.run(cli, { version }).pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.provide(CliRuntimeLayer),
|
|
||||||
NodeRuntime.runMain,
|
|
||||||
);
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
import * as NFS from "node:fs";
|
|
||||||
import * as path from "node:path";
|
|
||||||
import { execFileSync, spawn } from "node:child_process";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import { FileSystem, Schema } from "effect";
|
|
||||||
import * as Duration from "effect/Duration";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Fiber from "effect/Fiber";
|
|
||||||
import { TestClock } from "effect/testing";
|
|
||||||
import { vi } from "vitest";
|
|
||||||
|
|
||||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
|
||||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
|
||||||
|
|
||||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
|
||||||
|
|
||||||
vi.mock("node:fs", async (importOriginal) => {
|
|
||||||
const actual = await importOriginal<typeof import("node:fs")>();
|
|
||||||
return {
|
|
||||||
...actual,
|
|
||||||
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
|
||||||
const [filePath, flags] = args;
|
|
||||||
if (
|
|
||||||
typeof filePath === "string" &&
|
|
||||||
filePath === openSyncInterceptor.failPath &&
|
|
||||||
flags === "r"
|
|
||||||
) {
|
|
||||||
const error = new Error("no such device or address");
|
|
||||||
Object.assign(error, { code: "ENXIO" });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
|
||||||
it.effect("uses platform-specific fd paths", () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
|
||||||
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
|
||||||
assert.equal(resolveFdPath(3, "win32"), undefined);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
filePath,
|
|
||||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
|
||||||
mode: "desktop",
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const fd = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() => NFS.openSync(filePath, "r")),
|
|
||||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertSome(payload, {
|
|
||||||
mode: "desktop",
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
filePath,
|
|
||||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
|
||||||
mode: "desktop",
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
|
||||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
|
||||||
// Attempting to also close it synchronously in a finalizer races with the
|
|
||||||
// stream's async close and produces an uncaught EBADF.
|
|
||||||
const fd = NFS.openSync(filePath, "r");
|
|
||||||
|
|
||||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
|
||||||
try {
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertSome(payload, {
|
|
||||||
mode: "desktop",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
openSyncInterceptor.failPath = null;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns none when the fd is unavailable", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fd = NFS.openSync("/dev/null", "r");
|
|
||||||
NFS.closeSync(fd);
|
|
||||||
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertNone(payload);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
|
||||||
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
|
||||||
|
|
||||||
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
|
||||||
|
|
||||||
const _writer = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() =>
|
|
||||||
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
|
||||||
stdio: ["ignore", "ignore", "ignore"],
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
(writer) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
writer.kill("SIGKILL");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const fd = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
|
||||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
|
||||||
timeoutMs: 100,
|
|
||||||
}).pipe(Effect.forkScoped);
|
|
||||||
|
|
||||||
yield* Effect.yieldNow;
|
|
||||||
yield* TestClock.adjust(Duration.millis(100));
|
|
||||||
|
|
||||||
const payload = yield* Fiber.join(fiber);
|
|
||||||
assertNone(payload);
|
|
||||||
}).pipe(Effect.provide(TestClock.layer())),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
import * as NFS from "node:fs";
|
|
||||||
import * as Net from "node:net";
|
|
||||||
import * as readline from "node:readline";
|
|
||||||
import type { Readable } from "node:stream";
|
|
||||||
|
|
||||||
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
|
|
||||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
|
||||||
|
|
||||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
|
||||||
schema: Schema.Codec<A, I>,
|
|
||||||
fd: number,
|
|
||||||
options?: {
|
|
||||||
timeoutMs?: number;
|
|
||||||
},
|
|
||||||
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
|
|
||||||
const fdReady = yield* isFdReady(fd);
|
|
||||||
if (!fdReady) return Option.none();
|
|
||||||
|
|
||||||
const stream = yield* makeBootstrapInputStream(fd);
|
|
||||||
|
|
||||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
|
||||||
|
|
||||||
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
|
||||||
const input = readline.createInterface({
|
|
||||||
input: stream,
|
|
||||||
crlfDelay: Infinity,
|
|
||||||
});
|
|
||||||
|
|
||||||
const cleanup = () => {
|
|
||||||
stream.removeListener("error", handleError);
|
|
||||||
input.removeListener("line", handleLine);
|
|
||||||
input.removeListener("close", handleClose);
|
|
||||||
input.close();
|
|
||||||
stream.destroy();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleError = (error: Error) => {
|
|
||||||
if (isUnavailableBootstrapFdError(error)) {
|
|
||||||
resume(Effect.succeedNone);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resume(
|
|
||||||
Effect.fail(
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to read bootstrap envelope.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLine = (line: string) => {
|
|
||||||
const parsed = decodeJsonResult(schema)(line);
|
|
||||||
if (Result.isSuccess(parsed)) {
|
|
||||||
resume(Effect.succeedSome(parsed.success));
|
|
||||||
} else {
|
|
||||||
resume(
|
|
||||||
Effect.fail(
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to decode bootstrap envelope.",
|
|
||||||
cause: parsed.failure,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
resume(Effect.succeedNone);
|
|
||||||
};
|
|
||||||
|
|
||||||
stream.once("error", handleError);
|
|
||||||
input.once("line", handleLine);
|
|
||||||
input.once("close", handleClose);
|
|
||||||
|
|
||||||
return Effect.sync(cleanup);
|
|
||||||
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
|
||||||
});
|
|
||||||
|
|
||||||
const isUnavailableBootstrapFdError = Predicate.compose(
|
|
||||||
Predicate.hasProperty("code"),
|
|
||||||
(_) => _.code === "EBADF" || _.code === "ENOENT",
|
|
||||||
);
|
|
||||||
|
|
||||||
const isFdReady = (fd: number) =>
|
|
||||||
Effect.try({
|
|
||||||
try: () => NFS.fstatSync(fd),
|
|
||||||
catch: (error) =>
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to stat bootstrap fd.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
}).pipe(
|
|
||||||
Effect.as(true),
|
|
||||||
Effect.catchIf(
|
|
||||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
|
||||||
() => Effect.succeed(false),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const makeBootstrapInputStream = (fd: number) =>
|
|
||||||
Effect.try<Readable, BootstrapError>({
|
|
||||||
try: () => {
|
|
||||||
const fdPath = resolveFdPath(fd);
|
|
||||||
if (fdPath === undefined) {
|
|
||||||
return makeDirectBootstrapStream(fd);
|
|
||||||
}
|
|
||||||
|
|
||||||
let streamFd: number | undefined;
|
|
||||||
try {
|
|
||||||
streamFd = NFS.openSync(fdPath, "r");
|
|
||||||
return NFS.createReadStream("", {
|
|
||||||
fd: streamFd,
|
|
||||||
encoding: "utf8",
|
|
||||||
autoClose: true,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (isBootstrapFdPathDuplicationError(error)) {
|
|
||||||
if (streamFd !== undefined) {
|
|
||||||
NFS.closeSync(streamFd);
|
|
||||||
}
|
|
||||||
return makeDirectBootstrapStream(fd);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
catch: (error) =>
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to duplicate bootstrap fd.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
|
||||||
try {
|
|
||||||
return NFS.createReadStream("", {
|
|
||||||
fd,
|
|
||||||
encoding: "utf8",
|
|
||||||
autoClose: true,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
const stream = new Net.Socket({
|
|
||||||
fd,
|
|
||||||
readable: true,
|
|
||||||
writable: false,
|
|
||||||
});
|
|
||||||
stream.setEncoding("utf8");
|
|
||||||
return stream;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
|
||||||
Predicate.hasProperty("code"),
|
|
||||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
|
||||||
);
|
|
||||||
|
|
||||||
export function resolveFdPath(
|
|
||||||
fd: number,
|
|
||||||
platform: NodeJS.Platform = process.platform,
|
|
||||||
): string | undefined {
|
|
||||||
if (platform === "linux") {
|
|
||||||
return `/proc/self/fd/${fd}`;
|
|
||||||
}
|
|
||||||
if (platform === "win32") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return `/dev/fd/${fd}`;
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema } from "effect";
|
||||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
import { GitCommandError } from "../git/Errors.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
|
|||||||
id: input.projectId,
|
id: input.projectId,
|
||||||
title: "Project",
|
title: "Project",
|
||||||
workspaceRoot: input.workspaceRoot,
|
workspaceRoot: input.workspaceRoot,
|
||||||
defaultModelSelection: null,
|
defaultModel: null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
@@ -43,10 +43,7 @@ function makeSnapshot(input: {
|
|||||||
id: input.threadId,
|
id: input.threadId,
|
||||||
projectId: input.projectId,
|
projectId: input.projectId,
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -61,7 +58,6 @@ function makeSnapshot(input: {
|
|||||||
},
|
},
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
archivedAt: null,
|
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
activities: [],
|
activities: [],
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
|||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
const checkpointStore = yield* CheckpointStore;
|
const checkpointStore = yield* CheckpointStore;
|
||||||
|
|
||||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||||
function* (input) {
|
Effect.gen(function* () {
|
||||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||||
|
|
||||||
if (input.fromTurnCount === input.toTurnCount) {
|
if (input.fromTurnCount === input.toTurnCount) {
|
||||||
@@ -149,8 +149,7 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return turnDiff;
|
return turnDiff;
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||||
input: OrchestrationGetFullThreadDiffInput,
|
input: OrchestrationGetFullThreadDiffInput,
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { it } from "@effect/vitest";
|
|
||||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
|
||||||
import { describe, expect } from "vitest";
|
|
||||||
|
|
||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
|
||||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
|
||||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
|
||||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
|
||||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-checkpoint-store-test-",
|
|
||||||
});
|
|
||||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
|
||||||
Layer.provide(ServerConfigLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
);
|
|
||||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
|
||||||
Layer.provide(GitCoreTestLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
);
|
|
||||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
|
||||||
|
|
||||||
function makeTmpDir(
|
|
||||||
prefix = "checkpoint-store-test-",
|
|
||||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeTextFile(
|
|
||||||
filePath: string,
|
|
||||||
contents: string,
|
|
||||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
yield* fileSystem.writeFileString(filePath, contents);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function git(
|
|
||||||
cwd: string,
|
|
||||||
args: ReadonlyArray<string>,
|
|
||||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const gitCore = yield* GitCore;
|
|
||||||
const result = yield* gitCore.execute({
|
|
||||||
operation: "CheckpointStore.test.git",
|
|
||||||
cwd,
|
|
||||||
args,
|
|
||||||
timeoutMs: 10_000,
|
|
||||||
});
|
|
||||||
return result.stdout.trim();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function initRepoWithCommit(
|
|
||||||
cwd: string,
|
|
||||||
): Effect.Effect<
|
|
||||||
void,
|
|
||||||
GitCommandError | PlatformError.PlatformError,
|
|
||||||
GitCore | FileSystem.FileSystem
|
|
||||||
> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const core = yield* GitCore;
|
|
||||||
yield* core.initRepo({ cwd });
|
|
||||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
|
||||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
|
||||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
|
||||||
yield* git(cwd, ["add", "."]);
|
|
||||||
yield* git(cwd, ["commit", "-m", "initial commit"]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildLargeText(lineCount = 20_000): string {
|
|
||||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
|
||||||
.join("\n")
|
|
||||||
.concat("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
|
||||||
describe("diffCheckpoints", () => {
|
|
||||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const tmp = yield* makeTmpDir();
|
|
||||||
yield* initRepoWithCommit(tmp);
|
|
||||||
const checkpointStore = yield* CheckpointStore;
|
|
||||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
|
||||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
|
||||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
|
||||||
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: fromCheckpointRef,
|
|
||||||
});
|
|
||||||
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
const diff = yield* checkpointStore.diffCheckpoints({
|
|
||||||
cwd: tmp,
|
|
||||||
fromCheckpointRef,
|
|
||||||
toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(diff).toContain("diff --git");
|
|
||||||
expect(diff).not.toContain("[truncated]");
|
|
||||||
expect(diff).toContain("+line 19999");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -14,15 +14,16 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||||
|
|
||||||
import { CheckpointInvariantError } from "../Errors.ts";
|
import { CheckpointInvariantError } from "../Errors.ts";
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
import { GitCommandError } from "../../git/Errors.ts";
|
||||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
||||||
|
import { GitService } from "../../git/Services/GitService.ts";
|
||||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||||
import { CheckpointRef } from "@t3tools/contracts";
|
import { CheckpointRef } from "@t3tools/contracts";
|
||||||
|
|
||||||
const makeCheckpointStore = Effect.gen(function* () {
|
const makeCheckpointStore = Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitService;
|
||||||
|
|
||||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||||
git
|
git
|
||||||
@@ -86,140 +87,139 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
Effect.catch(() => Effect.succeed(false)),
|
Effect.catch(() => Effect.succeed(false)),
|
||||||
);
|
);
|
||||||
|
|
||||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||||
"captureCheckpoint",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.captureCheckpoint";
|
||||||
const operation = "CheckpointStore.captureCheckpoint";
|
|
||||||
|
|
||||||
yield* Effect.acquireUseRelease(
|
yield* Effect.acquireUseRelease(
|
||||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||||
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
(tempDir) =>
|
||||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
Effect.gen(function* () {
|
||||||
const commitEnv: NodeJS.ProcessEnv = {
|
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||||
...process.env,
|
const commitEnv: NodeJS.ProcessEnv = {
|
||||||
GIT_INDEX_FILE: tempIndexPath,
|
...process.env,
|
||||||
GIT_AUTHOR_NAME: "T3 Code",
|
GIT_INDEX_FILE: tempIndexPath,
|
||||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
GIT_AUTHOR_NAME: "T3 Code",
|
||||||
GIT_COMMITTER_NAME: "T3 Code",
|
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
GIT_COMMITTER_NAME: "T3 Code",
|
||||||
};
|
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||||
|
};
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
if (headExists) {
|
if (headExists) {
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["read-tree", "HEAD"],
|
args: ["read-tree", "HEAD"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["add", "-A", "--", "."],
|
args: ["add", "-A", "--", "."],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
|
|
||||||
const writeTreeResult = yield* git.execute({
|
const writeTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["write-tree"],
|
args: ["write-tree"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const treeOid = writeTreeResult.stdout.trim();
|
const treeOid = writeTreeResult.stdout.trim();
|
||||||
if (treeOid.length === 0) {
|
if (treeOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git write-tree",
|
command: "git write-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git write-tree returned an empty tree oid.",
|
detail: "git write-tree returned an empty tree oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||||
const commitTreeResult = yield* git.execute({
|
const commitTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["commit-tree", treeOid, "-m", message],
|
args: ["commit-tree", treeOid, "-m", message],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const commitOid = commitTreeResult.stdout.trim();
|
const commitOid = commitTreeResult.stdout.trim();
|
||||||
if (commitOid.length === 0) {
|
if (commitOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git commit-tree",
|
command: "git commit-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git commit-tree returned an empty commit oid.",
|
detail: "git commit-tree returned an empty commit oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", input.checkpointRef, commitOid],
|
args: ["update-ref", input.checkpointRef, commitOid],
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||||
).pipe(
|
).pipe(
|
||||||
Effect.catchTags({
|
Effect.catchTags({
|
||||||
PlatformError: (error) =>
|
PlatformError: (error) =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new CheckpointInvariantError({
|
new CheckpointInvariantError({
|
||||||
operation: "CheckpointStore.captureCheckpoint",
|
operation: "CheckpointStore.captureCheckpoint",
|
||||||
detail: "Failed to capture checkpoint.",
|
detail: "Failed to capture checkpoint.",
|
||||||
cause: error,
|
cause: error,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||||
Effect.map((commit) => commit !== null),
|
Effect.map((commit) => commit !== null),
|
||||||
);
|
);
|
||||||
|
|
||||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||||
"restoreCheckpoint",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.restoreCheckpoint";
|
||||||
const operation = "CheckpointStore.restoreCheckpoint";
|
|
||||||
|
|
||||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||||
|
|
||||||
if (!commitOid && input.fallbackToHead === true) {
|
if (!commitOid && input.fallbackToHead === true) {
|
||||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!commitOid) {
|
if (!commitOid) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
|
||||||
operation,
|
|
||||||
cwd: input.cwd,
|
|
||||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
|
||||||
});
|
|
||||||
yield* git.execute({
|
|
||||||
operation,
|
|
||||||
cwd: input.cwd,
|
|
||||||
args: ["clean", "-fd", "--", "."],
|
|
||||||
});
|
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
|
||||||
if (headExists) {
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["reset", "--quiet", "--", "."],
|
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||||
|
});
|
||||||
|
yield* git.execute({
|
||||||
|
operation,
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["clean", "-fd", "--", "."],
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
});
|
if (headExists) {
|
||||||
|
yield* git.execute({
|
||||||
|
operation,
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["reset", "--quiet", "--", "."],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
return true;
|
||||||
function* (input) {
|
});
|
||||||
|
|
||||||
|
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
const operation = "CheckpointStore.diffCheckpoints";
|
const operation = "CheckpointStore.diffCheckpoints";
|
||||||
|
|
||||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||||
@@ -248,26 +248,24 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return result.stdout;
|
return result.stdout;
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||||
"deleteCheckpointRefs",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.checkpointRefs,
|
input.checkpointRefs,
|
||||||
(checkpointRef) =>
|
(checkpointRef) =>
|
||||||
git.execute({
|
git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", "-d", checkpointRef],
|
args: ["update-ref", "-d", checkpointRef],
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
}),
|
}),
|
||||||
{ discard: true },
|
{ discard: true },
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isGitRepository,
|
isGitRepository,
|
||||||
@@ -279,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
} satisfies CheckpointStoreShape;
|
} satisfies CheckpointStoreShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
||||||
|
Layer.provideMerge(GitServiceLive),
|
||||||
|
);
|
||||||
@@ -1,318 +0,0 @@
|
|||||||
import os from "node:os";
|
|
||||||
|
|
||||||
import { assert, expect, it } from "@effect/vitest";
|
|
||||||
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
|
|
||||||
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { deriveServerPaths } from "./config";
|
|
||||||
import { resolveServerConfig } from "./cli";
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|
||||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
|
||||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
|
||||||
return fd;
|
|
||||||
});
|
|
||||||
|
|
||||||
it.effect("falls back to effect/config values when flags are omitted", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.none(),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
authToken: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_LOG_LEVEL: "Warn",
|
|
||||||
T3CODE_MODE: "desktop",
|
|
||||||
T3CODE_PORT: "4001",
|
|
||||||
T3CODE_HOST: "0.0.0.0",
|
|
||||||
T3CODE_HOME: baseDir,
|
|
||||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
|
||||||
T3CODE_NO_BROWSER: "true",
|
|
||||||
T3CODE_AUTH_TOKEN: "env-token",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "true",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Warn",
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4001,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "0.0.0.0",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:5173"),
|
|
||||||
noBrowser: true,
|
|
||||||
authToken: "env-token",
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses CLI flags when provided", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("web"),
|
|
||||||
port: Option.some(8788),
|
|
||||||
host: Option.some("127.0.0.1"),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
|
||||||
noBrowser: Option.some(true),
|
|
||||||
authToken: Option.some("flag-token"),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.some(true),
|
|
||||||
logWebSocketEvents: Option.some(true),
|
|
||||||
},
|
|
||||||
Option.some("Debug"),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_LOG_LEVEL: "Warn",
|
|
||||||
T3CODE_MODE: "desktop",
|
|
||||||
T3CODE_PORT: "4001",
|
|
||||||
T3CODE_HOST: "0.0.0.0",
|
|
||||||
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
|
|
||||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
|
||||||
T3CODE_NO_BROWSER: "false",
|
|
||||||
T3CODE_AUTH_TOKEN: "ignored-token",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "false",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Debug",
|
|
||||||
mode: "web",
|
|
||||||
port: 8788,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:4173"),
|
|
||||||
noBrowser: true,
|
|
||||||
authToken: "flag-token",
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = "/tmp/t3-bootstrap-home";
|
|
||||||
const fd = yield* openBootstrapFd({
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
t3Home: baseDir,
|
|
||||||
devUrl: "http://127.0.0.1:5173",
|
|
||||||
noBrowser: true,
|
|
||||||
authToken: "bootstrap-token",
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.none(),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
authToken: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Info",
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:5173"),
|
|
||||||
noBrowser: true,
|
|
||||||
authToken: "bootstrap-token",
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("creates derived runtime directories during config resolution", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("desktop"),
|
|
||||||
port: Option.some(4888),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
authToken: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const directory of [
|
|
||||||
resolved.stateDir,
|
|
||||||
resolved.logsDir,
|
|
||||||
resolved.providerLogsDir,
|
|
||||||
resolved.terminalLogsDir,
|
|
||||||
resolved.attachmentsDir,
|
|
||||||
resolved.worktreesDir,
|
|
||||||
path.dirname(resolved.serverLogPath),
|
|
||||||
]) {
|
|
||||||
expect(yield* fs.exists(directory)).toBe(true);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
|
|
||||||
const fd = yield* openBootstrapFd({
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
t3Home: "/tmp/t3-bootstrap-home",
|
|
||||||
devUrl: "http://127.0.0.1:5173",
|
|
||||||
noBrowser: false,
|
|
||||||
authToken: "bootstrap-token",
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
});
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.some(8788),
|
|
||||||
host: Option.some("127.0.0.1"),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
authToken: Option.some("flag-token"),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.some("Debug"),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_MODE: "web",
|
|
||||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
|
||||||
T3CODE_HOME: baseDir,
|
|
||||||
T3CODE_NO_BROWSER: "true",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "true",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Debug",
|
|
||||||
mode: "web",
|
|
||||||
port: 8788,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:4173"),
|
|
||||||
noBrowser: true,
|
|
||||||
authToken: "flag-token",
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Layer from "effect/Layer";
|
|
||||||
import * as CliError from "effect/unstable/cli/CliError";
|
|
||||||
import { Command } from "effect/unstable/cli";
|
|
||||||
|
|
||||||
import { cli } from "./cli.ts";
|
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
|
||||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
|
||||||
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
|
|
||||||
Effect.provide(CliRuntimeLayer),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
|
|
||||||
"--log-level",
|
|
||||||
"Debug",
|
|
||||||
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
|
|
||||||
|
|
||||||
if (!CliError.isCliError(error)) {
|
|
||||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
|
||||||
}
|
|
||||||
if (error._tag !== "InvalidValue") {
|
|
||||||
assert.fail(`Expected InvalidValue, got ${error._tag}`);
|
|
||||||
}
|
|
||||||
assert.equal(error.option, "log-level");
|
|
||||||
assert.equal(error.value, "Debug");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,292 +0,0 @@
|
|||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import { Config, Effect, LogLevel, Option, Schema } from "effect";
|
|
||||||
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
|
||||||
|
|
||||||
import {
|
|
||||||
DEFAULT_PORT,
|
|
||||||
deriveServerPaths,
|
|
||||||
ensureServerDirectories,
|
|
||||||
resolveStaticDir,
|
|
||||||
ServerConfig,
|
|
||||||
RuntimeMode,
|
|
||||||
type ServerConfigShape,
|
|
||||||
} from "./config";
|
|
||||||
import { readBootstrapEnvelope } from "./bootstrap";
|
|
||||||
import { resolveBaseDir } from "./os-jank";
|
|
||||||
import { runServer } from "./server";
|
|
||||||
|
|
||||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
|
||||||
|
|
||||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
|
||||||
mode: Schema.optional(RuntimeMode),
|
|
||||||
port: Schema.optional(PortSchema),
|
|
||||||
host: Schema.optional(Schema.String),
|
|
||||||
t3Home: Schema.optional(Schema.String),
|
|
||||||
devUrl: Schema.optional(Schema.URLFromString),
|
|
||||||
noBrowser: Schema.optional(Schema.Boolean),
|
|
||||||
authToken: Schema.optional(Schema.String),
|
|
||||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
|
||||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
|
||||||
});
|
|
||||||
|
|
||||||
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
|
||||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const portFlag = Flag.integer("port").pipe(
|
|
||||||
Flag.withSchema(PortSchema),
|
|
||||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const hostFlag = Flag.string("host").pipe(
|
|
||||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const baseDirFlag = Flag.string("base-dir").pipe(
|
|
||||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
|
||||||
Flag.withSchema(Schema.URLFromString),
|
|
||||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
|
||||||
Flag.withDescription("Disable automatic browser opening."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
|
||||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
|
||||||
Flag.withAlias("token"),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
|
||||||
Flag.withSchema(Schema.Int),
|
|
||||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
|
||||||
Flag.withDescription(
|
|
||||||
"Create a project for the current working directory on startup when missing.",
|
|
||||||
),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
|
||||||
Flag.withDescription(
|
|
||||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
|
||||||
),
|
|
||||||
Flag.withAlias("log-ws-events"),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
|
|
||||||
const EnvServerConfig = Config.all({
|
|
||||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
|
||||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
|
||||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
|
||||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
|
||||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
|
||||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
interface CliServerFlags {
|
|
||||||
readonly mode: Option.Option<RuntimeMode>;
|
|
||||||
readonly port: Option.Option<number>;
|
|
||||||
readonly host: Option.Option<string>;
|
|
||||||
readonly baseDir: Option.Option<string>;
|
|
||||||
readonly devUrl: Option.Option<URL>;
|
|
||||||
readonly noBrowser: Option.Option<boolean>;
|
|
||||||
readonly authToken: Option.Option<string>;
|
|
||||||
readonly bootstrapFd: Option.Option<number>;
|
|
||||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
|
||||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
|
||||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
|
||||||
|
|
||||||
const resolveOptionPrecedence = <Value>(
|
|
||||||
...values: ReadonlyArray<Option.Option<Value>>
|
|
||||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
|
||||||
|
|
||||||
export const resolveServerConfig = (
|
|
||||||
flags: CliServerFlags,
|
|
||||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { findAvailablePort } = yield* NetService;
|
|
||||||
const env = yield* EnvServerConfig;
|
|
||||||
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
|
|
||||||
const bootstrapEnvelope =
|
|
||||||
bootstrapFd !== undefined
|
|
||||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
|
||||||
: Option.none();
|
|
||||||
|
|
||||||
const mode: RuntimeMode = Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.mode,
|
|
||||||
Option.fromUndefinedOr(env.mode),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
|
|
||||||
),
|
|
||||||
() => "web",
|
|
||||||
);
|
|
||||||
|
|
||||||
const port = yield* Option.match(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.port,
|
|
||||||
Option.fromUndefinedOr(env.port),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
|
|
||||||
),
|
|
||||||
{
|
|
||||||
onSome: (value) => Effect.succeed(value),
|
|
||||||
onNone: () => {
|
|
||||||
if (mode === "desktop") {
|
|
||||||
return Effect.succeed(DEFAULT_PORT);
|
|
||||||
}
|
|
||||||
return findAvailablePort(DEFAULT_PORT);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const devUrl = Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.devUrl,
|
|
||||||
Option.fromUndefinedOr(env.devUrl),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
|
|
||||||
),
|
|
||||||
() => undefined,
|
|
||||||
);
|
|
||||||
const baseDir = yield* resolveBaseDir(
|
|
||||||
Option.getOrUndefined(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.baseDir,
|
|
||||||
Option.fromUndefinedOr(env.t3Home),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
|
||||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
|
||||||
yield* ensureServerDirectories(derivedPaths);
|
|
||||||
const noBrowser = resolveBooleanFlag(
|
|
||||||
flags.noBrowser,
|
|
||||||
Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
Option.fromUndefinedOr(env.noBrowser),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
|
||||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
() => mode === "desktop",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const authToken = Option.getOrUndefined(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.authToken,
|
|
||||||
Option.fromUndefinedOr(env.authToken),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
|
||||||
Option.fromUndefinedOr(bootstrap.authToken),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
|
||||||
flags.autoBootstrapProjectFromCwd,
|
|
||||||
Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
|
||||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
() => mode === "web",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const logWebSocketEvents = resolveBooleanFlag(
|
|
||||||
flags.logWebSocketEvents,
|
|
||||||
Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
|
||||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
() => Boolean(devUrl),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
|
||||||
const host = Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
flags.host,
|
|
||||||
Option.fromUndefinedOr(env.host),
|
|
||||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
|
||||||
),
|
|
||||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
|
||||||
);
|
|
||||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
|
||||||
|
|
||||||
const config: ServerConfigShape = {
|
|
||||||
logLevel,
|
|
||||||
mode,
|
|
||||||
port,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host,
|
|
||||||
staticDir,
|
|
||||||
devUrl,
|
|
||||||
noBrowser,
|
|
||||||
authToken,
|
|
||||||
autoBootstrapProjectFromCwd,
|
|
||||||
logWebSocketEvents,
|
|
||||||
};
|
|
||||||
|
|
||||||
return config;
|
|
||||||
});
|
|
||||||
|
|
||||||
const commandFlags = {
|
|
||||||
mode: modeFlag,
|
|
||||||
port: portFlag,
|
|
||||||
host: hostFlag,
|
|
||||||
baseDir: baseDirFlag,
|
|
||||||
devUrl: devUrlFlag,
|
|
||||||
noBrowser: noBrowserFlag,
|
|
||||||
authToken: authTokenFlag,
|
|
||||||
bootstrapFd: bootstrapFdFlag,
|
|
||||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
|
||||||
logWebSocketEvents: logWebSocketEventsFlag,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const rootCommand = Command.make("t3", commandFlags).pipe(
|
|
||||||
Command.withDescription("Run the T3 Code server."),
|
|
||||||
Command.withHandler((flags) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const logLevel = yield* GlobalFlag.LogLevel;
|
|
||||||
const config = yield* resolveServerConfig(flags, logLevel);
|
|
||||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const cli = rootCommand;
|
|
||||||
@@ -37,7 +37,6 @@ function createSendTurnHarness() {
|
|||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: true,
|
sparkEnabled: true,
|
||||||
},
|
},
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -76,7 +75,6 @@ function createThreadControlHarness() {
|
|||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -119,7 +117,6 @@ function createPendingUserInputHarness() {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
]),
|
]),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -138,43 +135,6 @@ function createPendingUserInputHarness() {
|
|||||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createCollabNotificationHarness() {
|
|
||||||
const manager = new CodexAppServerManager();
|
|
||||||
const context = {
|
|
||||||
session: {
|
|
||||||
provider: "codex",
|
|
||||||
status: "running",
|
|
||||||
threadId: asThreadId("thread_1"),
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
activeTurnId: "turn_parent",
|
|
||||||
resumeCursor: { threadId: "provider_parent" },
|
|
||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
account: {
|
|
||||||
type: "unknown",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: true,
|
|
||||||
},
|
|
||||||
pending: new Map(),
|
|
||||||
pendingApprovals: new Map(),
|
|
||||||
pendingUserInputs: new Map(),
|
|
||||||
collabReceiverTurns: new Map<string, string>(),
|
|
||||||
nextRequestId: 1,
|
|
||||||
stopping: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
const emitEvent = vi
|
|
||||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
const updateSession = vi
|
|
||||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
|
|
||||||
return { manager, context, emitEvent, updateSession };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("classifyCodexStderrLine", () => {
|
describe("classifyCodexStderrLine", () => {
|
||||||
it("ignores empty lines", () => {
|
it("ignores empty lines", () => {
|
||||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||||
@@ -207,42 +167,6 @@ describe("classifyCodexStderrLine", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("process stderr events", () => {
|
|
||||||
it("emits classified stderr lines as notifications", () => {
|
|
||||||
const manager = new CodexAppServerManager();
|
|
||||||
const emitEvent = vi
|
|
||||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
emitNotificationEvent: (
|
|
||||||
context: { session: { threadId: ThreadId } },
|
|
||||||
method: string,
|
|
||||||
message: string,
|
|
||||||
) => void;
|
|
||||||
}
|
|
||||||
).emitNotificationEvent(
|
|
||||||
{
|
|
||||||
session: {
|
|
||||||
threadId: asThreadId("thread-1"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"process/stderr",
|
|
||||||
"fatal: permission denied",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(emitEvent).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "notification",
|
|
||||||
method: "process/stderr",
|
|
||||||
threadId: "thread-1",
|
|
||||||
message: "fatal: permission denied",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("normalizeCodexModelSlug", () => {
|
describe("normalizeCodexModelSlug", () => {
|
||||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||||
@@ -310,7 +234,7 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("disables spark for api key accounts", () => {
|
it("keeps spark enabled for api key accounts", () => {
|
||||||
expect(
|
expect(
|
||||||
readCodexAccountSnapshot({
|
readCodexAccountSnapshot({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
@@ -318,20 +242,7 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
).toEqual({
|
).toEqual({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: false,
|
sparkEnabled: true,
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("disables spark for unknown chatgpt plans", () => {
|
|
||||||
expect(
|
|
||||||
readCodexAccountSnapshot({
|
|
||||||
type: "chatgpt",
|
|
||||||
email: "[email protected]",
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
type: "chatgpt",
|
|
||||||
planType: "unknown",
|
|
||||||
sparkEnabled: false,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -356,16 +267,6 @@ describe("resolveCodexModelForAccount", () => {
|
|||||||
}),
|
}),
|
||||||
).toBe("gpt-5.3-codex-spark");
|
).toBe("gpt-5.3-codex-spark");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back from spark to default for api key auth", () => {
|
|
||||||
expect(
|
|
||||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
|
||||||
type: "apiKey",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: false,
|
|
||||||
}),
|
|
||||||
).toBe("gpt-5.3-codex");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("startSession", () => {
|
describe("startSession", () => {
|
||||||
@@ -401,7 +302,6 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
binaryPath: "codex",
|
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow("cwd missing");
|
).rejects.toThrow("cwd missing");
|
||||||
@@ -450,7 +350,6 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
binaryPath: "codex",
|
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow(
|
).rejects.toThrow(
|
||||||
@@ -822,7 +721,6 @@ describe("respondToUserInput", () => {
|
|||||||
},
|
},
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
type ApprovalRequestContext = {
|
type ApprovalRequestContext = {
|
||||||
session: typeof context.session;
|
session: typeof context.session;
|
||||||
@@ -850,152 +748,6 @@ describe("respondToUserInput", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("collab child conversation routing", () => {
|
|
||||||
it("rewrites child notification turn ids onto the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/agentMessage/delta",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turnId: "turn_child_1",
|
|
||||||
itemId: "msg_child_1",
|
|
||||||
delta: "working",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(emitEvent).toHaveBeenLastCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
method: "item/agentMessage/delta",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "msg_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
emitEvent.mockClear();
|
|
||||||
updateSession.mockClear();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "turn/started",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turn: { id: "turn_child_1" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "turn/completed",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turn: { id: "turn_child_1", status: "completed" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(emitEvent).not.toHaveBeenCalled();
|
|
||||||
expect(updateSession).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rewrites child approval requests onto the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
emitEvent.mockClear();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerRequest(context, {
|
|
||||||
id: 42,
|
|
||||||
method: "item/commandExecution/requestApproval",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turnId: "turn_child_1",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
command: "bun install",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
|
|
||||||
expect.objectContaining({
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(emitEvent).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
method: "item/commandExecution/requestApproval",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||||
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
||||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||||
@@ -1009,8 +761,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
providerOptions: {
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
codex: {
|
||||||
|
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||||
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const firstTurn = await manager.sendTurn({
|
const firstTurn = await manager.sendTurn({
|
||||||
@@ -1040,8 +796,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
resumeCursor: firstSession.resumeCursor,
|
resumeCursor: firstSession.resumeCursor,
|
||||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
providerOptions: {
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
codex: {
|
||||||
|
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||||
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
|
type ProviderSessionStartInput,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
RuntimeMode,
|
RuntimeMode,
|
||||||
ProviderInteractionMode,
|
ProviderInteractionMode,
|
||||||
@@ -26,15 +27,6 @@ import {
|
|||||||
isCodexCliVersionSupported,
|
isCodexCliVersionSupported,
|
||||||
parseCodexCliVersion,
|
parseCodexCliVersion,
|
||||||
} from "./provider/codexCliVersion";
|
} from "./provider/codexCliVersion";
|
||||||
import {
|
|
||||||
readCodexAccountSnapshot,
|
|
||||||
resolveCodexModelForAccount,
|
|
||||||
type CodexAccountSnapshot,
|
|
||||||
} from "./provider/codexAccount";
|
|
||||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
|
||||||
|
|
||||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
|
||||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
|
||||||
|
|
||||||
type PendingRequestKey = string;
|
type PendingRequestKey = string;
|
||||||
|
|
||||||
@@ -78,7 +70,6 @@ interface CodexSessionContext {
|
|||||||
pending: Map<PendingRequestKey, PendingRequest>;
|
pending: Map<PendingRequestKey, PendingRequest>;
|
||||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||||
collabReceiverTurns: Map<string, TurnId>;
|
|
||||||
nextRequestId: number;
|
nextRequestId: number;
|
||||||
stopping: boolean;
|
stopping: boolean;
|
||||||
}
|
}
|
||||||
@@ -105,6 +96,23 @@ interface JsonRpcNotification {
|
|||||||
params?: unknown;
|
params?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CodexPlanType =
|
||||||
|
| "free"
|
||||||
|
| "go"
|
||||||
|
| "plus"
|
||||||
|
| "pro"
|
||||||
|
| "team"
|
||||||
|
| "business"
|
||||||
|
| "enterprise"
|
||||||
|
| "edu"
|
||||||
|
| "unknown";
|
||||||
|
|
||||||
|
interface CodexAccountSnapshot {
|
||||||
|
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||||
|
readonly planType: CodexPlanType | null;
|
||||||
|
readonly sparkEnabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CodexAppServerSendTurnInput {
|
export interface CodexAppServerSendTurnInput {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly input?: string;
|
readonly input?: string;
|
||||||
@@ -122,8 +130,7 @@ export interface CodexAppServerStartSessionInput {
|
|||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
readonly serviceTier?: string;
|
readonly serviceTier?: string;
|
||||||
readonly resumeCursor?: unknown;
|
readonly resumeCursor?: unknown;
|
||||||
readonly binaryPath: string;
|
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
||||||
readonly homePath?: string;
|
|
||||||
readonly runtimeMode: RuntimeMode;
|
readonly runtimeMode: RuntimeMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,6 +161,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
|||||||
"unknown thread",
|
"unknown thread",
|
||||||
"does not exist",
|
"does not exist",
|
||||||
];
|
];
|
||||||
|
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||||
|
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||||
|
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
|
||||||
|
|
||||||
|
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||||
|
if (!value || typeof value !== "object") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asString(value: unknown): string | undefined {
|
||||||
|
return typeof value === "string" ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||||
|
const record = asObject(response);
|
||||||
|
const account = asObject(record?.account) ?? record;
|
||||||
|
const accountType = asString(account?.type);
|
||||||
|
|
||||||
|
if (accountType === "apiKey") {
|
||||||
|
return {
|
||||||
|
type: "apiKey",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (accountType === "chatgpt") {
|
||||||
|
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||||
|
return {
|
||||||
|
type: "chatgpt",
|
||||||
|
planType,
|
||||||
|
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "unknown",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||||
|
|
||||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||||
@@ -306,13 +357,32 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveCodexModelForAccount(
|
||||||
|
model: string | undefined,
|
||||||
|
account: CodexAccountSnapshot,
|
||||||
|
): string | undefined {
|
||||||
|
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CODEX_DEFAULT_MODEL;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||||
* entire process tree instead.
|
* entire process tree instead.
|
||||||
*/
|
*/
|
||||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||||
killCodexChildProcess(child);
|
if (process.platform === "win32" && child.pid !== undefined) {
|
||||||
|
try {
|
||||||
|
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
// fallback to direct kill
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child.kill();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeCodexModelSlug(
|
export function normalizeCodexModelSlug(
|
||||||
@@ -331,6 +401,19 @@ export function normalizeCodexModelSlug(
|
|||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildCodexInitializeParams() {
|
||||||
|
return {
|
||||||
|
clientInfo: {
|
||||||
|
name: "t3code_desktop",
|
||||||
|
title: "T3 Code Desktop",
|
||||||
|
version: "0.1.0",
|
||||||
|
},
|
||||||
|
capabilities: {
|
||||||
|
experimentalApi: true,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
}
|
||||||
|
|
||||||
function buildCodexCollaborationMode(input: {
|
function buildCodexCollaborationMode(input: {
|
||||||
readonly interactionMode?: "default" | "plan";
|
readonly interactionMode?: "default" | "plan";
|
||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
@@ -457,8 +540,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
const codexBinaryPath = input.binaryPath;
|
const codexOptions = readCodexProviderOptions(input);
|
||||||
const codexHomePath = input.homePath;
|
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||||
|
const codexHomePath = codexOptions.homePath;
|
||||||
this.assertSupportedCodexCliVersion({
|
this.assertSupportedCodexCliVersion({
|
||||||
binaryPath: codexBinaryPath,
|
binaryPath: codexBinaryPath,
|
||||||
cwd: resolvedCwd,
|
cwd: resolvedCwd,
|
||||||
@@ -487,7 +571,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
pending: new Map(),
|
pending: new Map(),
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
nextRequestId: 1,
|
nextRequestId: 1,
|
||||||
stopping: false,
|
stopping: false,
|
||||||
};
|
};
|
||||||
@@ -649,7 +732,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
const context = this.requireSession(input.threadId);
|
const context = this.requireSession(input.threadId);
|
||||||
context.collabReceiverTurns.clear();
|
|
||||||
|
|
||||||
const turnInput: Array<
|
const turnInput: Array<
|
||||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||||
@@ -962,7 +1044,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1039,16 +1121,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
context: CodexSessionContext,
|
context: CodexSessionContext,
|
||||||
notification: JsonRpcNotification,
|
notification: JsonRpcNotification,
|
||||||
): void {
|
): void {
|
||||||
const rawRoute = this.readRouteFields(notification.params);
|
const route = this.readRouteFields(notification.params);
|
||||||
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
|
|
||||||
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
|
|
||||||
const isChildConversation = childParentTurnId !== undefined;
|
|
||||||
if (
|
|
||||||
isChildConversation &&
|
|
||||||
this.shouldSuppressChildConversationNotification(notification.method)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const textDelta =
|
const textDelta =
|
||||||
notification.method === "item/agentMessage/delta"
|
notification.method === "item/agentMessage/delta"
|
||||||
? this.readString(notification.params, "delta")
|
? this.readString(notification.params, "delta")
|
||||||
@@ -1061,10 +1134,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: notification.method,
|
method: notification.method,
|
||||||
...((childParentTurnId ?? rawRoute.turnId)
|
turnId: route.turnId,
|
||||||
? { turnId: childParentTurnId ?? rawRoute.turnId }
|
itemId: route.itemId,
|
||||||
: {}),
|
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
|
||||||
textDelta,
|
textDelta,
|
||||||
payload: notification.params,
|
payload: notification.params,
|
||||||
});
|
});
|
||||||
@@ -1080,9 +1151,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/started") {
|
if (notification.method === "turn/started") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "running",
|
status: "running",
|
||||||
@@ -1092,10 +1160,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/completed") {
|
if (notification.method === "turn/completed") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
context.collabReceiverTurns.clear();
|
|
||||||
const turn = this.readObject(notification.params, "turn");
|
const turn = this.readObject(notification.params, "turn");
|
||||||
const status = this.readString(turn, "status");
|
const status = this.readString(turn, "status");
|
||||||
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
||||||
@@ -1108,9 +1172,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "error") {
|
if (notification.method === "error") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
||||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||||
|
|
||||||
@@ -1122,9 +1183,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||||
const rawRoute = this.readRouteFields(request.params);
|
const route = this.readRouteFields(request.params);
|
||||||
const childParentTurnId = this.readChildParentTurnId(context, request.params);
|
|
||||||
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
|
||||||
const requestKind = this.requestKindForMethod(request.method);
|
const requestKind = this.requestKindForMethod(request.method);
|
||||||
let requestId: ApprovalRequestId | undefined;
|
let requestId: ApprovalRequestId | undefined;
|
||||||
if (requestKind) {
|
if (requestKind) {
|
||||||
@@ -1140,8 +1199,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
: "item/fileChange/requestApproval",
|
: "item/fileChange/requestApproval",
|
||||||
requestKind,
|
requestKind,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||||
};
|
};
|
||||||
context.pendingApprovals.set(requestId, pendingRequest);
|
context.pendingApprovals.set(requestId, pendingRequest);
|
||||||
}
|
}
|
||||||
@@ -1152,8 +1211,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
requestId,
|
requestId,
|
||||||
jsonRpcId: request.id,
|
jsonRpcId: request.id,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1164,8 +1223,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: request.method,
|
method: request.method,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
turnId: route.turnId,
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
itemId: route.itemId,
|
||||||
requestId,
|
requestId,
|
||||||
requestKind,
|
requestKind,
|
||||||
payload: request.params,
|
payload: request.params,
|
||||||
@@ -1270,22 +1329,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitNotificationEvent(
|
|
||||||
context: CodexSessionContext,
|
|
||||||
method: string,
|
|
||||||
message: string,
|
|
||||||
): void {
|
|
||||||
this.emitEvent({
|
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
|
||||||
kind: "notification",
|
|
||||||
provider: "codex",
|
|
||||||
threadId: context.session.threadId,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
method,
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private emitEvent(event: ProviderEvent): void {
|
private emitEvent(event: ProviderEvent): void {
|
||||||
this.emit("event", event);
|
this.emit("event", event);
|
||||||
}
|
}
|
||||||
@@ -1408,64 +1451,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
return route;
|
return route;
|
||||||
}
|
}
|
||||||
|
|
||||||
private readProviderConversationId(params: unknown): string | undefined {
|
|
||||||
return (
|
|
||||||
this.readString(params, "threadId") ??
|
|
||||||
this.readString(this.readObject(params, "thread"), "id") ??
|
|
||||||
this.readString(params, "conversationId")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
|
|
||||||
const providerConversationId = this.readProviderConversationId(params);
|
|
||||||
if (!providerConversationId) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return context.collabReceiverTurns.get(providerConversationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private rememberCollabReceiverTurns(
|
|
||||||
context: CodexSessionContext,
|
|
||||||
params: unknown,
|
|
||||||
parentTurnId: TurnId | undefined,
|
|
||||||
): void {
|
|
||||||
if (!parentTurnId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const payload = this.readObject(params);
|
|
||||||
const item = this.readObject(payload, "item") ?? payload;
|
|
||||||
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
|
|
||||||
if (itemType !== "collabAgentToolCall") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const receiverThreadIds =
|
|
||||||
this.readArray(item, "receiverThreadIds")
|
|
||||||
?.map((value) => (typeof value === "string" ? value : null))
|
|
||||||
.filter((value): value is string => value !== null) ?? [];
|
|
||||||
for (const receiverThreadId of receiverThreadIds) {
|
|
||||||
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private shouldSuppressChildConversationNotification(method: string): boolean {
|
|
||||||
return (
|
|
||||||
method === "thread/started" ||
|
|
||||||
method === "thread/status/changed" ||
|
|
||||||
method === "thread/archived" ||
|
|
||||||
method === "thread/unarchived" ||
|
|
||||||
method === "thread/closed" ||
|
|
||||||
method === "thread/compacted" ||
|
|
||||||
method === "thread/name/updated" ||
|
|
||||||
method === "thread/tokenUsage/updated" ||
|
|
||||||
method === "turn/started" ||
|
|
||||||
method === "turn/completed" ||
|
|
||||||
method === "turn/aborted" ||
|
|
||||||
method === "turn/plan/updated" ||
|
|
||||||
method === "item/plan/delta"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
||||||
const target =
|
const target =
|
||||||
key === undefined
|
key === undefined
|
||||||
@@ -1522,6 +1507,20 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
|
|||||||
return brandIfNonEmpty(value, (normalized) => normalized);
|
return brandIfNonEmpty(value, (normalized) => normalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||||
|
readonly binaryPath?: string;
|
||||||
|
readonly homePath?: string;
|
||||||
|
} {
|
||||||
|
const options = input.providerOptions?.codex;
|
||||||
|
if (!options) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
|
||||||
|
...(options.homePath ? { homePath: options.homePath } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function assertSupportedCodexCliVersion(input: {
|
function assertSupportedCodexCliVersion(input: {
|
||||||
readonly binaryPath: string;
|
readonly binaryPath: string;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
@@ -1575,11 +1574,7 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
|||||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readResumeThreadId(input: {
|
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
||||||
readonly resumeCursor?: unknown;
|
|
||||||
readonly threadId?: ThreadId;
|
|
||||||
readonly runtimeMode?: RuntimeMode;
|
|
||||||
}): string | undefined {
|
|
||||||
return readResumeCursorThreadId(input.resumeCursor);
|
return readResumeCursorThreadId(input.resumeCursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+13
-86
@@ -6,130 +6,57 @@
|
|||||||
*
|
*
|
||||||
* @module ServerConfig
|
* @module ServerConfig
|
||||||
*/
|
*/
|
||||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||||
|
|
||||||
export const DEFAULT_PORT = 3773;
|
export const DEFAULT_PORT = 3773;
|
||||||
|
|
||||||
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
export type RuntimeMode = "web" | "desktop";
|
||||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ServerDerivedPaths - Derived paths from the base directory.
|
|
||||||
*/
|
|
||||||
export interface ServerDerivedPaths {
|
|
||||||
readonly stateDir: string;
|
|
||||||
readonly dbPath: string;
|
|
||||||
readonly keybindingsConfigPath: string;
|
|
||||||
readonly settingsPath: string;
|
|
||||||
readonly worktreesDir: string;
|
|
||||||
readonly attachmentsDir: string;
|
|
||||||
readonly logsDir: string;
|
|
||||||
readonly serverLogPath: string;
|
|
||||||
readonly providerLogsDir: string;
|
|
||||||
readonly providerEventLogPath: string;
|
|
||||||
readonly terminalLogsDir: string;
|
|
||||||
readonly anonymousIdPath: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||||
*/
|
*/
|
||||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
export interface ServerConfigShape {
|
||||||
readonly logLevel: LogLevel.LogLevel;
|
|
||||||
readonly mode: RuntimeMode;
|
readonly mode: RuntimeMode;
|
||||||
readonly port: number;
|
readonly port: number;
|
||||||
readonly host: string | undefined;
|
readonly host: string | undefined;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
readonly baseDir: string;
|
readonly keybindingsConfigPath: string;
|
||||||
|
readonly stateDir: string;
|
||||||
readonly staticDir: string | undefined;
|
readonly staticDir: string | undefined;
|
||||||
readonly devUrl: URL | undefined;
|
readonly devUrl: URL | undefined;
|
||||||
readonly noBrowser: boolean;
|
readonly noBrowser: boolean;
|
||||||
readonly authToken: string | undefined;
|
readonly authToken: string | undefined;
|
||||||
|
readonly allowedHosts: readonly string[];
|
||||||
readonly autoBootstrapProjectFromCwd: boolean;
|
readonly autoBootstrapProjectFromCwd: boolean;
|
||||||
readonly logWebSocketEvents: boolean;
|
readonly logWebSocketEvents: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const deriveServerPaths = Effect.fn(function* (
|
|
||||||
baseDir: ServerConfigShape["baseDir"],
|
|
||||||
devUrl: ServerConfigShape["devUrl"],
|
|
||||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
|
|
||||||
const dbPath = join(stateDir, "state.sqlite");
|
|
||||||
const attachmentsDir = join(stateDir, "attachments");
|
|
||||||
const logsDir = join(stateDir, "logs");
|
|
||||||
const providerLogsDir = join(logsDir, "provider");
|
|
||||||
return {
|
|
||||||
stateDir,
|
|
||||||
dbPath,
|
|
||||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
|
||||||
settingsPath: join(stateDir, "settings.json"),
|
|
||||||
worktreesDir: join(baseDir, "worktrees"),
|
|
||||||
attachmentsDir,
|
|
||||||
logsDir,
|
|
||||||
serverLogPath: join(logsDir, "server.log"),
|
|
||||||
providerLogsDir,
|
|
||||||
providerEventLogPath: join(providerLogsDir, "events.log"),
|
|
||||||
terminalLogsDir: join(logsDir, "terminals"),
|
|
||||||
anonymousIdPath: join(stateDir, "anonymous-id"),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
|
|
||||||
yield* Effect.all(
|
|
||||||
[
|
|
||||||
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfig - Service tag for server runtime configuration.
|
* ServerConfig - Service tag for server runtime configuration.
|
||||||
*/
|
*/
|
||||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||||
"t3/config/ServerConfig",
|
"t3/config/ServerConfig",
|
||||||
) {
|
) {
|
||||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||||
Layer.effect(
|
Layer.effect(
|
||||||
ServerConfig,
|
ServerConfig,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const devUrl = undefined;
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const baseDir =
|
|
||||||
typeof baseDirOrPrefix === "string"
|
|
||||||
? baseDirOrPrefix
|
|
||||||
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
|
||||||
yield* ensureServerDirectories(derivedPaths);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
logLevel: "Error",
|
|
||||||
cwd,
|
cwd,
|
||||||
baseDir,
|
stateDir: statedir,
|
||||||
...derivedPaths,
|
|
||||||
mode: "web",
|
mode: "web",
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
port: 0,
|
port: 0,
|
||||||
host: undefined,
|
host: undefined,
|
||||||
authToken: undefined,
|
authToken: undefined,
|
||||||
|
allowedHosts: [],
|
||||||
|
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl,
|
devUrl: undefined,
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
} satisfies ServerConfigShape;
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { Schema } from "effect";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitCommandError - Git command execution failed.
|
||||||
|
*/
|
||||||
|
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
command: Schema.String,
|
||||||
|
cwd: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHubCliError - GitHub CLI execution or authentication failed.
|
||||||
|
*/
|
||||||
|
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TextGenerationError - Commit or PR text generation failed.
|
||||||
|
*/
|
||||||
|
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
||||||
|
"TextGenerationError",
|
||||||
|
{
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Text generation failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitManagerError - Stacked Git workflow orchestration failed.
|
||||||
|
*/
|
||||||
|
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Git manager failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
||||||
|
*/
|
||||||
|
export type GitManagerServiceError =
|
||||||
|
| GitManagerError
|
||||||
|
| GitCommandError
|
||||||
|
| GitHubCliError
|
||||||
|
| TextGenerationError;
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { it } from "@effect/vitest";
|
|
||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
||||||
import { expect } from "vitest";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
|
||||||
import { sanitizeThreadTitle } from "../Utils.ts";
|
|
||||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
|
||||||
Layer.provideMerge(
|
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3code-claude-text-generation-test-",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
function makeFakeClaudeBinary(dir: string) {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const binDir = path.join(dir, "bin");
|
|
||||||
const claudePath = path.join(binDir, "claude");
|
|
||||||
yield* fs.makeDirectory(binDir, { recursive: true });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
claudePath,
|
|
||||||
[
|
|
||||||
"#!/bin/sh",
|
|
||||||
'args="$*"',
|
|
||||||
'stdin_content="$(cat)"',
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
|
|
||||||
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
|
|
||||||
' printf "%s\\n" "args missing expected content" >&2',
|
|
||||||
" exit 2",
|
|
||||||
" }",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
|
|
||||||
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
|
|
||||||
' printf "%s\\n" "args contained forbidden content" >&2',
|
|
||||||
" exit 3",
|
|
||||||
" fi",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
|
|
||||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
|
|
||||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
|
||||||
" exit 4",
|
|
||||||
" }",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
|
|
||||||
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
|
|
||||||
"fi",
|
|
||||||
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
|
|
||||||
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
yield* fs.chmod(claudePath, 0o755);
|
|
||||||
return binDir;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function withFakeClaudeEnv<A, E, R>(
|
|
||||||
input: {
|
|
||||||
output: string;
|
|
||||||
exitCode?: number;
|
|
||||||
stderr?: string;
|
|
||||||
argsMustContain?: string;
|
|
||||||
argsMustNotContain?: string;
|
|
||||||
stdinMustContain?: string;
|
|
||||||
},
|
|
||||||
effect: Effect.Effect<A, E, R>,
|
|
||||||
) {
|
|
||||||
return Effect.acquireUseRelease(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
|
|
||||||
const binDir = yield* makeFakeClaudeBinary(tempDir);
|
|
||||||
const previousPath = process.env.PATH;
|
|
||||||
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
|
|
||||||
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
|
|
||||||
yield* Effect.sync(() => {
|
|
||||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
|
||||||
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
|
|
||||||
|
|
||||||
if (input.exitCode !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stderr !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.argsMustContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.argsMustNotContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stdinMustContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
previousPath,
|
|
||||||
previousOutput,
|
|
||||||
previousExitCode,
|
|
||||||
previousStderr,
|
|
||||||
previousArgsMustContain,
|
|
||||||
previousArgsMustNotContain,
|
|
||||||
previousStdinMustContain,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
() => effect,
|
|
||||||
(previous) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
process.env.PATH = previous.previousPath;
|
|
||||||
|
|
||||||
if (previous.previousOutput === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousExitCode === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStderr === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousArgsMustContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousArgsMustNotContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStdinMustContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
|
||||||
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
|
|
||||||
argsMustNotContain: "--effort",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/claude-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-haiku-4-5",
|
|
||||||
options: {
|
|
||||||
thinking: false,
|
|
||||||
effort: "high",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("forwards Claude fast mode and supported effort", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title: "Improve orchestration flow",
|
|
||||||
body: "Body",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
argsMustContain: '--effort max --settings {"fastMode":true}',
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generatePrContent({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/claude-effect",
|
|
||||||
commitSummary: "Improve orchestration",
|
|
||||||
diffSummary: "1 file changed",
|
|
||||||
diffPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("generates thread titles through the Claude provider", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title:
|
|
||||||
' "Reconnect failures after restart because the session state does not recover" ',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
stdinMustContain: "You write concise thread titles for coding conversations.",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Please investigate reconnect failures after restarting the session.",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe(
|
|
||||||
sanitizeThreadTitle(
|
|
||||||
'"Reconnect failures after restart because the session state does not recover"',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title: ' """ """ ',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("New thread");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
/**
|
|
||||||
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
|
|
||||||
*
|
|
||||||
* Implements the same TextGenerationShape contract as CodexTextGeneration but
|
|
||||||
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
|
|
||||||
* instead of the `codex exec` CLI.
|
|
||||||
*
|
|
||||||
* @module ClaudeTextGeneration
|
|
||||||
*/
|
|
||||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
|
||||||
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 { TextGenerationError } from "@t3tools/contracts";
|
|
||||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
|
||||||
import {
|
|
||||||
buildBranchNamePrompt,
|
|
||||||
buildCommitMessagePrompt,
|
|
||||||
buildPrContentPrompt,
|
|
||||||
buildThreadTitlePrompt,
|
|
||||||
} from "../Prompts.ts";
|
|
||||||
import {
|
|
||||||
normalizeCliError,
|
|
||||||
sanitizeCommitSubject,
|
|
||||||
sanitizePrTitle,
|
|
||||||
sanitizeThreadTitle,
|
|
||||||
toJsonSchemaObject,
|
|
||||||
} from "../Utils.ts";
|
|
||||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
|
||||||
|
|
||||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
|
||||||
* We only care about `structured_output`.
|
|
||||||
*/
|
|
||||||
const ClaudeOutputEnvelope = Schema.Struct({
|
|
||||||
structured_output: Schema.Unknown,
|
|
||||||
});
|
|
||||||
|
|
||||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
||||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
|
||||||
operation: string,
|
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
|
||||||
stream.pipe(
|
|
||||||
Stream.decodeText(),
|
|
||||||
Stream.runFold(
|
|
||||||
() => "",
|
|
||||||
(acc, chunk) => acc + chunk,
|
|
||||||
),
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
|
||||||
* schema-validated result.
|
|
||||||
*/
|
|
||||||
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson,
|
|
||||||
modelSelection,
|
|
||||||
}: {
|
|
||||||
operation:
|
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
cwd: string;
|
|
||||||
prompt: string;
|
|
||||||
outputSchemaJson: S;
|
|
||||||
modelSelection: ClaudeModelSelection;
|
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
|
||||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
|
||||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
|
||||||
getClaudeModelCapabilities(modelSelection.model),
|
|
||||||
modelSelection.options,
|
|
||||||
);
|
|
||||||
const settings = {
|
|
||||||
...(typeof normalizedOptions?.thinking === "boolean"
|
|
||||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
|
||||||
: {}),
|
|
||||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const claudeSettings = yield* Effect.map(
|
|
||||||
serverSettingsService.getSettings,
|
|
||||||
(settings) => settings.providers.claudeAgent,
|
|
||||||
).pipe(Effect.catch(() => Effect.undefined));
|
|
||||||
|
|
||||||
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
|
||||||
const command = ChildProcess.make(
|
|
||||||
claudeSettings?.binaryPath || "claude",
|
|
||||||
[
|
|
||||||
"-p",
|
|
||||||
"--output-format",
|
|
||||||
"json",
|
|
||||||
"--json-schema",
|
|
||||||
jsonSchemaStr,
|
|
||||||
"--model",
|
|
||||||
resolveApiModelId(modelSelection),
|
|
||||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
|
||||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
|
||||||
"--dangerously-skip-permissions",
|
|
||||||
],
|
|
||||||
{
|
|
||||||
cwd,
|
|
||||||
shell: process.platform === "win32",
|
|
||||||
stdin: {
|
|
||||||
stream: Stream.encodeText(Stream.make(prompt)),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const child = yield* commandSpawner
|
|
||||||
.spawn(command)
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
|
||||||
[
|
|
||||||
readStreamAsString(operation, child.stdout),
|
|
||||||
readStreamAsString(operation, child.stderr),
|
|
||||||
child.exitCode.pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
|
||||||
const stderrDetail = stderr.trim();
|
|
||||||
const stdoutDetail = stdout.trim();
|
|
||||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail:
|
|
||||||
detail.length > 0
|
|
||||||
? `Claude CLI command failed: ${detail}`
|
|
||||||
: `Claude CLI command failed with code ${exitCode}.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return stdout;
|
|
||||||
});
|
|
||||||
|
|
||||||
const rawStdout = yield* runClaudeCommand().pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
|
||||||
Effect.flatMap(
|
|
||||||
Option.match({
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
|
||||||
),
|
|
||||||
onSome: (value) => Effect.succeed(value),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
|
||||||
rawStdout,
|
|
||||||
).pipe(
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Claude CLI returned unexpected output format.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Claude returned invalid structured output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// TextGenerationShape methods
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateCommitMessage",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
|
||||||
branch: input.branch,
|
|
||||||
stagedSummary: input.stagedSummary,
|
|
||||||
stagedPatch: input.stagedPatch,
|
|
||||||
includeBranch: input.includeBranch === true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
subject: sanitizeCommitSubject(generated.subject),
|
|
||||||
body: generated.body.trim(),
|
|
||||||
...("branch" in generated && typeof generated.branch === "string"
|
|
||||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generatePrContent",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
|
||||||
baseBranch: input.baseBranch,
|
|
||||||
headBranch: input.headBranch,
|
|
||||||
commitSummary: input.commitSummary,
|
|
||||||
diffSummary: input.diffSummary,
|
|
||||||
diffPatch: input.diffPatch,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizePrTitle(generated.title),
|
|
||||||
body: generated.body.trim(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateBranchName",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateBranchName",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateBranchName",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
branch: sanitizeBranchFragment(generated.branch),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateThreadTitle",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizeThreadTitle(generated.title),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
generateCommitMessage,
|
|
||||||
generatePrContent,
|
|
||||||
generateBranchName,
|
|
||||||
generateThreadTitle,
|
|
||||||
} satisfies TextGenerationShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
|
||||||
@@ -1,43 +1,20 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it } from "@effect/vitest";
|
import { it } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||||
provider: "codex" as const,
|
CodexTextGenerationLive.pipe(
|
||||||
model: "gpt-5.4-mini",
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
};
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
function makeFakeCodexBinary(dir: string) {
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
|
||||||
Layer.provideMerge(
|
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3code-codex-text-generation-test-",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
function makeFakeCodexBinary(
|
|
||||||
dir: string,
|
|
||||||
input: {
|
|
||||||
output: string;
|
|
||||||
exitCode?: number;
|
|
||||||
stderr?: string;
|
|
||||||
requireImage?: boolean;
|
|
||||||
requireFastServiceTier?: boolean;
|
|
||||||
requireReasoningEffort?: string;
|
|
||||||
forbidReasoningEffort?: boolean;
|
|
||||||
stdinMustContain?: string;
|
|
||||||
stdinMustNotContain?: string;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
@@ -50,102 +27,49 @@ function makeFakeCodexBinary(
|
|||||||
[
|
[
|
||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
'output_path=""',
|
'output_path=""',
|
||||||
'seen_image="0"',
|
|
||||||
'seen_fast_service_tier="0"',
|
|
||||||
'seen_reasoning_effort=""',
|
|
||||||
"while [ $# -gt 0 ]; do",
|
"while [ $# -gt 0 ]; do",
|
||||||
' if [ "$1" = "--image" ]; then',
|
' if [ "$1" = "--image" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' if [ -n "$1" ]; then',
|
' if [ -n "$1" ]; then',
|
||||||
' seen_image="1"',
|
' seen_image="1"',
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
|
||||||
" continue",
|
|
||||||
" fi",
|
|
||||||
' if [ "$1" = "--config" ]; then',
|
|
||||||
" shift",
|
|
||||||
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
|
||||||
' seen_fast_service_tier="1"',
|
|
||||||
" fi",
|
|
||||||
' case "$1" in',
|
|
||||||
" model_reasoning_effort=*)",
|
|
||||||
' seen_reasoning_effort="$1"',
|
|
||||||
" ;;",
|
|
||||||
" esac",
|
|
||||||
" shift",
|
|
||||||
" continue",
|
" continue",
|
||||||
" fi",
|
" fi",
|
||||||
' if [ "$1" = "--output-last-message" ]; then',
|
' if [ "$1" = "--output-last-message" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' output_path="$1"',
|
' output_path="$1"',
|
||||||
" shift",
|
|
||||||
" continue",
|
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
" shift",
|
||||||
"done",
|
"done",
|
||||||
'stdin_content="$(cat)"',
|
'stdin_content="$(cat)"',
|
||||||
...(input.requireImage
|
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||||
? [
|
' printf "%s\\n" "missing --image input" >&2',
|
||||||
'if [ "$seen_image" != "1" ]; then',
|
" exit 2",
|
||||||
' printf "%s\\n" "missing --image input" >&2',
|
|
||||||
` exit 2`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.requireFastServiceTier
|
|
||||||
? [
|
|
||||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
|
||||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
|
||||||
` exit 5`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.requireReasoningEffort !== undefined
|
|
||||||
? [
|
|
||||||
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
|
|
||||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
|
||||||
` exit 6`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.forbidReasoningEffort
|
|
||||||
? [
|
|
||||||
'if [ -n "$seen_reasoning_effort" ]; then',
|
|
||||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
|
||||||
` exit 7`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stdinMustContain !== undefined
|
|
||||||
? [
|
|
||||||
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
|
|
||||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
|
||||||
` exit 3`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stdinMustNotContain !== undefined
|
|
||||||
? [
|
|
||||||
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
|
|
||||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
|
||||||
` exit 4`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stderr !== undefined
|
|
||||||
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
|
|
||||||
: []),
|
|
||||||
'if [ -n "$output_path" ]; then',
|
|
||||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
|
||||||
input.output,
|
|
||||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
|
||||||
"fi",
|
"fi",
|
||||||
`exit ${input.exitCode ?? 0}`,
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
" exit 3",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||||
|
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||||
|
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||||
|
" exit 4",
|
||||||
|
" fi",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||||
|
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$output_path" ]; then',
|
||||||
|
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
||||||
|
"fi",
|
||||||
|
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||||
"",
|
"",
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
);
|
);
|
||||||
yield* fs.chmod(codexPath, 0o755);
|
yield* fs.chmod(codexPath, 0o755);
|
||||||
return codexPath;
|
return binDir;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,9 +79,6 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
exitCode?: number;
|
exitCode?: number;
|
||||||
stderr?: string;
|
stderr?: string;
|
||||||
requireImage?: boolean;
|
requireImage?: boolean;
|
||||||
requireFastServiceTier?: boolean;
|
|
||||||
requireReasoningEffort?: string;
|
|
||||||
forbidReasoningEffort?: boolean;
|
|
||||||
stdinMustContain?: string;
|
stdinMustContain?: string;
|
||||||
stdinMustNotContain?: string;
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
@@ -167,32 +88,106 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||||
const serverSettings = yield* ServerSettingsService;
|
const previousPath = process.env.PATH;
|
||||||
const previousSettings = yield* serverSettings.getSettings;
|
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
yield* serverSettings.updateSettings({
|
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
providers: {
|
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||||
codex: {
|
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
binaryPath: codexPath,
|
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
},
|
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
},
|
|
||||||
|
yield* Effect.sync(() => {
|
||||||
|
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||||
|
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
||||||
|
|
||||||
|
if (input.exitCode !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stderr !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.requireImage) {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustNotContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
|
||||||
|
return {
|
||||||
|
previousPath,
|
||||||
|
previousOutput,
|
||||||
|
previousExitCode,
|
||||||
|
previousStderr,
|
||||||
|
previousRequireImage,
|
||||||
|
previousStdinMustContain,
|
||||||
|
previousStdinMustNotContain,
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
() => effect,
|
() => effect,
|
||||||
({ serverSettings, previousBinaryPath }) =>
|
(previous) =>
|
||||||
serverSettings
|
Effect.sync(() => {
|
||||||
.updateSettings({
|
process.env.PATH = previous.previousPath;
|
||||||
providers: {
|
|
||||||
codex: {
|
if (previous.previousOutput === undefined) {
|
||||||
binaryPath: previousBinaryPath,
|
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
},
|
} else {
|
||||||
},
|
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||||
})
|
}
|
||||||
.pipe(Effect.asVoid),
|
|
||||||
|
if (previous.previousExitCode === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStderr === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousRequireImage === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustNotContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||||
|
}
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
@@ -212,7 +207,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-effect",
|
branch: "feature/codex-effect",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||||
@@ -223,63 +217,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect(
|
|
||||||
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
|
||||||
() =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
}),
|
|
||||||
requireFastServiceTier: true,
|
|
||||||
requireReasoningEffort: "xhigh",
|
|
||||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.4",
|
|
||||||
options: {
|
|
||||||
reasoningEffort: "xhigh",
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("defaults git text generation codex effort to low", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
}),
|
|
||||||
requireReasoningEffort: "low",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -299,7 +236,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
includeBranch: true,
|
includeBranch: true,
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
expect(generated.subject).toBe("Add important change");
|
||||||
@@ -326,7 +262,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
commitSummary: "feat: improve orchestration flow",
|
commitSummary: "feat: improve orchestration flow",
|
||||||
diffSummary: "2 files changed",
|
diffSummary: "2 files changed",
|
||||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
expect(generated.title).toBe("Improve orchestration flow");
|
||||||
@@ -350,7 +285,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Please update session handling.",
|
message: "Please update session handling.",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("feat/session");
|
expect(generated.branch).toBe("feat/session");
|
||||||
@@ -358,70 +292,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("generates thread titles and trims them for sidebar use", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title:
|
|
||||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title: ' """ """ ',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("New thread");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title: ` "' hello world '" `,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("hello world");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -436,7 +306,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix timeout behavior.",
|
message: "Fix timeout behavior.",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/session-timeout");
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
@@ -456,27 +325,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
id: attachmentId,
|
id: attachmentId,
|
||||||
name: "bug.png",
|
name: "bug.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
})
|
||||||
|
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/ui-regression");
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
}),
|
}),
|
||||||
@@ -494,16 +363,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration
|
const generated = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -543,15 +410,13 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const result = yield* textGeneration
|
const result = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -564,12 +429,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
expect(result._tag).toBe("Left");
|
||||||
if (Result.isFailure(result)) {
|
if (result._tag === "Left") {
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.failure.message).toContain("missing --image input");
|
expect(result.left.message).toContain("missing --image input");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -591,14 +461,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix websocket reconnect flake",
|
message: "Fix websocket reconnect flake",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
expect(result._tag).toBe("Left");
|
||||||
if (Result.isFailure(result)) {
|
if (result._tag === "Left") {
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -620,16 +494,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-error",
|
branch: "feature/codex-error",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
if (Result.isFailure(result)) {
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
}),
|
||||||
expect(result.failure.message).toContain(
|
|
||||||
"Codex CLI command failed: codex execution failed",
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,45 +1,105 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { CodexModelSelection } from "@t3tools/contracts";
|
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
type BranchNameGenerationInput,
|
type BranchNameGenerationInput,
|
||||||
type ThreadTitleGenerationResult,
|
type BranchNameGenerationResult,
|
||||||
|
type CommitMessageGenerationResult,
|
||||||
|
type PrContentGenerationResult,
|
||||||
type TextGenerationShape,
|
type TextGenerationShape,
|
||||||
TextGeneration,
|
TextGeneration,
|
||||||
} from "../Services/TextGeneration.ts";
|
} from "../Services/TextGeneration.ts";
|
||||||
import {
|
|
||||||
buildBranchNamePrompt,
|
|
||||||
buildCommitMessagePrompt,
|
|
||||||
buildPrContentPrompt,
|
|
||||||
buildThreadTitlePrompt,
|
|
||||||
} from "../Prompts.ts";
|
|
||||||
import {
|
|
||||||
normalizeCliError,
|
|
||||||
sanitizeCommitSubject,
|
|
||||||
sanitizePrTitle,
|
|
||||||
sanitizeThreadTitle,
|
|
||||||
toJsonSchemaObject,
|
|
||||||
} from "../Utils.ts";
|
|
||||||
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
|
||||||
|
|
||||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
const CODEX_MODEL = "gpt-5.3-codex";
|
||||||
|
const CODEX_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
|
function toCodexOutputJsonSchema(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCodexError(
|
||||||
|
operation: string,
|
||||||
|
error: unknown,
|
||||||
|
fallback: string,
|
||||||
|
): TextGenerationError {
|
||||||
|
if (Schema.is(TextGenerationError)(error)) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
const lower = error.message.toLowerCase();
|
||||||
|
if (
|
||||||
|
error.message.includes("Command not found: codex") ||
|
||||||
|
lower.includes("spawn codex") ||
|
||||||
|
lower.includes("enoent")
|
||||||
|
) {
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex CLI (`codex`) is required but not available on PATH.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: `${fallback}: ${error.message}`,
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: fallback,
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function limitSection(value: string, maxChars: number): string {
|
||||||
|
if (value.length <= maxChars) return value;
|
||||||
|
const truncated = value.slice(0, maxChars);
|
||||||
|
return `${truncated}\n\n[truncated]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeCommitSubject(raw: string): string {
|
||||||
|
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
|
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||||
|
if (withoutTrailingPeriod.length === 0) {
|
||||||
|
return "Update project files";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (withoutTrailingPeriod.length <= 72) {
|
||||||
|
return withoutTrailingPeriod;
|
||||||
|
}
|
||||||
|
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizePrTitle(raw: string): string {
|
||||||
|
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
|
if (singleLine.length > 0) {
|
||||||
|
return singleLine;
|
||||||
|
}
|
||||||
|
return "Update project changes";
|
||||||
|
}
|
||||||
|
|
||||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
const serverConfig = yield* Effect.service(ServerConfig);
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
|
||||||
|
|
||||||
type MaterializedImageAttachments = {
|
type MaterializedImageAttachments = {
|
||||||
readonly imagePaths: ReadonlyArray<string>;
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
@@ -49,367 +109,358 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: string,
|
operation: string,
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
stream: Stream.Stream<Uint8Array, E>,
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
): Effect.Effect<string, TextGenerationError> =>
|
||||||
stream.pipe(
|
Effect.gen(function* () {
|
||||||
Stream.decodeText(),
|
let text = "";
|
||||||
Stream.runFold(
|
yield* Stream.runForEach(stream, (chunk) =>
|
||||||
() => "",
|
Effect.sync(() => {
|
||||||
(acc, chunk) => acc + chunk,
|
text += Buffer.from(chunk).toString("utf8");
|
||||||
),
|
}),
|
||||||
Effect.mapError((cause) =>
|
).pipe(
|
||||||
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
|
Effect.mapError((cause) =>
|
||||||
),
|
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||||
);
|
),
|
||||||
|
);
|
||||||
|
return text;
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||||
|
|
||||||
const writeTempFile = (
|
const writeTempFile = (
|
||||||
operation: string,
|
operation: string,
|
||||||
prefix: string,
|
prefix: string,
|
||||||
content: string,
|
content: string,
|
||||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
): Effect.Effect<string, TextGenerationError> => {
|
||||||
return fileSystem
|
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||||
.makeTempFileScoped({
|
return fileSystem.writeFileString(filePath, content).pipe(
|
||||||
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
|
Effect.mapError(
|
||||||
})
|
(cause) =>
|
||||||
.pipe(
|
new TextGenerationError({
|
||||||
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
|
operation,
|
||||||
Effect.mapError(
|
detail: `Failed to write temp file at ${filePath}.`,
|
||||||
(cause) =>
|
cause,
|
||||||
new TextGenerationError({
|
}),
|
||||||
operation,
|
),
|
||||||
detail: `Failed to write temp file`,
|
Effect.as(filePath),
|
||||||
cause,
|
);
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
const materializeImageAttachments = (
|
||||||
_operation:
|
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle",
|
|
||||||
attachments: BranchNameGenerationInput["attachments"],
|
attachments: BranchNameGenerationInput["attachments"],
|
||||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||||
if (!attachments || attachments.length === 0) {
|
Effect.gen(function* () {
|
||||||
return { imagePaths: [] };
|
if (!attachments || attachments.length === 0) {
|
||||||
}
|
return { imagePaths: [] };
|
||||||
|
|
||||||
const imagePaths: string[] = [];
|
|
||||||
for (const attachment of attachments) {
|
|
||||||
if (attachment.type !== "image") {
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedPath = resolveAttachmentPath({
|
const imagePaths: string[] = [];
|
||||||
attachmentsDir: serverConfig.attachmentsDir,
|
for (const attachment of attachments) {
|
||||||
attachment,
|
if (attachment.type !== "image") {
|
||||||
});
|
continue;
|
||||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
}
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const fileInfo = yield* fileSystem
|
|
||||||
.stat(resolvedPath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
imagePaths.push(resolvedPath);
|
|
||||||
}
|
|
||||||
return { imagePaths };
|
|
||||||
});
|
|
||||||
|
|
||||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
const resolvedPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(resolvedPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
imagePaths.push(resolvedPath);
|
||||||
|
}
|
||||||
|
return { imagePaths };
|
||||||
|
});
|
||||||
|
|
||||||
|
const runCodexJson = <S extends Schema.Top>({
|
||||||
operation,
|
operation,
|
||||||
cwd,
|
cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson,
|
outputSchemaJson,
|
||||||
imagePaths = [],
|
imagePaths = [],
|
||||||
cleanupPaths = [],
|
cleanupPaths = [],
|
||||||
modelSelection,
|
|
||||||
}: {
|
}: {
|
||||||
operation:
|
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: S;
|
outputSchemaJson: S;
|
||||||
imagePaths?: ReadonlyArray<string>;
|
imagePaths?: ReadonlyArray<string>;
|
||||||
cleanupPaths?: ReadonlyArray<string>;
|
cleanupPaths?: ReadonlyArray<string>;
|
||||||
modelSelection: CodexModelSelection;
|
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
Effect.gen(function* () {
|
||||||
const schemaPath = yield* writeTempFile(
|
const schemaPath = yield* writeTempFile(
|
||||||
operation,
|
operation,
|
||||||
"codex-schema",
|
"codex-schema",
|
||||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||||
);
|
|
||||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
|
||||||
|
|
||||||
const codexSettings = yield* Effect.map(
|
|
||||||
serverSettingsService.getSettings,
|
|
||||||
(settings) => settings.providers.codex,
|
|
||||||
).pipe(Effect.catch(() => Effect.undefined));
|
|
||||||
|
|
||||||
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
|
||||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
|
||||||
getCodexModelCapabilities(modelSelection.model),
|
|
||||||
modelSelection.options,
|
|
||||||
);
|
);
|
||||||
const reasoningEffort =
|
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
|
||||||
const command = ChildProcess.make(
|
const runCodexCommand = Effect.gen(function* () {
|
||||||
codexSettings?.binaryPath || "codex",
|
const command = ChildProcess.make(
|
||||||
[
|
"codex",
|
||||||
"exec",
|
[
|
||||||
"--ephemeral",
|
"exec",
|
||||||
"-s",
|
"--ephemeral",
|
||||||
"read-only",
|
"-s",
|
||||||
"--model",
|
"read-only",
|
||||||
modelSelection.model,
|
"--model",
|
||||||
"--config",
|
CODEX_MODEL,
|
||||||
`model_reasoning_effort="${reasoningEffort}"`,
|
"--config",
|
||||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||||
"--output-schema",
|
"--output-schema",
|
||||||
schemaPath,
|
schemaPath,
|
||||||
"--output-last-message",
|
"--output-last-message",
|
||||||
outputPath,
|
outputPath,
|
||||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||||
"-",
|
"-",
|
||||||
],
|
],
|
||||||
|
{
|
||||||
|
cwd,
|
||||||
|
shell: process.platform === "win32",
|
||||||
|
stdin: {
|
||||||
|
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const child = yield* commandSpawner
|
||||||
|
.spawn(command)
|
||||||
|
.pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||||
|
[
|
||||||
|
readStreamAsString(operation, child.stdout),
|
||||||
|
readStreamAsString(operation, child.stderr),
|
||||||
|
child.exitCode.pipe(
|
||||||
|
Effect.map((value) => Number(value)),
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
const stderrDetail = stderr.trim();
|
||||||
|
const stdoutDetail = stdout.trim();
|
||||||
|
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail:
|
||||||
|
detail.length > 0
|
||||||
|
? `Codex CLI command failed: ${detail}`
|
||||||
|
: `Codex CLI command failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const cleanup = Effect.all(
|
||||||
|
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||||
{
|
{
|
||||||
env: {
|
concurrency: "unbounded",
|
||||||
...process.env,
|
|
||||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
|
||||||
},
|
|
||||||
cwd,
|
|
||||||
shell: process.platform === "win32",
|
|
||||||
stdin: {
|
|
||||||
stream: Stream.encodeText(Stream.make(prompt)),
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
);
|
).pipe(Effect.asVoid);
|
||||||
|
|
||||||
const child = yield* commandSpawner
|
return yield* Effect.gen(function* () {
|
||||||
.spawn(command)
|
yield* runCodexCommand.pipe(
|
||||||
.pipe(
|
Effect.scoped,
|
||||||
Effect.mapError((cause) =>
|
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
Effect.flatMap(
|
||||||
|
Option.match({
|
||||||
|
onNone: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||||
|
),
|
||||||
|
onSome: () => Effect.void,
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||||
[
|
Effect.mapError(
|
||||||
readStreamAsString(operation, child.stdout),
|
(cause) =>
|
||||||
readStreamAsString(operation, child.stderr),
|
new TextGenerationError({
|
||||||
child.exitCode.pipe(
|
operation,
|
||||||
Effect.mapError((cause) =>
|
detail: "Failed to read Codex output file.",
|
||||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex returned invalid structured output.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
);
|
||||||
{ concurrency: "unbounded" },
|
}).pipe(Effect.ensuring(cleanup));
|
||||||
);
|
});
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||||
const stderrDetail = stderr.trim();
|
const wantsBranch = input.includeBranch === true;
|
||||||
const stdoutDetail = stdout.trim();
|
|
||||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
const prompt = [
|
||||||
return yield* new TextGenerationError({
|
"You write concise git commit messages.",
|
||||||
operation,
|
wantsBranch
|
||||||
detail:
|
? "Return a JSON object with keys: subject, body, branch."
|
||||||
detail.length > 0
|
: "Return a JSON object with keys: subject, body.",
|
||||||
? `Codex CLI command failed: ${detail}`
|
"Rules:",
|
||||||
: `Codex CLI command failed with code ${exitCode}.`,
|
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||||
|
"- body can be empty string or short bullet points",
|
||||||
|
...(wantsBranch
|
||||||
|
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||||
|
: []),
|
||||||
|
"- capture the primary user-visible or developer-visible change",
|
||||||
|
"",
|
||||||
|
`Branch: ${input.branch ?? "(detached)"}`,
|
||||||
|
"",
|
||||||
|
"Staged files:",
|
||||||
|
limitSection(input.stagedSummary, 6_000),
|
||||||
|
"",
|
||||||
|
"Staged patch:",
|
||||||
|
limitSection(input.stagedPatch, 40_000),
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const outputSchemaJson = wantsBranch
|
||||||
|
? Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
branch: Schema.String,
|
||||||
|
})
|
||||||
|
: Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const cleanup = Effect.all(
|
return runCodexJson({
|
||||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
|
||||||
{
|
|
||||||
concurrency: "unbounded",
|
|
||||||
},
|
|
||||||
).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
return yield* Effect.gen(function* () {
|
|
||||||
yield* runCodexCommand().pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
|
||||||
Effect.flatMap(
|
|
||||||
Option.match({
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
|
||||||
),
|
|
||||||
onSome: () => Effect.void,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Failed to read Codex output file.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned invalid structured output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.ensuring(cleanup));
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
|
||||||
"CodexTextGeneration.generateCommitMessage",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
|
||||||
branch: input.branch,
|
|
||||||
stagedSummary: input.stagedSummary,
|
|
||||||
stagedPatch: input.stagedPatch,
|
|
||||||
includeBranch: input.includeBranch === true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: outputSchema,
|
outputSchemaJson,
|
||||||
modelSelection: input.modelSelection,
|
}).pipe(
|
||||||
});
|
Effect.map(
|
||||||
|
(generated) =>
|
||||||
|
({
|
||||||
|
subject: sanitizeCommitSubject(generated.subject),
|
||||||
|
body: generated.body.trim(),
|
||||||
|
...("branch" in generated && typeof generated.branch === "string"
|
||||||
|
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||||
|
: {}),
|
||||||
|
}) satisfies CommitMessageGenerationResult,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
|
||||||
subject: sanitizeCommitSubject(generated.subject),
|
const prompt = [
|
||||||
body: generated.body.trim(),
|
"You write GitHub pull request content.",
|
||||||
...("branch" in generated && typeof generated.branch === "string"
|
"Return a JSON object with keys: title, body.",
|
||||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
"Rules:",
|
||||||
: {}),
|
"- title should be concise and specific",
|
||||||
};
|
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||||
});
|
"- under Summary, provide short bullet points",
|
||||||
|
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||||
|
"",
|
||||||
|
`Base branch: ${input.baseBranch}`,
|
||||||
|
`Head branch: ${input.headBranch}`,
|
||||||
|
"",
|
||||||
|
"Commits:",
|
||||||
|
limitSection(input.commitSummary, 12_000),
|
||||||
|
"",
|
||||||
|
"Diff stat:",
|
||||||
|
limitSection(input.diffSummary, 12_000),
|
||||||
|
"",
|
||||||
|
"Diff patch:",
|
||||||
|
limitSection(input.diffPatch, 40_000),
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
return runCodexJson({
|
||||||
"CodexTextGeneration.generatePrContent",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
|
||||||
baseBranch: input.baseBranch,
|
|
||||||
headBranch: input.headBranch,
|
|
||||||
commitSummary: input.commitSummary,
|
|
||||||
diffSummary: input.diffSummary,
|
|
||||||
diffPatch: input.diffPatch,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: outputSchema,
|
outputSchemaJson: Schema.Struct({
|
||||||
modelSelection: input.modelSelection,
|
title: Schema.String,
|
||||||
});
|
body: Schema.String,
|
||||||
|
}),
|
||||||
return {
|
}).pipe(
|
||||||
title: sanitizePrTitle(generated.title),
|
Effect.map(
|
||||||
body: generated.body.trim(),
|
(generated) =>
|
||||||
};
|
({
|
||||||
});
|
title: sanitizePrTitle(generated.title),
|
||||||
|
body: generated.body.trim(),
|
||||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
}) satisfies PrContentGenerationResult,
|
||||||
"CodexTextGeneration.generateBranchName",
|
),
|
||||||
)(function* (input) {
|
|
||||||
const { imagePaths } = yield* materializeImageAttachments(
|
|
||||||
"generateBranchName",
|
|
||||||
input.attachments,
|
|
||||||
);
|
);
|
||||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
};
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||||
return yield* new TextGenerationError({
|
return Effect.gen(function* () {
|
||||||
|
const { imagePaths } = yield* materializeImageAttachments(
|
||||||
|
"generateBranchName",
|
||||||
|
input.attachments,
|
||||||
|
);
|
||||||
|
const attachmentLines = (input.attachments ?? []).map(
|
||||||
|
(attachment) =>
|
||||||
|
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const promptSections = [
|
||||||
|
"You generate concise git branch names.",
|
||||||
|
"Return a JSON object with key: branch.",
|
||||||
|
"Rules:",
|
||||||
|
"- Branch should describe the requested work from the user message.",
|
||||||
|
"- Keep it short and specific (2-6 words).",
|
||||||
|
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||||
|
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||||
|
"",
|
||||||
|
"User message:",
|
||||||
|
limitSection(input.message, 8_000),
|
||||||
|
];
|
||||||
|
if (attachmentLines.length > 0) {
|
||||||
|
promptSections.push(
|
||||||
|
"",
|
||||||
|
"Attachment metadata:",
|
||||||
|
limitSection(attachmentLines.join("\n"), 4_000),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const prompt = promptSections.join("\n");
|
||||||
|
|
||||||
|
const generated = yield* runCodexJson({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
detail: "Invalid model selection.",
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: Schema.Struct({
|
||||||
|
branch: Schema.String,
|
||||||
|
}),
|
||||||
|
imagePaths,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
return {
|
||||||
operation: "generateBranchName",
|
branch: sanitizeBranchFragment(generated.branch),
|
||||||
cwd: input.cwd,
|
} satisfies BranchNameGenerationResult;
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
imagePaths,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
});
|
||||||
|
};
|
||||||
return {
|
|
||||||
branch: sanitizeBranchFragment(generated.branch),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
|
||||||
"CodexTextGeneration.generateThreadTitle",
|
|
||||||
)(function* (input) {
|
|
||||||
const { imagePaths } = yield* materializeImageAttachments(
|
|
||||||
"generateThreadTitle",
|
|
||||||
input.attachments,
|
|
||||||
);
|
|
||||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
imagePaths,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizeThreadTitle(generated.title),
|
|
||||||
} satisfies ThreadTitleGenerationResult;
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
generatePrContent,
|
generatePrContent,
|
||||||
generateBranchName,
|
generateBranchName,
|
||||||
generateThreadTitle,
|
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+697
-1269
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@ import { Effect, Layer, Schema } from "effect";
|
|||||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { runProcess } from "../../processRunner";
|
import { runProcess } from "../../processRunner";
|
||||||
import { GitHubCliError } from "@t3tools/contracts";
|
import { GitHubCliError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
GitHubCli,
|
GitHubCli,
|
||||||
type GitHubRepositoryCloneUrls,
|
type GitHubRepositoryCloneUrls,
|
||||||
|
|||||||
@@ -6,9 +6,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
|||||||
import { it } from "@effect/vitest";
|
import { it } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||||
import {
|
import {
|
||||||
type GitHubCliShape,
|
type GitHubCliShape,
|
||||||
@@ -16,11 +15,10 @@ import {
|
|||||||
GitHubCli,
|
GitHubCli,
|
||||||
} from "../Services/GitHubCli.ts";
|
} from "../Services/GitHubCli.ts";
|
||||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { GitServiceLive } from "./GitService.ts";
|
||||||
|
import { GitService } from "../Services/GitService.ts";
|
||||||
import { GitCoreLive } from "./GitCore.ts";
|
import { GitCoreLive } from "./GitCore.ts";
|
||||||
import { GitCore } from "../Services/GitCore.ts";
|
|
||||||
import { makeGitManager } from "./GitManager.ts";
|
import { makeGitManager } from "./GitManager.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
interface FakeGhScenario {
|
interface FakeGhScenario {
|
||||||
prListSequence?: string[];
|
prListSequence?: string[];
|
||||||
@@ -49,7 +47,6 @@ interface FakeGitTextGeneration {
|
|||||||
stagedSummary: string;
|
stagedSummary: string;
|
||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
includeBranch?: boolean;
|
includeBranch?: boolean;
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}) => Effect.Effect<
|
}) => Effect.Effect<
|
||||||
{ subject: string; body: string; branch?: string | undefined },
|
{ subject: string; body: string; branch?: string | undefined },
|
||||||
TextGenerationError
|
TextGenerationError
|
||||||
@@ -61,18 +58,11 @@ interface FakeGitTextGeneration {
|
|||||||
commitSummary: string;
|
commitSummary: string;
|
||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||||
generateBranchName: (input: {
|
generateBranchName: (input: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
message: string;
|
message: string;
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||||
generateThreadTitle: (input: {
|
|
||||||
cwd: string;
|
|
||||||
message: string;
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}) => Effect.Effect<{ title: string }, TextGenerationError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||||
@@ -116,11 +106,11 @@ function runGit(
|
|||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||||
GitCommandError,
|
GitCommandError,
|
||||||
GitCore
|
GitService
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const gitCore = yield* GitCore;
|
const gitService = yield* GitService;
|
||||||
return yield* gitCore.execute({
|
return yield* gitService.execute({
|
||||||
operation: "GitManager.test.runGit",
|
operation: "GitManager.test.runGit",
|
||||||
cwd,
|
cwd,
|
||||||
args,
|
args,
|
||||||
@@ -134,7 +124,7 @@ function initRepo(
|
|||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
void,
|
void,
|
||||||
PlatformError.PlatformError | GitCommandError,
|
PlatformError.PlatformError | GitCommandError,
|
||||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
FileSystem.FileSystem | Scope.Scope | GitService
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
@@ -150,7 +140,7 @@ function initRepo(
|
|||||||
function createBareRemote(): Effect.Effect<
|
function createBareRemote(): Effect.Effect<
|
||||||
string,
|
string,
|
||||||
PlatformError.PlatformError | GitCommandError,
|
PlatformError.PlatformError | GitCommandError,
|
||||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
FileSystem.FileSystem | Scope.Scope | GitService
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||||
@@ -176,10 +166,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
branch: "update-workflow",
|
branch: "update-workflow",
|
||||||
}),
|
}),
|
||||||
generateThreadTitle: () =>
|
|
||||||
Effect.succeed({
|
|
||||||
title: "Update workflow",
|
|
||||||
}),
|
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -217,17 +203,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
generateThreadTitle: (input) =>
|
|
||||||
implementation.generateThreadTitle(input).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "fake text generation failed",
|
|
||||||
...(cause !== undefined ? { cause } : {}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,20 +449,12 @@ function runStackedAction(
|
|||||||
input: {
|
input: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
action: "commit" | "commit_push" | "commit_push_pr";
|
action: "commit" | "commit_push" | "commit_push_pr";
|
||||||
actionId?: string;
|
|
||||||
commitMessage?: string;
|
commitMessage?: string;
|
||||||
featureBranch?: boolean;
|
featureBranch?: boolean;
|
||||||
filePaths?: readonly string[];
|
filePaths?: readonly string[];
|
||||||
},
|
},
|
||||||
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
|
|
||||||
) {
|
) {
|
||||||
return manager.runStackedAction(
|
return manager.runStackedAction(input);
|
||||||
{
|
|
||||||
...input,
|
|
||||||
actionId: input.actionId ?? "test-action-id",
|
|
||||||
},
|
|
||||||
options,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
||||||
@@ -507,34 +474,26 @@ function makeManager(input?: {
|
|||||||
}) {
|
}) {
|
||||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||||
const textGeneration = createTextGeneration(input?.textGeneration);
|
const textGeneration = createTextGeneration(input?.textGeneration);
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-git-manager-test-",
|
|
||||||
});
|
|
||||||
|
|
||||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
|
||||||
|
|
||||||
const gitCoreLayer = GitCoreLive.pipe(
|
const gitCoreLayer = GitCoreLive.pipe(
|
||||||
|
Layer.provideMerge(GitServiceLive),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const managerLayer = Layer.mergeAll(
|
const managerLayer = Layer.mergeAll(
|
||||||
Layer.succeed(GitHubCli, gitHubCli),
|
Layer.succeed(GitHubCli, gitHubCli),
|
||||||
Layer.succeed(TextGeneration, textGeneration),
|
Layer.succeed(TextGeneration, textGeneration),
|
||||||
gitCoreLayer,
|
gitCoreLayer,
|
||||||
serverSettingsLayer,
|
NodeServices.layer,
|
||||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
);
|
||||||
|
|
||||||
return makeGitManager().pipe(
|
return makeGitManager.pipe(
|
||||||
Effect.provide(managerLayer),
|
Effect.provide(managerLayer),
|
||||||
Effect.map((manager) => ({ manager, ghCalls })),
|
Effect.map((manager) => ({ manager, ghCalls })),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const GitManagerTestLayer = GitCoreLive.pipe(
|
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||||
@@ -1977,117 +1936,4 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
expect(errorMessage).toContain("already checked out in the main repo");
|
expect(errorMessage).toContain("already checked out in the main repo");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("emits ordered progress events for commit hooks", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
|
||||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
|
|
||||||
{ mode: 0o755 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager();
|
|
||||||
const events: GitActionProgressEvent[] = [];
|
|
||||||
|
|
||||||
const result = yield* runStackedAction(
|
|
||||||
manager,
|
|
||||||
{
|
|
||||||
cwd: repoDir,
|
|
||||||
action: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionId: "action-1",
|
|
||||||
progressReporter: {
|
|
||||||
publish: (event) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
events.push(event);
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result.commit.status).toBe("created");
|
|
||||||
expect(events.map((event) => event.kind)).toContain("action_started");
|
|
||||||
expect(events).toEqual(
|
|
||||||
expect.arrayContaining([
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "phase_started",
|
|
||||||
phase: "commit",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "hook_started",
|
|
||||||
hookName: "pre-commit",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "hook_output",
|
|
||||||
text: "hook: start",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "hook_output",
|
|
||||||
text: "hook: end",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "hook_finished",
|
|
||||||
hookName: "pre-commit",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "action_finished",
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("emits action_failed when a commit hook rejects", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
|
||||||
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
|
|
||||||
{ mode: 0o755 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager();
|
|
||||||
const events: GitActionProgressEvent[] = [];
|
|
||||||
|
|
||||||
const errorMessage = yield* runStackedAction(
|
|
||||||
manager,
|
|
||||||
{
|
|
||||||
cwd: repoDir,
|
|
||||||
action: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionId: "action-2",
|
|
||||||
progressReporter: {
|
|
||||||
publish: (event) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
events.push(event);
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
).pipe(
|
|
||||||
Effect.flip,
|
|
||||||
Effect.map((error) => error.message),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(errorMessage).toContain("hook: fail");
|
|
||||||
expect(events).toEqual(
|
|
||||||
expect.arrayContaining([
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "hook_started",
|
|
||||||
hookName: "pre-commit",
|
|
||||||
}),
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "action_failed",
|
|
||||||
phase: "commit",
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it, assert } from "@effect/vitest";
|
||||||
|
import { Effect, Layer, Schema } from "effect";
|
||||||
|
|
||||||
|
import { GitCommandError } from "../Errors.ts";
|
||||||
|
import { GitServiceLive } from "./GitService.ts";
|
||||||
|
import { GitService } from "../Services/GitService.ts";
|
||||||
|
|
||||||
|
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||||
|
|
||||||
|
layer("GitServiceLive", (it) => {
|
||||||
|
it.effect("runGit executes successful git commands", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* gitService.execute({
|
||||||
|
operation: "GitProcess.test.version",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["--version"],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.code, 0);
|
||||||
|
assert.ok(result.stdout.toLowerCase().includes("git version"));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("runGit can return non-zero exit codes when allowed", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* gitService.execute({
|
||||||
|
operation: "GitProcess.test.allowNonZero",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.notEqual(result.code, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* Effect.result(
|
||||||
|
gitService.execute({
|
||||||
|
operation: "GitProcess.test.failOnNonZero",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(result._tag, "Failure");
|
||||||
|
if (result._tag === "Failure") {
|
||||||
|
assert.ok(Schema.is(GitCommandError)(result.failure));
|
||||||
|
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
|
||||||
|
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
/**
|
||||||
|
* Git process helpers - Effect-native git execution with typed errors.
|
||||||
|
*
|
||||||
|
* Centralizes child-process git invocation for server modules. This module
|
||||||
|
* only executes git commands and reports structured failures.
|
||||||
|
*
|
||||||
|
* @module GitServiceLive
|
||||||
|
*/
|
||||||
|
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||||
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
import { GitCommandError } from "../Errors.ts";
|
||||||
|
import {
|
||||||
|
ExecuteGitInput,
|
||||||
|
ExecuteGitResult,
|
||||||
|
GitService,
|
||||||
|
GitServiceShape,
|
||||||
|
} from "../Services/GitService.ts";
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||||
|
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||||
|
|
||||||
|
function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||||
|
return `git ${args.join(" ")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toGitCommandError(
|
||||||
|
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
|
detail: string,
|
||||||
|
) {
|
||||||
|
return (cause: unknown) =>
|
||||||
|
Schema.is(GitCommandError)(cause)
|
||||||
|
? cause
|
||||||
|
: new GitCommandError({
|
||||||
|
operation: input.operation,
|
||||||
|
command: quoteGitCommand(input.args),
|
||||||
|
cwd: input.cwd,
|
||||||
|
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
|
||||||
|
...(cause !== undefined ? { cause } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const collectOutput = Effect.fn(function* <E>(
|
||||||
|
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
|
stream: Stream.Stream<Uint8Array, E>,
|
||||||
|
maxOutputBytes: number,
|
||||||
|
): Effect.fn.Return<string, GitCommandError> {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let bytes = 0;
|
||||||
|
let text = "";
|
||||||
|
|
||||||
|
yield* Stream.runForEach(stream, (chunk) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
bytes += chunk.byteLength;
|
||||||
|
if (bytes > maxOutputBytes) {
|
||||||
|
return yield* new GitCommandError({
|
||||||
|
operation: input.operation,
|
||||||
|
command: quoteGitCommand(input.args),
|
||||||
|
cwd: input.cwd,
|
||||||
|
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
text += decoder.decode(chunk, { stream: true });
|
||||||
|
}),
|
||||||
|
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||||
|
|
||||||
|
text += decoder.decode();
|
||||||
|
return text;
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeGitService = Effect.gen(function* () {
|
||||||
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
|
||||||
|
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||||
|
const commandInput = {
|
||||||
|
...input,
|
||||||
|
args: [...input.args],
|
||||||
|
} as const;
|
||||||
|
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
|
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||||
|
|
||||||
|
const commandEffect = Effect.gen(function* () {
|
||||||
|
const child = yield* commandSpawner
|
||||||
|
.spawn(
|
||||||
|
ChildProcess.make("git", commandInput.args, {
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
...(input.env ? { env: input.env } : {}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||||
|
|
||||||
|
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||||
|
[
|
||||||
|
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||||
|
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||||
|
child.exitCode.pipe(
|
||||||
|
Effect.map((value) => Number(value)),
|
||||||
|
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||||
|
const trimmedStderr = stderr.trim();
|
||||||
|
return yield* new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail:
|
||||||
|
trimmedStderr.length > 0
|
||||||
|
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||||
|
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||||
|
});
|
||||||
|
|
||||||
|
return yield* commandEffect.pipe(
|
||||||
|
Effect.scoped,
|
||||||
|
Effect.timeoutOption(timeoutMs),
|
||||||
|
Effect.flatMap((result) =>
|
||||||
|
Option.match(result, {
|
||||||
|
onNone: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
onSome: Effect.succeed,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
execute,
|
||||||
|
} satisfies GitServiceShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GitServiceLive = Layer.effect(GitService, makeGitService);
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
/**
|
|
||||||
* RoutingTextGeneration – Dispatches text generation requests to either the
|
|
||||||
* Codex CLI or Claude CLI implementation based on the provider in each
|
|
||||||
* request input.
|
|
||||||
*
|
|
||||||
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
|
|
||||||
* the Claude layer; for any other value (including the default `undefined`) it
|
|
||||||
* falls through to the Codex layer.
|
|
||||||
*
|
|
||||||
* @module RoutingTextGeneration
|
|
||||||
*/
|
|
||||||
import { Effect, Layer, ServiceMap } from "effect";
|
|
||||||
|
|
||||||
import {
|
|
||||||
TextGeneration,
|
|
||||||
type TextGenerationProvider,
|
|
||||||
type TextGenerationShape,
|
|
||||||
} from "../Services/TextGeneration.ts";
|
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
|
||||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Internal service tags so both concrete layers can coexist.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
|
|
||||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
|
|
||||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Routing implementation
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const makeRoutingTextGeneration = Effect.gen(function* () {
|
|
||||||
const codex = yield* CodexTextGen;
|
|
||||||
const claude = yield* ClaudeTextGen;
|
|
||||||
|
|
||||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
|
||||||
provider === "claudeAgent" ? claude : codex;
|
|
||||||
|
|
||||||
return {
|
|
||||||
generateCommitMessage: (input) =>
|
|
||||||
route(input.modelSelection.provider).generateCommitMessage(input),
|
|
||||||
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
|
|
||||||
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
|
|
||||||
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
|
|
||||||
} satisfies TextGenerationShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
const InternalCodexLayer = Layer.effect(
|
|
||||||
CodexTextGen,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const svc = yield* TextGeneration;
|
|
||||||
return svc;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(CodexTextGenerationLive));
|
|
||||||
|
|
||||||
const InternalClaudeLayer = Layer.effect(
|
|
||||||
ClaudeTextGen,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const svc = yield* TextGeneration;
|
|
||||||
return svc;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(ClaudeTextGenerationLive));
|
|
||||||
|
|
||||||
export const RoutingTextGenerationLive = Layer.effect(
|
|
||||||
TextGeneration,
|
|
||||||
makeRoutingTextGeneration,
|
|
||||||
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
buildBranchNamePrompt,
|
|
||||||
buildCommitMessagePrompt,
|
|
||||||
buildPrContentPrompt,
|
|
||||||
buildThreadTitlePrompt,
|
|
||||||
} from "./Prompts.ts";
|
|
||||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
describe("buildCommitMessagePrompt", () => {
|
|
||||||
it("includes staged patch and summary in the prompt", () => {
|
|
||||||
const result = buildCommitMessagePrompt({
|
|
||||||
branch: "main",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md\n+hello",
|
|
||||||
includeBranch: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("Staged files:");
|
|
||||||
expect(result.prompt).toContain("M README.md");
|
|
||||||
expect(result.prompt).toContain("Staged patch:");
|
|
||||||
expect(result.prompt).toContain("diff --git a/README.md b/README.md");
|
|
||||||
expect(result.prompt).toContain("Branch: main");
|
|
||||||
// Should NOT include the branch generation instruction
|
|
||||||
expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes branch generation instruction when includeBranch is true", () => {
|
|
||||||
const result = buildCommitMessagePrompt({
|
|
||||||
branch: "feature/foo",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff",
|
|
||||||
includeBranch: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("branch must be a short semantic git branch fragment");
|
|
||||||
expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch.");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("shows (detached) when branch is null", () => {
|
|
||||||
const result = buildCommitMessagePrompt({
|
|
||||||
branch: null,
|
|
||||||
stagedSummary: "M a.ts",
|
|
||||||
stagedPatch: "diff",
|
|
||||||
includeBranch: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("Branch: (detached)");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("buildPrContentPrompt", () => {
|
|
||||||
it("includes branch names, commits, and diff in the prompt", () => {
|
|
||||||
const result = buildPrContentPrompt({
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/auth",
|
|
||||||
commitSummary: "feat: add login page",
|
|
||||||
diffSummary: "3 files changed",
|
|
||||||
diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("Base branch: main");
|
|
||||||
expect(result.prompt).toContain("Head branch: feature/auth");
|
|
||||||
expect(result.prompt).toContain("Commits:");
|
|
||||||
expect(result.prompt).toContain("feat: add login page");
|
|
||||||
expect(result.prompt).toContain("Diff stat:");
|
|
||||||
expect(result.prompt).toContain("3 files changed");
|
|
||||||
expect(result.prompt).toContain("Diff patch:");
|
|
||||||
expect(result.prompt).toContain("export function login()");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("buildBranchNamePrompt", () => {
|
|
||||||
it("includes the user message in the prompt", () => {
|
|
||||||
const result = buildBranchNamePrompt({
|
|
||||||
message: "Fix the login timeout bug",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("User message:");
|
|
||||||
expect(result.prompt).toContain("Fix the login timeout bug");
|
|
||||||
expect(result.prompt).not.toContain("Attachment metadata:");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes attachment metadata when attachments are provided", () => {
|
|
||||||
const result = buildBranchNamePrompt({
|
|
||||||
message: "Fix the layout from screenshot",
|
|
||||||
attachments: [
|
|
||||||
{
|
|
||||||
type: "image" as const,
|
|
||||||
id: "att-123",
|
|
||||||
name: "screenshot.png",
|
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 12345,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("Attachment metadata:");
|
|
||||||
expect(result.prompt).toContain("screenshot.png");
|
|
||||||
expect(result.prompt).toContain("image/png");
|
|
||||||
expect(result.prompt).toContain("12345 bytes");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("buildThreadTitlePrompt", () => {
|
|
||||||
it("includes the user message in the prompt", () => {
|
|
||||||
const result = buildThreadTitlePrompt({
|
|
||||||
message: "Investigate reconnect regressions after session restore",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("User message:");
|
|
||||||
expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
|
|
||||||
expect(result.prompt).not.toContain("Attachment metadata:");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes attachment metadata when attachments are provided", () => {
|
|
||||||
const result = buildThreadTitlePrompt({
|
|
||||||
message: "Name this thread from the screenshot",
|
|
||||||
attachments: [
|
|
||||||
{
|
|
||||||
type: "image" as const,
|
|
||||||
id: "att-456",
|
|
||||||
name: "thread.png",
|
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 67890,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.prompt).toContain("Attachment metadata:");
|
|
||||||
expect(result.prompt).toContain("thread.png");
|
|
||||||
expect(result.prompt).toContain("image/png");
|
|
||||||
expect(result.prompt).toContain("67890 bytes");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("sanitizeThreadTitle", () => {
|
|
||||||
it("truncates long titles with the shared sidebar-safe limit", () => {
|
|
||||||
expect(
|
|
||||||
sanitizeThreadTitle(
|
|
||||||
' "Reconnect failures after restart because the session state does not recover" ',
|
|
||||||
),
|
|
||||||
).toBe("Reconnect failures after restart because the se...");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("normalizeCliError", () => {
|
|
||||||
it("detects 'Command not found' and includes CLI name in the message", () => {
|
|
||||||
const error = normalizeCliError(
|
|
||||||
"claude",
|
|
||||||
"generateCommitMessage",
|
|
||||||
new Error("Command not found: claude"),
|
|
||||||
"Something went wrong",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(TextGenerationError);
|
|
||||||
expect(error.detail).toContain("Claude CLI");
|
|
||||||
expect(error.detail).toContain("not available on PATH");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses the CLI name from the first argument for codex", () => {
|
|
||||||
const error = normalizeCliError(
|
|
||||||
"codex",
|
|
||||||
"generateBranchName",
|
|
||||||
new Error("Command not found: codex"),
|
|
||||||
"Something went wrong",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(TextGenerationError);
|
|
||||||
expect(error.detail).toContain("Codex CLI");
|
|
||||||
expect(error.detail).toContain("not available on PATH");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns the error as-is if it is already a TextGenerationError", () => {
|
|
||||||
const existing = new TextGenerationError({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
detail: "Already wrapped",
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
|
|
||||||
|
|
||||||
expect(result).toBe(existing);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("wraps unknown non-Error values with the fallback message", () => {
|
|
||||||
const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
|
|
||||||
|
|
||||||
expect(result).toBeInstanceOf(TextGenerationError);
|
|
||||||
expect(result.detail).toBe("fallback");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
/**
|
|
||||||
* Shared prompt builders for text generation providers.
|
|
||||||
*
|
|
||||||
* Extracts the prompt construction logic that is identical across
|
|
||||||
* Codex, Claude, and any future CLI-based text generation backends.
|
|
||||||
*
|
|
||||||
* @module textGenerationPrompts
|
|
||||||
*/
|
|
||||||
import { Schema } from "effect";
|
|
||||||
import type { ChatAttachment } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { limitSection } from "./Utils.ts";
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Commit message
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export interface CommitMessagePromptInput {
|
|
||||||
branch: string | null;
|
|
||||||
stagedSummary: string;
|
|
||||||
stagedPatch: string;
|
|
||||||
includeBranch: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
|
||||||
const wantsBranch = input.includeBranch;
|
|
||||||
|
|
||||||
const prompt = [
|
|
||||||
"You write concise git commit messages.",
|
|
||||||
wantsBranch
|
|
||||||
? "Return a JSON object with keys: subject, body, branch."
|
|
||||||
: "Return a JSON object with keys: subject, body.",
|
|
||||||
"Rules:",
|
|
||||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
|
||||||
"- body can be empty string or short bullet points",
|
|
||||||
...(wantsBranch
|
|
||||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
|
||||||
: []),
|
|
||||||
"- capture the primary user-visible or developer-visible change",
|
|
||||||
"",
|
|
||||||
`Branch: ${input.branch ?? "(detached)"}`,
|
|
||||||
"",
|
|
||||||
"Staged files:",
|
|
||||||
limitSection(input.stagedSummary, 6_000),
|
|
||||||
"",
|
|
||||||
"Staged patch:",
|
|
||||||
limitSection(input.stagedPatch, 40_000),
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
if (wantsBranch) {
|
|
||||||
return {
|
|
||||||
prompt,
|
|
||||||
outputSchema: Schema.Struct({
|
|
||||||
subject: Schema.String,
|
|
||||||
body: Schema.String,
|
|
||||||
branch: Schema.String,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
prompt,
|
|
||||||
outputSchema: Schema.Struct({
|
|
||||||
subject: Schema.String,
|
|
||||||
body: Schema.String,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// PR content
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export interface PrContentPromptInput {
|
|
||||||
baseBranch: string;
|
|
||||||
headBranch: string;
|
|
||||||
commitSummary: string;
|
|
||||||
diffSummary: string;
|
|
||||||
diffPatch: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
|
||||||
const prompt = [
|
|
||||||
"You write GitHub pull request content.",
|
|
||||||
"Return a JSON object with keys: title, body.",
|
|
||||||
"Rules:",
|
|
||||||
"- title should be concise and specific",
|
|
||||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
|
||||||
"- under Summary, provide short bullet points",
|
|
||||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
|
||||||
"",
|
|
||||||
`Base branch: ${input.baseBranch}`,
|
|
||||||
`Head branch: ${input.headBranch}`,
|
|
||||||
"",
|
|
||||||
"Commits:",
|
|
||||||
limitSection(input.commitSummary, 12_000),
|
|
||||||
"",
|
|
||||||
"Diff stat:",
|
|
||||||
limitSection(input.diffSummary, 12_000),
|
|
||||||
"",
|
|
||||||
"Diff patch:",
|
|
||||||
limitSection(input.diffPatch, 40_000),
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
const outputSchema = Schema.Struct({
|
|
||||||
title: Schema.String,
|
|
||||||
body: Schema.String,
|
|
||||||
});
|
|
||||||
|
|
||||||
return { prompt, outputSchema };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Branch name
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export interface BranchNamePromptInput {
|
|
||||||
message: string;
|
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PromptFromMessageInput {
|
|
||||||
instruction: string;
|
|
||||||
responseShape: string;
|
|
||||||
rules: ReadonlyArray<string>;
|
|
||||||
message: string;
|
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
|
||||||
const attachmentLines = (input.attachments ?? []).map(
|
|
||||||
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const promptSections = [
|
|
||||||
input.instruction,
|
|
||||||
input.responseShape,
|
|
||||||
"Rules:",
|
|
||||||
...input.rules.map((rule) => `- ${rule}`),
|
|
||||||
"",
|
|
||||||
"User message:",
|
|
||||||
limitSection(input.message, 8_000),
|
|
||||||
];
|
|
||||||
if (attachmentLines.length > 0) {
|
|
||||||
promptSections.push(
|
|
||||||
"",
|
|
||||||
"Attachment metadata:",
|
|
||||||
limitSection(attachmentLines.join("\n"), 4_000),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return promptSections.join("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
|
||||||
const prompt = buildPromptFromMessage({
|
|
||||||
instruction: "You generate concise git branch names.",
|
|
||||||
responseShape: "Return a JSON object with key: branch.",
|
|
||||||
rules: [
|
|
||||||
"Branch should describe the requested work from the user message.",
|
|
||||||
"Keep it short and specific (2-6 words).",
|
|
||||||
"Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
|
||||||
"If images are attached, use them as primary context for visual/UI issues.",
|
|
||||||
],
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
const outputSchema = Schema.Struct({
|
|
||||||
branch: Schema.String,
|
|
||||||
});
|
|
||||||
|
|
||||||
return { prompt, outputSchema };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Thread title
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export interface ThreadTitlePromptInput {
|
|
||||||
message: string;
|
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
|
||||||
const prompt = buildPromptFromMessage({
|
|
||||||
instruction: "You write concise thread titles for coding conversations.",
|
|
||||||
responseShape: "Return a JSON object with key: title.",
|
|
||||||
rules: [
|
|
||||||
"Title should summarize the user's request, not restate it verbatim.",
|
|
||||||
"Keep it short and specific (3-8 words).",
|
|
||||||
"Avoid quotes, filler, prefixes, and trailing punctuation.",
|
|
||||||
"If images are attached, use them as primary context for visual/UI issues.",
|
|
||||||
],
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
const outputSchema = Schema.Struct({
|
|
||||||
title: Schema.String,
|
|
||||||
});
|
|
||||||
|
|
||||||
return { prompt, outputSchema };
|
|
||||||
}
|
|
||||||
@@ -22,28 +22,7 @@ import type {
|
|||||||
GitStatusResult,
|
GitStatusResult,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
|
||||||
import type { GitCommandError } from "@t3tools/contracts";
|
import type { GitCommandError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface ExecuteGitInput {
|
|
||||||
readonly operation: string;
|
|
||||||
readonly cwd: string;
|
|
||||||
readonly args: ReadonlyArray<string>;
|
|
||||||
readonly stdin?: string;
|
|
||||||
readonly env?: NodeJS.ProcessEnv;
|
|
||||||
readonly allowNonZeroExit?: boolean;
|
|
||||||
readonly timeoutMs?: number;
|
|
||||||
readonly maxOutputBytes?: number;
|
|
||||||
readonly truncateOutputAtMaxBytes?: boolean;
|
|
||||||
readonly progress?: ExecuteGitProgress;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ExecuteGitResult {
|
|
||||||
readonly code: number;
|
|
||||||
readonly stdout: string;
|
|
||||||
readonly stderr: string;
|
|
||||||
readonly stdoutTruncated: boolean;
|
|
||||||
readonly stderrTruncated: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||||
upstreamRef: string | null;
|
upstreamRef: string | null;
|
||||||
@@ -54,35 +33,6 @@ export interface GitPreparedCommitContext {
|
|||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExecuteGitProgress {
|
|
||||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
|
||||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
|
||||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
|
||||||
readonly onHookFinished?: (input: {
|
|
||||||
hookName: string;
|
|
||||||
exitCode: number | null;
|
|
||||||
durationMs: number | null;
|
|
||||||
}) => Effect.Effect<void, never>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitCommitProgress {
|
|
||||||
readonly onOutputLine?: (input: {
|
|
||||||
stream: "stdout" | "stderr";
|
|
||||||
text: string;
|
|
||||||
}) => Effect.Effect<void, never>;
|
|
||||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
|
||||||
readonly onHookFinished?: (input: {
|
|
||||||
hookName: string;
|
|
||||||
exitCode: number | null;
|
|
||||||
durationMs: number | null;
|
|
||||||
}) => Effect.Effect<void, never>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitCommitOptions {
|
|
||||||
readonly timeoutMs?: number;
|
|
||||||
readonly progress?: GitCommitProgress;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitPushResult {
|
export interface GitPushResult {
|
||||||
status: "pushed" | "skipped_up_to_date";
|
status: "pushed" | "skipped_up_to_date";
|
||||||
branch: string;
|
branch: string;
|
||||||
@@ -96,11 +46,6 @@ export interface GitRangeContext {
|
|||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GitListWorkspaceFilesResult {
|
|
||||||
readonly paths: ReadonlyArray<string>;
|
|
||||||
readonly truncated: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitRenameBranchInput {
|
export interface GitRenameBranchInput {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
oldBranch: string;
|
oldBranch: string;
|
||||||
@@ -141,11 +86,6 @@ export interface GitSetBranchUpstreamInput {
|
|||||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||||
*/
|
*/
|
||||||
export interface GitCoreShape {
|
export interface GitCoreShape {
|
||||||
/**
|
|
||||||
* Execute a raw Git command.
|
|
||||||
*/
|
|
||||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read Git status for a repository.
|
* Read Git status for a repository.
|
||||||
*/
|
*/
|
||||||
@@ -171,7 +111,6 @@ export interface GitCoreShape {
|
|||||||
cwd: string,
|
cwd: string,
|
||||||
subject: string,
|
subject: string,
|
||||||
body: string,
|
body: string,
|
||||||
options?: GitCommitOptions,
|
|
||||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -198,26 +137,6 @@ export interface GitCoreShape {
|
|||||||
key: string,
|
key: string,
|
||||||
) => Effect.Effect<string | null, GitCommandError>;
|
) => Effect.Effect<string | null, GitCommandError>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the provided cwd is inside a git work tree.
|
|
||||||
*/
|
|
||||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List tracked and untracked workspace file paths relative to cwd.
|
|
||||||
*/
|
|
||||||
readonly listWorkspaceFiles: (
|
|
||||||
cwd: string,
|
|
||||||
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove gitignored paths from a relative path list.
|
|
||||||
*/
|
|
||||||
readonly filterIgnoredPaths: (
|
|
||||||
cwd: string,
|
|
||||||
relativePaths: ReadonlyArray<string>,
|
|
||||||
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List local + remote branches and branch metadata.
|
* List local + remote branches and branch metadata.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { ServiceMap } from "effect";
|
|||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
import type { ProcessRunResult } from "../../processRunner";
|
import type { ProcessRunResult } from "../../processRunner";
|
||||||
import type { GitHubCliError } from "@t3tools/contracts";
|
import type { GitHubCliError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface GitHubPullRequestSummary {
|
export interface GitHubPullRequestSummary {
|
||||||
readonly number: number;
|
readonly number: number;
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
* @module GitManager
|
* @module GitManager
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
GitActionProgressEvent,
|
|
||||||
GitPreparePullRequestThreadInput,
|
GitPreparePullRequestThreadInput,
|
||||||
GitPreparePullRequestThreadResult,
|
GitPreparePullRequestThreadResult,
|
||||||
GitPullRequestRefInput,
|
GitPullRequestRefInput,
|
||||||
@@ -19,16 +18,7 @@ import {
|
|||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { ServiceMap } from "effect";
|
import { ServiceMap } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
import type { GitManagerServiceError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface GitActionProgressReporter {
|
|
||||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitRunStackedActionOptions {
|
|
||||||
readonly actionId?: string;
|
|
||||||
readonly progressReporter?: GitActionProgressReporter;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GitManagerShape - Service API for high-level Git workflow actions.
|
* GitManagerShape - Service API for high-level Git workflow actions.
|
||||||
@@ -61,7 +51,6 @@ export interface GitManagerShape {
|
|||||||
*/
|
*/
|
||||||
readonly runStackedAction: (
|
readonly runStackedAction: (
|
||||||
input: GitRunStackedActionInput,
|
input: GitRunStackedActionInput,
|
||||||
options?: GitRunStackedActionOptions,
|
|
||||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* GitService - Service for Git command execution.
|
||||||
|
*
|
||||||
|
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||||
|
* domain errors for Git command execution.
|
||||||
|
*
|
||||||
|
* @module GitService
|
||||||
|
*/
|
||||||
|
import { ServiceMap } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
|
import type { GitCommandError } from "../Errors.ts";
|
||||||
|
|
||||||
|
export interface ExecuteGitInput {
|
||||||
|
readonly operation: string;
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly args: ReadonlyArray<string>;
|
||||||
|
readonly env?: NodeJS.ProcessEnv;
|
||||||
|
readonly allowNonZeroExit?: boolean;
|
||||||
|
readonly timeoutMs?: number;
|
||||||
|
readonly maxOutputBytes?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExecuteGitResult {
|
||||||
|
readonly code: number;
|
||||||
|
readonly stdout: string;
|
||||||
|
readonly stderr: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitServiceShape - Service API for Git command execution.
|
||||||
|
*/
|
||||||
|
export interface GitServiceShape {
|
||||||
|
/**
|
||||||
|
* Execute a Git command.
|
||||||
|
*/
|
||||||
|
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitService - Service for Git command execution.
|
||||||
|
*/
|
||||||
|
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
|
||||||
|
"t3/git/Services/GitService",
|
||||||
|
) {}
|
||||||
@@ -8,12 +8,9 @@
|
|||||||
*/
|
*/
|
||||||
import { ServiceMap } from "effect";
|
import { ServiceMap } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import type { TextGenerationError } from "@t3tools/contracts";
|
import type { TextGenerationError } from "../Errors.ts";
|
||||||
|
|
||||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
|
||||||
export type TextGenerationProvider = "codex" | "claudeAgent";
|
|
||||||
|
|
||||||
export interface CommitMessageGenerationInput {
|
export interface CommitMessageGenerationInput {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
@@ -22,8 +19,6 @@ export interface CommitMessageGenerationInput {
|
|||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
/** When true, the model also returns a semantic branch name for the change. */
|
/** When true, the model also returns a semantic branch name for the change. */
|
||||||
includeBranch?: boolean;
|
includeBranch?: boolean;
|
||||||
/** What model and provider to use for generation. */
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CommitMessageGenerationResult {
|
export interface CommitMessageGenerationResult {
|
||||||
@@ -40,8 +35,6 @@ export interface PrContentGenerationInput {
|
|||||||
commitSummary: string;
|
commitSummary: string;
|
||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
/** What model and provider to use for generation. */
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PrContentGenerationResult {
|
export interface PrContentGenerationResult {
|
||||||
@@ -53,33 +46,18 @@ export interface BranchNameGenerationInput {
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
message: string;
|
message: string;
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
/** What model and provider to use for generation. */
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BranchNameGenerationResult {
|
export interface BranchNameGenerationResult {
|
||||||
branch: string;
|
branch: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ThreadTitleGenerationInput {
|
|
||||||
cwd: string;
|
|
||||||
message: string;
|
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
|
||||||
/** What model and provider to use for generation. */
|
|
||||||
modelSelection: ModelSelection;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ThreadTitleGenerationResult {
|
|
||||||
title: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TextGenerationService {
|
export interface TextGenerationService {
|
||||||
generateCommitMessage(
|
generateCommitMessage(
|
||||||
input: CommitMessageGenerationInput,
|
input: CommitMessageGenerationInput,
|
||||||
): Promise<CommitMessageGenerationResult>;
|
): Promise<CommitMessageGenerationResult>;
|
||||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||||
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -106,13 +84,6 @@ export interface TextGenerationShape {
|
|||||||
readonly generateBranchName: (
|
readonly generateBranchName: (
|
||||||
input: BranchNameGenerationInput,
|
input: BranchNameGenerationInput,
|
||||||
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate a concise thread title from a user's first message.
|
|
||||||
*/
|
|
||||||
readonly generateThreadTitle: (
|
|
||||||
input: ThreadTitleGenerationInput,
|
|
||||||
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
/**
|
|
||||||
* Shared utilities for text generation layers (Codex, Claude, etc.).
|
|
||||||
*
|
|
||||||
* @module textGenerationUtils
|
|
||||||
*/
|
|
||||||
import { Schema } from "effect";
|
|
||||||
|
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { existsSync } from "node:fs";
|
|
||||||
import { join } from "node:path";
|
|
||||||
|
|
||||||
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;
|
|
||||||
const truncated = value.slice(0, maxChars);
|
|
||||||
return `${truncated}\n\n[truncated]`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
|
||||||
export function sanitizeCommitSubject(raw: string): string {
|
|
||||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
|
||||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
|
||||||
if (withoutTrailingPeriod.length === 0) {
|
|
||||||
return "Update project files";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (withoutTrailingPeriod.length <= 72) {
|
|
||||||
return withoutTrailingPeriod;
|
|
||||||
}
|
|
||||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise a raw PR title to a single line with a sensible fallback. */
|
|
||||||
export function sanitizePrTitle(raw: string): string {
|
|
||||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
|
||||||
if (singleLine.length > 0) {
|
|
||||||
return singleLine;
|
|
||||||
}
|
|
||||||
return "Update project changes";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
|
|
||||||
export function sanitizeThreadTitle(raw: string): string {
|
|
||||||
const normalized = raw
|
|
||||||
.trim()
|
|
||||||
.split(/\r?\n/g)[0]
|
|
||||||
?.trim()
|
|
||||||
.replace(/^['"`]+|['"`]+$/g, "")
|
|
||||||
.trim()
|
|
||||||
.replace(/\s+/g, " ");
|
|
||||||
|
|
||||||
if (!normalized || normalized.trim().length === 0) {
|
|
||||||
return "New thread";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (normalized.length <= 50) {
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${normalized.slice(0, 47).trimEnd()}...`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
|
|
||||||
function cliLabel(cliName: string): string {
|
|
||||||
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
|
|
||||||
return `${capitalized} CLI (\`${cliName}\`)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Normalize an unknown error from a CLI text generation process into a
|
|
||||||
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
|
|
||||||
* and Claude (and future providers) can share the same logic.
|
|
||||||
*/
|
|
||||||
export function normalizeCliError(
|
|
||||||
cliName: string,
|
|
||||||
operation: string,
|
|
||||||
error: unknown,
|
|
||||||
fallback: string,
|
|
||||||
): TextGenerationError {
|
|
||||||
if (Schema.is(TextGenerationError)(error)) {
|
|
||||||
return error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error instanceof Error) {
|
|
||||||
const lower = error.message.toLowerCase();
|
|
||||||
if (
|
|
||||||
error.message.includes(`Command not found: ${cliName}`) ||
|
|
||||||
lower.includes(`spawn ${cliName}`) ||
|
|
||||||
lower.includes("enoent")
|
|
||||||
) {
|
|
||||||
return new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
|
|
||||||
cause: error,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: `${fallback}: ${error.message}`,
|
|
||||||
cause: error,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: fallback,
|
|
||||||
cause: error,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
export function isGitRepository(cwd: string): boolean {
|
||||||
|
return existsSync(join(cwd, ".git"));
|
||||||
|
}
|
||||||
@@ -1,197 +0,0 @@
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
|
||||||
import { Effect, FileSystem, Option, Path } from "effect";
|
|
||||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
||||||
|
|
||||||
import {
|
|
||||||
ATTACHMENTS_ROUTE_PREFIX,
|
|
||||||
normalizeAttachmentRelativePath,
|
|
||||||
resolveAttachmentRelativePath,
|
|
||||||
} from "./attachmentPaths";
|
|
||||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
|
||||||
import { ServerConfig } from "./config";
|
|
||||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
|
||||||
|
|
||||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
|
||||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
|
||||||
|
|
||||||
export const attachmentsRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const url = HttpServerRequest.toURL(request);
|
|
||||||
if (Option.isNone(url)) {
|
|
||||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
|
||||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
|
||||||
if (!normalizedRelativePath) {
|
|
||||||
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const isIdLookup =
|
|
||||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
|
||||||
const filePath = isIdLookup
|
|
||||||
? resolveAttachmentPathById({
|
|
||||||
attachmentsDir: config.attachmentsDir,
|
|
||||||
attachmentId: normalizedRelativePath,
|
|
||||||
})
|
|
||||||
: resolveAttachmentRelativePath({
|
|
||||||
attachmentsDir: config.attachmentsDir,
|
|
||||||
relativePath: normalizedRelativePath,
|
|
||||||
});
|
|
||||||
if (!filePath) {
|
|
||||||
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
|
|
||||||
status: isIdLookup ? 404 : 400,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const fileInfo = yield* fileSystem
|
|
||||||
.stat(filePath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
|
||||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* HttpServerResponse.file(filePath, {
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
"Cache-Control": "public, max-age=31536000, immutable",
|
|
||||||
},
|
|
||||||
}).pipe(
|
|
||||||
Effect.catch(() =>
|
|
||||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const projectFaviconRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"/api/project-favicon",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const url = HttpServerRequest.toURL(request);
|
|
||||||
if (Option.isNone(url)) {
|
|
||||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectCwd = url.value.searchParams.get("cwd");
|
|
||||||
if (!projectCwd) {
|
|
||||||
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const faviconResolver = yield* ProjectFaviconResolver;
|
|
||||||
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
|
|
||||||
if (!faviconFilePath) {
|
|
||||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
|
||||||
status: 200,
|
|
||||||
contentType: "image/svg+xml",
|
|
||||||
headers: {
|
|
||||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* HttpServerResponse.file(faviconFilePath, {
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
|
||||||
},
|
|
||||||
}).pipe(
|
|
||||||
Effect.catch(() =>
|
|
||||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"*",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const url = HttpServerRequest.toURL(request);
|
|
||||||
if (Option.isNone(url)) {
|
|
||||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
if (config.devUrl) {
|
|
||||||
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!config.staticDir) {
|
|
||||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
|
||||||
status: 503,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const staticRoot = path.resolve(config.staticDir);
|
|
||||||
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
|
||||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
|
||||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
|
||||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
|
||||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
|
||||||
if (
|
|
||||||
staticRelativePath.length === 0 ||
|
|
||||||
hasRawLeadingParentSegment ||
|
|
||||||
hasPathTraversalSegment ||
|
|
||||||
staticRelativePath.includes("\0")
|
|
||||||
) {
|
|
||||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const isWithinStaticRoot = (candidate: string) =>
|
|
||||||
candidate === staticRoot ||
|
|
||||||
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
|
|
||||||
|
|
||||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
|
||||||
if (!isWithinStaticRoot(filePath)) {
|
|
||||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const ext = path.extname(filePath);
|
|
||||||
if (!ext) {
|
|
||||||
filePath = path.resolve(filePath, "index.html");
|
|
||||||
if (!isWithinStaticRoot(filePath)) {
|
|
||||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileInfo = yield* fileSystem
|
|
||||||
.stat(filePath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
|
||||||
const indexPath = path.resolve(staticRoot, "index.html");
|
|
||||||
const indexData = yield* fileSystem
|
|
||||||
.readFile(indexPath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!indexData) {
|
|
||||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
||||||
}
|
|
||||||
return HttpServerResponse.uint8Array(indexData, {
|
|
||||||
status: 200,
|
|
||||||
contentType: "text/html; charset=utf-8",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
|
||||||
const data = yield* fileSystem
|
|
||||||
.readFile(filePath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!data) {
|
|
||||||
return HttpServerResponse.text("Internal Server Error", { status: 500 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return HttpServerResponse.uint8Array(data, {
|
|
||||||
status: 200,
|
|
||||||
contentType,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Layer from "effect/Layer";
|
||||||
|
|
||||||
|
import { CliConfig, t3Cli } from "./main";
|
||||||
|
import { OpenLive } from "./open";
|
||||||
|
import { Command } from "effect/unstable/cli";
|
||||||
|
import { version } from "../package.json" with { type: "json" };
|
||||||
|
import { ServerLive } from "./wsServer";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
import { FetchHttpClient } from "effect/unstable/http";
|
||||||
|
|
||||||
|
const RuntimeLayer = Layer.empty.pipe(
|
||||||
|
Layer.provideMerge(CliConfig.layer),
|
||||||
|
Layer.provideMerge(ServerLive),
|
||||||
|
Layer.provideMerge(OpenLive),
|
||||||
|
Layer.provideMerge(NetService.layer),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
Layer.provideMerge(FetchHttpClient.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
|
||||||
@@ -3,31 +3,35 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
|||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { assertFailure } from "@effect/vitest/utils";
|
import { assertFailure } from "@effect/vitest/utils";
|
||||||
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_KEYBINDINGS,
|
DEFAULT_KEYBINDINGS,
|
||||||
Keybindings,
|
Keybindings,
|
||||||
|
KeybindingsConfigError,
|
||||||
KeybindingsLive,
|
KeybindingsLive,
|
||||||
ResolvedKeybindingFromConfig,
|
ResolvedKeybindingFromConfig,
|
||||||
compileResolvedKeybindingRule,
|
compileResolvedKeybindingRule,
|
||||||
compileResolvedKeybindingsConfig,
|
compileResolvedKeybindingsConfig,
|
||||||
parseKeybindingShortcut,
|
parseKeybindingShortcut,
|
||||||
} from "./keybindings";
|
} from "./keybindings";
|
||||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||||
const makeKeybindingsLayer = () => {
|
const makeKeybindingsLayer = () =>
|
||||||
return KeybindingsLive.pipe(
|
KeybindingsLive.pipe(
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.fresh(
|
Layer.effect(
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
ServerConfig,
|
||||||
prefix: "t3code-keybindings-test-",
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
|
||||||
|
const configPath = join(dir, "keybindings.json");
|
||||||
|
return { keybindingsConfigPath: configPath } as ServerConfigShape;
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
};
|
|
||||||
|
|
||||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||||
effect.pipe(
|
effect.pipe(
|
||||||
@@ -38,9 +42,7 @@ const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R
|
|||||||
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
|
||||||
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
|
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
|
||||||
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
|
|
||||||
yield* fileSystem.writeFileString(configPath, encoded);
|
yield* fileSystem.writeFileString(configPath, encoded);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -165,19 +167,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
|||||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("ships configurable thread navigation defaults", () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
const defaultsByCommand = new Map(
|
|
||||||
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
|
|
||||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
|
||||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
|
||||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
|
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
|||||||
@@ -9,14 +9,12 @@
|
|||||||
import {
|
import {
|
||||||
KeybindingRule,
|
KeybindingRule,
|
||||||
KeybindingsConfig,
|
KeybindingsConfig,
|
||||||
KeybindingsConfigError,
|
|
||||||
KeybindingShortcut,
|
KeybindingShortcut,
|
||||||
KeybindingWhenNode,
|
KeybindingWhenNode,
|
||||||
MAX_KEYBINDINGS_COUNT,
|
MAX_KEYBINDINGS_COUNT,
|
||||||
MAX_WHEN_EXPRESSION_DEPTH,
|
MAX_WHEN_EXPRESSION_DEPTH,
|
||||||
ResolvedKeybindingRule,
|
ResolvedKeybindingRule,
|
||||||
ResolvedKeybindingsConfig,
|
ResolvedKeybindingsConfig,
|
||||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
|
||||||
type ServerConfigIssue,
|
type ServerConfigIssue,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Mutable } from "effect/Types";
|
import { Mutable } from "effect/Types";
|
||||||
@@ -25,7 +23,6 @@ import {
|
|||||||
Cache,
|
Cache,
|
||||||
Cause,
|
Cause,
|
||||||
Deferred,
|
Deferred,
|
||||||
Duration,
|
|
||||||
Effect,
|
Effect,
|
||||||
Exit,
|
Exit,
|
||||||
FileSystem,
|
FileSystem,
|
||||||
@@ -45,7 +42,19 @@ import {
|
|||||||
} from "effect";
|
} from "effect";
|
||||||
import * as Semaphore from "effect/Semaphore";
|
import * as Semaphore from "effect/Semaphore";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig } from "./config";
|
||||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
|
||||||
|
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||||
|
"KeybindingsConfigParseError",
|
||||||
|
{
|
||||||
|
configPath: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type WhenToken =
|
type WhenToken =
|
||||||
| { type: "identifier"; value: string }
|
| { type: "identifier"; value: string }
|
||||||
@@ -65,12 +74,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
|||||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||||
{ key: "mod+o", command: "editor.openFavorite" },
|
{ key: "mod+o", command: "editor.openFavorite" },
|
||||||
{ key: "mod+shift+[", command: "thread.previous" },
|
|
||||||
{ key: "mod+shift+]", command: "thread.next" },
|
|
||||||
...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
|
|
||||||
key: `mod+${index + 1}`,
|
|
||||||
command,
|
|
||||||
})),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function normalizeKeyToken(token: string): string {
|
function normalizeKeyToken(token: string): string {
|
||||||
@@ -405,7 +408,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
|||||||
|
|
||||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||||
|
|
||||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
|
||||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||||
SchemaGetter.stringifyJson({ space: 2 }),
|
SchemaGetter.stringifyJson({ space: 2 }),
|
||||||
@@ -669,7 +672,6 @@ const makeKeybindings = Effect.gen(function* () {
|
|||||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
new KeybindingsConfigError({
|
new KeybindingsConfigError({
|
||||||
@@ -815,25 +817,16 @@ const makeKeybindings = Effect.gen(function* () {
|
|||||||
|
|
||||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||||
|
|
||||||
// Debounce watch events so the file is fully written before we read it.
|
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
|
||||||
// Editors emit multiple events per save (truncate, write, rename) and
|
const isTargetConfigEvent =
|
||||||
// `fs.watch` can fire before the content has been flushed to disk.
|
event.path === keybindingsConfigFile ||
|
||||||
const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
|
event.path === keybindingsConfigPath ||
|
||||||
Stream.filter((event) => {
|
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
|
||||||
return (
|
if (!isTargetConfigEvent) {
|
||||||
event.path === keybindingsConfigFile ||
|
return Effect.void;
|
||||||
event.path === keybindingsConfigPath ||
|
}
|
||||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
|
return revalidateAndEmitSafely;
|
||||||
);
|
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||||
}),
|
|
||||||
Stream.debounce(Duration.millis(100)),
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
|
|
||||||
Effect.ignoreCause({ log: true }),
|
|
||||||
Effect.forkIn(watcherScope),
|
|
||||||
Effect.asVoid,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const start = Effect.gen(function* () {
|
const start = Effect.gen(function* () {
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import util from "node:util";
|
||||||
|
|
||||||
|
type LogLevel = "info" | "warn" | "error" | "event";
|
||||||
|
|
||||||
|
type LogContext = Record<string, unknown>;
|
||||||
|
|
||||||
|
const ANSI = {
|
||||||
|
reset: "\u001b[0m",
|
||||||
|
dim: "\u001b[2m",
|
||||||
|
cyan: "\u001b[36m",
|
||||||
|
yellow: "\u001b[33m",
|
||||||
|
red: "\u001b[31m",
|
||||||
|
magenta: "\u001b[35m",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||||
|
info: "INFO",
|
||||||
|
warn: "WARN",
|
||||||
|
error: "ERROR",
|
||||||
|
event: "EVENT",
|
||||||
|
};
|
||||||
|
|
||||||
|
const LEVEL_COLOR: Record<LogLevel, string> = {
|
||||||
|
info: ANSI.cyan,
|
||||||
|
warn: ANSI.yellow,
|
||||||
|
error: ANSI.red,
|
||||||
|
event: ANSI.magenta,
|
||||||
|
};
|
||||||
|
|
||||||
|
function useColors() {
|
||||||
|
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function colorize(value: string, color: string, enabled: boolean) {
|
||||||
|
return enabled ? `${color}${value}${ANSI.reset}` : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function timeStamp() {
|
||||||
|
return new Date().toISOString().slice(11, 23);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatValue(value: unknown) {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof value === "number" ||
|
||||||
|
typeof value === "boolean" ||
|
||||||
|
value === null ||
|
||||||
|
value === undefined
|
||||||
|
) {
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
return util.inspect(value, {
|
||||||
|
depth: 4,
|
||||||
|
breakLength: Infinity,
|
||||||
|
compact: true,
|
||||||
|
maxArrayLength: 25,
|
||||||
|
maxStringLength: 320,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatContext(context: LogContext | undefined) {
|
||||||
|
if (!context) return "";
|
||||||
|
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
|
||||||
|
if (entries.length === 0) return "";
|
||||||
|
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
|
||||||
|
const colorEnabled = useColors();
|
||||||
|
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
|
||||||
|
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
|
||||||
|
const contextText = formatContext(context);
|
||||||
|
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
|
||||||
|
|
||||||
|
if (level === "warn") {
|
||||||
|
console.warn(line);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (level === "error") {
|
||||||
|
console.error(line);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLogger(scope: string) {
|
||||||
|
return {
|
||||||
|
info(message: string, context?: LogContext) {
|
||||||
|
write("info", scope, message, context);
|
||||||
|
},
|
||||||
|
warn(message: string, context?: LogContext) {
|
||||||
|
write("warn", scope, message, context);
|
||||||
|
},
|
||||||
|
error(message: string, context?: LogContext) {
|
||||||
|
write("error", scope, message, context);
|
||||||
|
},
|
||||||
|
event(message: string, context?: LogContext) {
|
||||||
|
write("event", scope, message, context);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
import * as Http from "node:http";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { assert, it, vi } from "@effect/vitest";
|
||||||
|
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||||
|
import * as ConfigProvider from "effect/ConfigProvider";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Layer from "effect/Layer";
|
||||||
|
import * as Command from "effect/unstable/cli/Command";
|
||||||
|
import { FetchHttpClient } from "effect/unstable/http";
|
||||||
|
import { beforeEach } from "vitest";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
|
||||||
|
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||||
|
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||||
|
import { Open, type OpenShape } from "./open";
|
||||||
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||||
|
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||||
|
import { Server, type ServerShape } from "./wsServer";
|
||||||
|
|
||||||
|
const start = vi.fn(() => undefined);
|
||||||
|
const stop = vi.fn(() => undefined);
|
||||||
|
let resolvedConfig: ServerConfigShape | null = null;
|
||||||
|
const serverStart = Effect.acquireRelease(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
resolvedConfig = yield* ServerConfig;
|
||||||
|
start();
|
||||||
|
return {} as unknown as Http.Server;
|
||||||
|
}),
|
||||||
|
() => Effect.sync(() => stop()),
|
||||||
|
);
|
||||||
|
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
|
||||||
|
|
||||||
|
// Shared service layer used by this CLI test suite.
|
||||||
|
const testLayer = Layer.mergeAll(
|
||||||
|
Layer.succeed(CliConfig, {
|
||||||
|
cwd: "/tmp/t3-test-workspace",
|
||||||
|
fixPath: Effect.void,
|
||||||
|
resolveStaticDir: Effect.undefined,
|
||||||
|
} satisfies CliConfigShape),
|
||||||
|
Layer.succeed(NetService, {
|
||||||
|
canListenOnHost: () => Effect.succeed(true),
|
||||||
|
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||||
|
reserveLoopbackPort: () => Effect.succeed(0),
|
||||||
|
findAvailablePort,
|
||||||
|
}),
|
||||||
|
Layer.succeed(Server, {
|
||||||
|
start: serverStart,
|
||||||
|
stopSignal: Effect.void,
|
||||||
|
} satisfies ServerShape),
|
||||||
|
Layer.succeed(Open, {
|
||||||
|
openBrowser: (_target: string) => Effect.void,
|
||||||
|
openInEditor: () => Effect.void,
|
||||||
|
} satisfies OpenShape),
|
||||||
|
AnalyticsService.layerTest,
|
||||||
|
FetchHttpClient.layer,
|
||||||
|
NodeServices.layer,
|
||||||
|
);
|
||||||
|
|
||||||
|
const runCli = (
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||||
|
) => {
|
||||||
|
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_STATE_DIR: uniqueStateDir,
|
||||||
|
...env,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
resolvedConfig = null;
|
||||||
|
start.mockImplementation(() => undefined);
|
||||||
|
stop.mockImplementation(() => undefined);
|
||||||
|
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||||
|
});
|
||||||
|
|
||||||
|
it.layer(testLayer)("server CLI command", (it) => {
|
||||||
|
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli([
|
||||||
|
"--mode",
|
||||||
|
"desktop",
|
||||||
|
"--port",
|
||||||
|
"4010",
|
||||||
|
"--host",
|
||||||
|
"0.0.0.0",
|
||||||
|
"--state-dir",
|
||||||
|
"/tmp/t3-cli-state",
|
||||||
|
"--dev-url",
|
||||||
|
"http://127.0.0.1:5173",
|
||||||
|
"--no-browser",
|
||||||
|
"--auth-token",
|
||||||
|
"auth-secret",
|
||||||
|
"--allowed-hosts",
|
||||||
|
"app.example, ADMIN.example:8443",
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.mode, "desktop");
|
||||||
|
assert.equal(resolvedConfig?.port, 4010);
|
||||||
|
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||||
|
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
|
||||||
|
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||||
|
assert.equal(resolvedConfig?.noBrowser, true);
|
||||||
|
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||||
|
assert.deepEqual(resolvedConfig?.allowedHosts, ["app.example", "admin.example:8443"]);
|
||||||
|
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||||
|
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||||
|
assert.equal(stop.mock.calls.length, 1);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("supports --token as an alias for --auth-token", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--token", "token-secret"]);
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.authToken, "token-secret");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses env fallbacks when flags are not provided", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli([], {
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_PORT: "4999",
|
||||||
|
T3CODE_HOST: "100.88.10.4",
|
||||||
|
T3CODE_STATE_DIR: "/tmp/t3-env-state",
|
||||||
|
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
T3CODE_AUTH_TOKEN: "env-token",
|
||||||
|
T3CODE_ALLOWED_HOSTS: "app.example, admin.example:8443",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.mode, "desktop");
|
||||||
|
assert.equal(resolvedConfig?.port, 4999);
|
||||||
|
assert.equal(resolvedConfig?.host, "100.88.10.4");
|
||||||
|
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
|
||||||
|
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||||
|
assert.equal(resolvedConfig?.noBrowser, true);
|
||||||
|
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||||
|
assert.deepEqual(resolvedConfig?.allowedHosts, ["app.example", "admin.example:8443"]);
|
||||||
|
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||||
|
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||||
|
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||||
|
yield* runCli(["--mode", "web"], {
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.mode, "web");
|
||||||
|
assert.equal(resolvedConfig?.port, 4666);
|
||||||
|
assert.equal(resolvedConfig?.host, undefined);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--no-browser"], {
|
||||||
|
T3CODE_NO_BROWSER: "false",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.noBrowser, true);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
|
||||||
|
yield* runCli([]);
|
||||||
|
|
||||||
|
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.port, 5444);
|
||||||
|
assert.equal(resolvedConfig?.mode, "web");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses fixed localhost defaults in desktop mode", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli([], {
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.port, 3773);
|
||||||
|
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||||
|
assert.equal(resolvedConfig?.mode, "desktop");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("allows overriding desktop host with --host", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--host", "0.0.0.0"], {
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.mode, "desktop");
|
||||||
|
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--auto-bootstrap-project-from-cwd"], {
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_LOG_WS_EVENTS: "false",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||||
|
assert.equal(resolvedConfig?.logWebSocketEvents, false);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("prefers --allowed-hosts over T3CODE_ALLOWED_HOSTS", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--allowed-hosts", "cli.example:4321"], {
|
||||||
|
T3CODE_ALLOWED_HOSTS: "env.example",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 1);
|
||||||
|
assert.deepEqual(resolvedConfig?.allowedHosts, ["cli.example:4321"]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const recordTelemetry = vi.fn(
|
||||||
|
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
|
||||||
|
);
|
||||||
|
const getSnapshot = vi.fn(() =>
|
||||||
|
Effect.succeed({
|
||||||
|
snapshotSequence: 2,
|
||||||
|
projects: [{} as OrchestrationReadModel["projects"][number]],
|
||||||
|
threads: [
|
||||||
|
{} as OrchestrationReadModel["threads"][number],
|
||||||
|
{} as OrchestrationReadModel["threads"][number],
|
||||||
|
],
|
||||||
|
updatedAt: new Date(1).toISOString(),
|
||||||
|
} satisfies OrchestrationReadModel),
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* recordStartupHeartbeat.pipe(
|
||||||
|
Effect.provideService(ProjectionSnapshotQuery, {
|
||||||
|
getSnapshot,
|
||||||
|
}),
|
||||||
|
Effect.provideService(AnalyticsService, {
|
||||||
|
record: recordTelemetry,
|
||||||
|
flush: Effect.void,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(recordTelemetry.mock.calls[0], [
|
||||||
|
"server.boot.heartbeat",
|
||||||
|
{
|
||||||
|
threadCount: 2,
|
||||||
|
projectCount: 1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("does not start server for invalid --mode values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--mode", "invalid"]);
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 0);
|
||||||
|
assert.equal(stop.mock.calls.length, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("does not start server for invalid --dev-url values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 0);
|
||||||
|
assert.equal(stop.mock.calls.length, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("does not start server for invalid --allowed-hosts values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--allowed-hosts", "https://app.example/path"]).pipe(
|
||||||
|
Effect.catch(() => Effect.void),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(start.mock.calls.length, 0);
|
||||||
|
assert.equal(stop.mock.calls.length, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("does not start server for out-of-range --port values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* runCli(["--port", "70000"]);
|
||||||
|
|
||||||
|
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||||
|
assert.equal(start.mock.calls.length, 0);
|
||||||
|
assert.equal(stop.mock.calls.length, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
/**
|
||||||
|
* CliConfig - CLI/runtime bootstrap service definitions.
|
||||||
|
*
|
||||||
|
* Defines startup-only service contracts used while resolving process config
|
||||||
|
* and constructing server runtime layers.
|
||||||
|
*
|
||||||
|
* @module CliConfig
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
Config,
|
||||||
|
Data,
|
||||||
|
Effect,
|
||||||
|
FileSystem,
|
||||||
|
Layer,
|
||||||
|
Option,
|
||||||
|
Path,
|
||||||
|
Schema,
|
||||||
|
SchemaIssue,
|
||||||
|
SchemaTransformation,
|
||||||
|
ServiceMap,
|
||||||
|
} from "effect";
|
||||||
|
import { Command, Flag } from "effect/unstable/cli";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
import {
|
||||||
|
DEFAULT_PORT,
|
||||||
|
resolveStaticDir,
|
||||||
|
ServerConfig,
|
||||||
|
type RuntimeMode,
|
||||||
|
type ServerConfigShape,
|
||||||
|
} from "./config";
|
||||||
|
import { fixPath, resolveStateDir } from "./os-jank";
|
||||||
|
import { Open } from "./open";
|
||||||
|
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||||
|
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||||
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||||
|
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||||
|
import { Server } from "./wsServer";
|
||||||
|
import { ServerLoggerLive } from "./serverLogger";
|
||||||
|
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||||
|
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||||
|
|
||||||
|
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||||
|
readonly message: string;
|
||||||
|
readonly cause?: unknown;
|
||||||
|
}> {}
|
||||||
|
|
||||||
|
const invalidAllowedHostIssue = (input: string) =>
|
||||||
|
new SchemaIssue.InvalidValue(Option.some(input), {
|
||||||
|
message: `Invalid host "${input}". Expected bare host[:port], for example "app.example" or "app.example:443".`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const AllowedHost = Schema.Trim.pipe(
|
||||||
|
Schema.check(
|
||||||
|
Schema.makeFilter(
|
||||||
|
(input) => {
|
||||||
|
if (input.length === 0 || input.includes("://")) {
|
||||||
|
return invalidAllowedHostIssue(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidateUrl = `http://${input}`;
|
||||||
|
if (!URL.canParse(candidateUrl)) {
|
||||||
|
return invalidAllowedHostIssue(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = new URL(candidateUrl);
|
||||||
|
return parsed.username ||
|
||||||
|
parsed.password ||
|
||||||
|
parsed.pathname !== "/" ||
|
||||||
|
parsed.search ||
|
||||||
|
parsed.hash
|
||||||
|
? invalidAllowedHostIssue(input)
|
||||||
|
: true;
|
||||||
|
},
|
||||||
|
{ identifier: "AllowedHost" },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase()),
|
||||||
|
);
|
||||||
|
|
||||||
|
const AllowedHostsCsv = Schema.String.pipe(
|
||||||
|
Schema.decodeTo(
|
||||||
|
Schema.Array(AllowedHost),
|
||||||
|
SchemaTransformation.transform({
|
||||||
|
decode: (input): readonly string[] =>
|
||||||
|
Array.from(
|
||||||
|
new Set(
|
||||||
|
input
|
||||||
|
.split(",")
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.filter((entry) => entry.length > 0),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
encode: (input: readonly string[]) => input.join(", "),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
interface CliInput {
|
||||||
|
readonly mode: Option.Option<RuntimeMode>;
|
||||||
|
readonly port: Option.Option<number>;
|
||||||
|
readonly host: Option.Option<string>;
|
||||||
|
readonly stateDir: Option.Option<string>;
|
||||||
|
readonly devUrl: Option.Option<URL>;
|
||||||
|
readonly noBrowser: Option.Option<boolean>;
|
||||||
|
readonly authToken: Option.Option<string>;
|
||||||
|
readonly allowedHosts: Option.Option<readonly string[]>;
|
||||||
|
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||||
|
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CliConfigShape - Startup helpers required while building server layers.
|
||||||
|
*/
|
||||||
|
export interface CliConfigShape {
|
||||||
|
/**
|
||||||
|
* Current process working directory.
|
||||||
|
*/
|
||||||
|
readonly cwd: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply OS-specific PATH normalization.
|
||||||
|
*/
|
||||||
|
readonly fixPath: Effect.Effect<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve static web asset directory for server mode.
|
||||||
|
*/
|
||||||
|
readonly resolveStaticDir: Effect.Effect<string | undefined>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CliConfig - Service tag for startup CLI/runtime helpers.
|
||||||
|
*/
|
||||||
|
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||||
|
"t3/main/CliConfig",
|
||||||
|
) {
|
||||||
|
static readonly layer = Layer.effect(
|
||||||
|
CliConfig,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
return {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
fixPath: Effect.sync(fixPath),
|
||||||
|
resolveStaticDir: resolveStaticDir().pipe(
|
||||||
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
),
|
||||||
|
} satisfies CliConfigShape;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const CliEnvConfig = Config.all({
|
||||||
|
mode: Config.string("T3CODE_MODE").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(
|
||||||
|
Option.match<RuntimeMode, string>({
|
||||||
|
onNone: () => "web",
|
||||||
|
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||||
|
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||||
|
stateDir: Config.string("T3CODE_STATE_DIR").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||||
|
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
allowedHosts: Config.schema(AllowedHostsCsv, "T3CODE_ALLOWED_HOSTS").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||||
|
Config.option,
|
||||||
|
Config.map(Option.getOrUndefined),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||||
|
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||||
|
|
||||||
|
const ServerConfigLive = (input: CliInput) =>
|
||||||
|
Layer.effect(
|
||||||
|
ServerConfig,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const cliConfig = yield* CliConfig;
|
||||||
|
const { findAvailablePort } = yield* NetService;
|
||||||
|
const env = yield* CliEnvConfig.asEffect().pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new StartupError({ message: "Failed to read environment configuration", cause }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||||
|
|
||||||
|
const port = yield* Option.match(input.port, {
|
||||||
|
onSome: (value) => Effect.succeed(value),
|
||||||
|
onNone: () => {
|
||||||
|
if (env.port) {
|
||||||
|
return Effect.succeed(env.port);
|
||||||
|
}
|
||||||
|
if (mode === "desktop") {
|
||||||
|
return Effect.succeed(DEFAULT_PORT);
|
||||||
|
}
|
||||||
|
return findAvailablePort(DEFAULT_PORT);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const stateDir = yield* resolveStateDir(
|
||||||
|
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||||
|
);
|
||||||
|
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||||
|
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||||
|
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||||
|
const allowedHosts = Option.getOrUndefined(input.allowedHosts) ?? env.allowedHosts ?? [];
|
||||||
|
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||||
|
input.autoBootstrapProjectFromCwd,
|
||||||
|
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||||
|
);
|
||||||
|
const logWebSocketEvents = resolveBooleanFlag(
|
||||||
|
input.logWebSocketEvents,
|
||||||
|
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||||
|
);
|
||||||
|
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||||
|
const host =
|
||||||
|
Option.getOrUndefined(input.host) ??
|
||||||
|
env.host ??
|
||||||
|
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||||
|
|
||||||
|
const config: ServerConfigShape = {
|
||||||
|
mode,
|
||||||
|
port,
|
||||||
|
cwd: cliConfig.cwd,
|
||||||
|
keybindingsConfigPath,
|
||||||
|
host,
|
||||||
|
stateDir,
|
||||||
|
staticDir,
|
||||||
|
devUrl,
|
||||||
|
noBrowser,
|
||||||
|
authToken,
|
||||||
|
allowedHosts,
|
||||||
|
autoBootstrapProjectFromCwd,
|
||||||
|
logWebSocketEvents,
|
||||||
|
} satisfies ServerConfigShape;
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const LayerLive = (input: CliInput) =>
|
||||||
|
Layer.empty.pipe(
|
||||||
|
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||||
|
Layer.provideMerge(makeServerProviderLayer()),
|
||||||
|
Layer.provideMerge(ProviderHealthLive),
|
||||||
|
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||||
|
Layer.provideMerge(ServerLoggerLive),
|
||||||
|
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||||
|
Layer.provideMerge(ServerConfigLive(input)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const isWildcardHost = (host: string | undefined): boolean =>
|
||||||
|
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||||
|
|
||||||
|
const formatHostForUrl = (host: string): string =>
|
||||||
|
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||||
|
|
||||||
|
export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||||
|
const analytics = yield* AnalyticsService;
|
||||||
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
|
|
||||||
|
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||||
|
Effect.map((snapshot) => ({
|
||||||
|
threadCount: snapshot.threads.length,
|
||||||
|
projectCount: snapshot.projects.length,
|
||||||
|
})),
|
||||||
|
Effect.catch((cause) =>
|
||||||
|
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||||
|
Effect.as({
|
||||||
|
threadCount: 0,
|
||||||
|
projectCount: 0,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* analytics.record("server.boot.heartbeat", {
|
||||||
|
threadCount,
|
||||||
|
projectCount,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeServerProgram = (input: CliInput) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const cliConfig = yield* CliConfig;
|
||||||
|
const { start, stopSignal } = yield* Server;
|
||||||
|
const openDeps = yield* Open;
|
||||||
|
yield* cliConfig.fixPath;
|
||||||
|
|
||||||
|
const config = yield* ServerConfig;
|
||||||
|
|
||||||
|
if (!config.devUrl && !config.staticDir) {
|
||||||
|
yield* Effect.logWarning(
|
||||||
|
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||||
|
{
|
||||||
|
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* start;
|
||||||
|
yield* Effect.forkChild(recordStartupHeartbeat);
|
||||||
|
|
||||||
|
const localUrl = `http://localhost:${config.port}`;
|
||||||
|
const bindUrl =
|
||||||
|
config.host && !isWildcardHost(config.host)
|
||||||
|
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||||
|
: localUrl;
|
||||||
|
const { authToken, devUrl, ...safeConfig } = config;
|
||||||
|
yield* Effect.logInfo("T3 Code running", {
|
||||||
|
...safeConfig,
|
||||||
|
devUrl: devUrl?.toString(),
|
||||||
|
authEnabled: Boolean(authToken),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!config.noBrowser) {
|
||||||
|
const target = config.devUrl?.toString() ?? bindUrl;
|
||||||
|
yield* openDeps.openBrowser(target).pipe(
|
||||||
|
Effect.catch(() =>
|
||||||
|
Effect.logInfo("browser auto-open unavailable", {
|
||||||
|
hint: `Open ${target} in your browser.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return yield* stopSignal;
|
||||||
|
}).pipe(Effect.provide(LayerLive(input)));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* These flags mirrors the environment variables and the config shape.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||||
|
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const portFlag = Flag.integer("port").pipe(
|
||||||
|
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||||
|
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const hostFlag = Flag.string("host").pipe(
|
||||||
|
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const stateDirFlag = Flag.string("state-dir").pipe(
|
||||||
|
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||||
|
Flag.withSchema(Schema.URLFromString),
|
||||||
|
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||||
|
Flag.withDescription("Disable automatic browser opening."),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||||
|
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||||
|
Flag.withAlias("token"),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const allowedHostsFlag = Flag.string("allowed-hosts").pipe(
|
||||||
|
Flag.withSchema(AllowedHostsCsv),
|
||||||
|
Flag.withDescription(
|
||||||
|
"Comma-separated host[:port] values allowed for inbound HTTP and WebSocket traffic (equivalent to T3CODE_ALLOWED_HOSTS).",
|
||||||
|
),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||||
|
Flag.withDescription(
|
||||||
|
"Create a project for the current working directory on startup when missing.",
|
||||||
|
),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||||
|
Flag.withDescription(
|
||||||
|
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||||
|
),
|
||||||
|
Flag.withAlias("log-ws-events"),
|
||||||
|
Flag.optional,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const t3Cli = Command.make("t3", {
|
||||||
|
mode: modeFlag,
|
||||||
|
port: portFlag,
|
||||||
|
host: hostFlag,
|
||||||
|
stateDir: stateDirFlag,
|
||||||
|
devUrl: devUrlFlag,
|
||||||
|
noBrowser: noBrowserFlag,
|
||||||
|
authToken: authTokenFlag,
|
||||||
|
allowedHosts: allowedHostsFlag,
|
||||||
|
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||||
|
logWebSocketEvents: logWebSocketEventsFlag,
|
||||||
|
}).pipe(
|
||||||
|
Command.withDescription("Run the T3 Code server."),
|
||||||
|
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
|
||||||
|
);
|
||||||
@@ -31,15 +31,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
|||||||
args: ["/tmp/workspace"],
|
args: ["/tmp/workspace"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const traeLaunch = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace", editor: "trae" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(traeLaunch, {
|
|
||||||
command: "trae",
|
|
||||||
args: ["/tmp/workspace"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||||
"darwin",
|
"darwin",
|
||||||
@@ -49,24 +40,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
|||||||
args: ["/tmp/workspace"],
|
args: ["/tmp/workspace"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(vscodeInsidersLaunch, {
|
|
||||||
command: "code-insiders",
|
|
||||||
args: ["/tmp/workspace"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(vscodiumLaunch, {
|
|
||||||
command: "codium",
|
|
||||||
args: ["/tmp/workspace"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const zedLaunch = yield* resolveEditorLaunch(
|
const zedLaunch = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||||
"darwin",
|
"darwin",
|
||||||
@@ -98,15 +71,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
|||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const traeLineAndColumn = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(traeLineAndColumn, {
|
|
||||||
command: "trae",
|
|
||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||||
"darwin",
|
"darwin",
|
||||||
@@ -116,24 +80,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
|||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
|
||||||
command: "code-insiders",
|
|
||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
|
||||||
"darwin",
|
|
||||||
);
|
|
||||||
assert.deepEqual(vscodiumLineAndColumn, {
|
|
||||||
command: "codium",
|
|
||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||||
"darwin",
|
"darwin",
|
||||||
@@ -274,15 +220,13 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
|||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||||
|
|
||||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
|
||||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
|
||||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
|
||||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||||
const editors = resolveAvailableEditors("win32", {
|
const editors = resolveAvailableEditors("win32", {
|
||||||
PATH: dir,
|
PATH: dir,
|
||||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
});
|
});
|
||||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
+11
-6
@@ -10,14 +10,17 @@ import { spawn } from "node:child_process";
|
|||||||
import { accessSync, constants, statSync } from "node:fs";
|
import { accessSync, constants, statSync } from "node:fs";
|
||||||
import { extname, join } from "node:path";
|
import { extname, join } from "node:path";
|
||||||
|
|
||||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||||
import { ServiceMap, Effect, Layer } from "effect";
|
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||||
|
|
||||||
// ==============================
|
// ==============================
|
||||||
// Definitions
|
// Definitions
|
||||||
// ==============================
|
// ==============================
|
||||||
|
|
||||||
export { OpenError };
|
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||||
|
message: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {}
|
||||||
|
|
||||||
export interface OpenInEditorInput {
|
export interface OpenInEditorInput {
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
@@ -36,8 +39,10 @@ interface CommandAvailabilityOptions {
|
|||||||
|
|
||||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||||
|
|
||||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
return (
|
||||||
|
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||||
@@ -208,7 +213,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (editorDef.command) {
|
if (editorDef.command) {
|
||||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||||
: { command: editorDef.command, args: [input.cwd] };
|
: { command: editorDef.command, args: [input.cwd] };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
|
|
||||||
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -19,7 +19,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
|
||||||
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
||||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||||
@@ -38,8 +37,6 @@ import {
|
|||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
|
||||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||||
@@ -47,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
|||||||
type LegacyProviderRuntimeEvent = {
|
type LegacyProviderRuntimeEvent = {
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
readonly eventId: EventId;
|
readonly eventId: EventId;
|
||||||
readonly provider: ProviderKind;
|
readonly provider: "codex";
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly turnId?: string | undefined;
|
readonly turnId?: string | undefined;
|
||||||
@@ -116,7 +113,7 @@ async function waitForThread(
|
|||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}) => boolean,
|
}) => boolean,
|
||||||
timeoutMs = 15_000,
|
timeoutMs = 5000,
|
||||||
) {
|
) {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
const poll = async (): Promise<{
|
const poll = async (): Promise<{
|
||||||
@@ -141,7 +138,7 @@ async function waitForThread(
|
|||||||
async function waitForEvent(
|
async function waitForEvent(
|
||||||
engine: OrchestrationEngineShape,
|
engine: OrchestrationEngineShape,
|
||||||
predicate: (event: { type: string }) => boolean,
|
predicate: (event: { type: string }) => boolean,
|
||||||
timeoutMs = 15_000,
|
timeoutMs = 5000,
|
||||||
) {
|
) {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
const poll = async () => {
|
const poll = async () => {
|
||||||
@@ -192,7 +189,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
|||||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
|
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
const poll = async (): Promise<void> => {
|
const poll = async (): Promise<void> => {
|
||||||
if (gitRefExists(cwd, ref)) {
|
if (gitRefExists(cwd, ref)) {
|
||||||
@@ -238,7 +235,6 @@ describe("CheckpointReactor", () => {
|
|||||||
readonly projectWorkspaceRoot?: string;
|
readonly projectWorkspaceRoot?: string;
|
||||||
readonly threadWorktreePath?: string | null;
|
readonly threadWorktreePath?: string | null;
|
||||||
readonly providerSessionCwd?: string;
|
readonly providerSessionCwd?: string;
|
||||||
readonly providerName?: ProviderKind;
|
|
||||||
}) {
|
}) {
|
||||||
const cwd = createGitRepository();
|
const cwd = createGitRepository();
|
||||||
tempDirs.push(cwd);
|
tempDirs.push(cwd);
|
||||||
@@ -246,7 +242,7 @@ describe("CheckpointReactor", () => {
|
|||||||
cwd,
|
cwd,
|
||||||
options?.hasSession ?? true,
|
options?.hasSession ?? true,
|
||||||
options?.providerSessionCwd ?? cwd,
|
options?.providerSessionCwd ?? cwd,
|
||||||
options?.providerName ?? "codex",
|
"codex",
|
||||||
);
|
);
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
@@ -255,19 +251,12 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-checkpoint-reactor-test-",
|
|
||||||
});
|
|
||||||
|
|
||||||
const layer = CheckpointReactorLive.pipe(
|
const layer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(CheckpointStoreLive),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(WorkspacePathsLive),
|
|
||||||
Layer.provideMerge(GitCoreLive),
|
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -276,7 +265,7 @@ describe("CheckpointReactor", () => {
|
|||||||
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
||||||
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||||
const drain = () => Effect.runPromise(reactor.drain);
|
const drain = () => Effect.runPromise(reactor.drain);
|
||||||
|
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
@@ -287,10 +276,7 @@ describe("CheckpointReactor", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Test Project",
|
title: "Test Project",
|
||||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -301,10 +287,7 @@ describe("CheckpointReactor", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -494,67 +477,6 @@ describe("CheckpointReactor", () => {
|
|||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
seedFilesystemCheckpoints: false,
|
|
||||||
providerName: "claudeAgent",
|
|
||||||
});
|
|
||||||
const createdAt = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
status: "ready",
|
|
||||||
providerName: "claudeAgent",
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: createdAt,
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
harness.provider.emit({
|
|
||||||
type: "turn.started",
|
|
||||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
|
||||||
provider: "claudeAgent",
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
turnId: asTurnId("turn-claude-1"),
|
|
||||||
});
|
|
||||||
await waitForGitRefExists(
|
|
||||||
harness.cwd,
|
|
||||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
|
||||||
);
|
|
||||||
|
|
||||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
|
||||||
harness.provider.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
|
||||||
provider: "claudeAgent",
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
turnId: asTurnId("turn-claude-1"),
|
|
||||||
payload: { state: "completed" },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
|
||||||
const thread = await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
|
||||||
expect(
|
|
||||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
@@ -870,75 +792,6 @@ describe("CheckpointReactor", () => {
|
|||||||
).toBe(false);
|
).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
|
||||||
const harness = await createHarness({ providerName: "claudeAgent" });
|
|
||||||
const createdAt = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
status: "ready",
|
|
||||||
providerName: "claudeAgent",
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: createdAt,
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.diff.complete",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
turnId: asTurnId("turn-claude-1"),
|
|
||||||
completedAt: createdAt,
|
|
||||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
|
||||||
status: "ready",
|
|
||||||
files: [],
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.diff.complete",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
turnId: asTurnId("turn-claude-2"),
|
|
||||||
completedAt: createdAt,
|
|
||||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
|
||||||
status: "ready",
|
|
||||||
files: [],
|
|
||||||
checkpointTurnCount: 2,
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.checkpoint.revert",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
turnCount: 1,
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
|
||||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
|
||||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
numTurns: 1,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
@@ -1009,7 +862,18 @@ describe("CheckpointReactor", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await harness.drain();
|
const deadline = Date.now() + 2000;
|
||||||
|
const waitForRollbackCalls = async (): Promise<void> => {
|
||||||
|
if (harness.provider.rollbackConversation.mock.calls.length >= 2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Date.now() >= deadline) {
|
||||||
|
throw new Error("Timed out waiting for rollbackConversation calls.");
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
return waitForRollbackCalls();
|
||||||
|
};
|
||||||
|
await waitForRollbackCalls();
|
||||||
|
|
||||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
checkpointRefForThreadTurn,
|
checkpointRefForThreadTurn,
|
||||||
resolveThreadWorkspaceCwd,
|
resolveThreadWorkspaceCwd,
|
||||||
} from "../../checkpointing/Utils.ts";
|
} from "../../checkpointing/Utils.ts";
|
||||||
|
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
|
||||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||||
@@ -23,8 +24,7 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
|||||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||||
import { isGitRepository } from "../../git/Utils.ts";
|
import { isGitRepository } from "../../git/isRepo.ts";
|
||||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
|
||||||
|
|
||||||
type ReactorInput =
|
type ReactorInput =
|
||||||
| {
|
| {
|
||||||
@@ -68,7 +68,6 @@ const make = Effect.gen(function* () {
|
|||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const checkpointStore = yield* CheckpointStore;
|
const checkpointStore = yield* CheckpointStore;
|
||||||
const receiptBus = yield* RuntimeReceiptBus;
|
const receiptBus = yield* RuntimeReceiptBus;
|
||||||
const workspaceEntries = yield* WorkspaceEntries;
|
|
||||||
|
|
||||||
const appendRevertFailureActivity = (input: {
|
const appendRevertFailureActivity = (input: {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
@@ -227,7 +226,7 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
// Invalidate the workspace entry cache so the @-mention file picker
|
// Invalidate the workspace entry cache so the @-mention file picker
|
||||||
// reflects files created or deleted during this turn.
|
// reflects files created or deleted during this turn.
|
||||||
yield* workspaceEntries.invalidate(input.cwd);
|
clearWorkspaceIndexCache(input.cwd);
|
||||||
|
|
||||||
const files = yield* checkpointStore
|
const files = yield* checkpointStore
|
||||||
.diffCheckpoints({
|
.diffCheckpoints({
|
||||||
@@ -643,7 +642,7 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
// Invalidate the workspace entry cache so the @-mention file picker
|
// Invalidate the workspace entry cache so the @-mention file picker
|
||||||
// reflects the reverted filesystem state.
|
// reflects the reverted filesystem state.
|
||||||
yield* workspaceEntries.invalidate(sessionRuntime.value.cwd);
|
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
|
||||||
|
|
||||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||||
if (rolledBackTurns > 0) {
|
if (rolledBackTurns > 0) {
|
||||||
@@ -767,7 +766,7 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
const worker = yield* makeDrainableWorker(processInputSafely);
|
const worker = yield* makeDrainableWorker(processInputSafely);
|
||||||
|
|
||||||
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
|
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
|
||||||
yield* Effect.forkScoped(
|
yield* Effect.forkScoped(
|
||||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -35,15 +35,12 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
|||||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||||
|
|
||||||
async function createOrchestrationSystem() {
|
async function createOrchestrationSystem() {
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-orchestration-engine-test-",
|
|
||||||
});
|
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||||
@@ -72,10 +69,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Project 1",
|
title: "Project 1",
|
||||||
workspaceRoot: "/tmp/project-1",
|
workspaceRoot: "/tmp/project-1",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -86,10 +80,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -120,73 +111,6 @@ describe("OrchestrationEngine", () => {
|
|||||||
await system.dispose();
|
await system.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("archives and unarchives threads through orchestration commands", async () => {
|
|
||||||
const system = await createOrchestrationSystem();
|
|
||||||
const { engine } = system;
|
|
||||||
const createdAt = now();
|
|
||||||
|
|
||||||
await system.run(
|
|
||||||
engine.dispatch({
|
|
||||||
type: "project.create",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
|
|
||||||
projectId: asProjectId("project-archive"),
|
|
||||||
title: "Project Archive",
|
|
||||||
workspaceRoot: "/tmp/project-archive",
|
|
||||||
defaultModelSelection: {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await system.run(
|
|
||||||
engine.dispatch({
|
|
||||||
type: "thread.create",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
|
||||||
projectId: asProjectId("project-archive"),
|
|
||||||
title: "Archive me",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
branch: null,
|
|
||||||
worktreePath: null,
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await system.run(
|
|
||||||
engine.dispatch({
|
|
||||||
type: "thread.archive",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
(await system.run(engine.getReadModel())).threads.find(
|
|
||||||
(thread) => thread.id === "thread-archive",
|
|
||||||
)?.archivedAt,
|
|
||||||
).not.toBeNull();
|
|
||||||
|
|
||||||
await system.run(
|
|
||||||
engine.dispatch({
|
|
||||||
type: "thread.unarchive",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
(await system.run(engine.getReadModel())).threads.find(
|
|
||||||
(thread) => thread.id === "thread-archive",
|
|
||||||
)?.archivedAt,
|
|
||||||
).toBeNull();
|
|
||||||
|
|
||||||
await system.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("replays append-only events from sequence", async () => {
|
it("replays append-only events from sequence", async () => {
|
||||||
const system = await createOrchestrationSystem();
|
const system = await createOrchestrationSystem();
|
||||||
const { engine } = system;
|
const { engine } = system;
|
||||||
@@ -199,10 +123,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-replay"),
|
projectId: asProjectId("project-replay"),
|
||||||
title: "Replay Project",
|
title: "Replay Project",
|
||||||
workspaceRoot: "/tmp/project-replay",
|
workspaceRoot: "/tmp/project-replay",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -213,10 +134,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||||
projectId: asProjectId("project-replay"),
|
projectId: asProjectId("project-replay"),
|
||||||
title: "replay",
|
title: "replay",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -257,10 +175,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-stream"),
|
projectId: asProjectId("project-stream"),
|
||||||
title: "Stream Project",
|
title: "Stream Project",
|
||||||
workspaceRoot: "/tmp/project-stream",
|
workspaceRoot: "/tmp/project-stream",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -281,10 +196,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||||
projectId: asProjectId("project-stream"),
|
projectId: asProjectId("project-stream"),
|
||||||
title: "domain-stream",
|
title: "domain-stream",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -318,10 +230,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-turn-diff"),
|
projectId: asProjectId("project-turn-diff"),
|
||||||
title: "Turn Diff Project",
|
title: "Turn Diff Project",
|
||||||
workspaceRoot: "/tmp/project-turn-diff",
|
workspaceRoot: "/tmp/project-turn-diff",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -332,10 +241,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||||
projectId: asProjectId("project-turn-diff"),
|
projectId: asProjectId("project-turn-diff"),
|
||||||
title: "Turn diff thread",
|
title: "Turn diff thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -411,17 +317,13 @@ describe("OrchestrationEngine", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-orchestration-engine-test-",
|
|
||||||
});
|
|
||||||
|
|
||||||
const runtime = ManagedRuntime.make(
|
const runtime = ManagedRuntime.make(
|
||||||
OrchestrationEngineLive.pipe(
|
OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -435,10 +337,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-flaky"),
|
projectId: asProjectId("project-flaky"),
|
||||||
title: "Flaky Project",
|
title: "Flaky Project",
|
||||||
workspaceRoot: "/tmp/project-flaky",
|
workspaceRoot: "/tmp/project-flaky",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -451,10 +350,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||||
projectId: asProjectId("project-flaky"),
|
projectId: asProjectId("project-flaky"),
|
||||||
title: "flaky-fail",
|
title: "flaky-fail",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -471,10 +367,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||||
projectId: asProjectId("project-flaky"),
|
projectId: asProjectId("project-flaky"),
|
||||||
title: "flaky-ok",
|
title: "flaky-ok",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -528,10 +421,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-atomic"),
|
projectId: asProjectId("project-atomic"),
|
||||||
title: "Atomic Project",
|
title: "Atomic Project",
|
||||||
workspaceRoot: "/tmp/project-atomic",
|
workspaceRoot: "/tmp/project-atomic",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -542,10 +432,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||||
projectId: asProjectId("project-atomic"),
|
projectId: asProjectId("project-atomic"),
|
||||||
title: "atomic",
|
title: "atomic",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -669,10 +556,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-sync"),
|
projectId: asProjectId("project-sync"),
|
||||||
title: "Sync Project",
|
title: "Sync Project",
|
||||||
workspaceRoot: "/tmp/project-sync",
|
workspaceRoot: "/tmp/project-sync",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -683,10 +567,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||||
projectId: asProjectId("project-sync"),
|
projectId: asProjectId("project-sync"),
|
||||||
title: "sync-before",
|
title: "sync-before",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -754,10 +635,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-duplicate"),
|
projectId: asProjectId("project-duplicate"),
|
||||||
title: "Duplicate Project",
|
title: "Duplicate Project",
|
||||||
workspaceRoot: "/tmp/project-duplicate",
|
workspaceRoot: "/tmp/project-duplicate",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -769,10 +647,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||||
projectId: asProjectId("project-duplicate"),
|
projectId: asProjectId("project-duplicate"),
|
||||||
title: "duplicate",
|
title: "duplicate",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -789,10 +664,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||||
projectId: asProjectId("project-duplicate"),
|
projectId: asProjectId("project-duplicate"),
|
||||||
title: "duplicate",
|
title: "duplicate",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
|
|
||||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||||
yield* Effect.forkScoped(worker);
|
yield* Effect.forkScoped(worker);
|
||||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
yield* Effect.log("orchestration engine started").pipe(
|
||||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -24,28 +24,25 @@ describe("OrchestrationReactor", () => {
|
|||||||
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProviderRuntimeIngestionService, {
|
Layer.succeed(ProviderRuntimeIngestionService, {
|
||||||
start: () => {
|
start: Effect.sync(() => {
|
||||||
started.push("provider-runtime-ingestion");
|
started.push("provider-runtime-ingestion");
|
||||||
return Effect.void;
|
}),
|
||||||
},
|
|
||||||
drain: Effect.void,
|
drain: Effect.void,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProviderCommandReactor, {
|
Layer.succeed(ProviderCommandReactor, {
|
||||||
start: () => {
|
start: Effect.sync(() => {
|
||||||
started.push("provider-command-reactor");
|
started.push("provider-command-reactor");
|
||||||
return Effect.void;
|
}),
|
||||||
},
|
|
||||||
drain: Effect.void,
|
drain: Effect.void,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(CheckpointReactor, {
|
Layer.succeed(CheckpointReactor, {
|
||||||
start: () => {
|
start: Effect.sync(() => {
|
||||||
started.push("checkpoint-reactor");
|
started.push("checkpoint-reactor");
|
||||||
return Effect.void;
|
}),
|
||||||
},
|
|
||||||
drain: Effect.void,
|
drain: Effect.void,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -54,7 +51,7 @@ describe("OrchestrationReactor", () => {
|
|||||||
|
|
||||||
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
||||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||||
|
|
||||||
expect(started).toEqual([
|
expect(started).toEqual([
|
||||||
"provider-runtime-ingestion",
|
"provider-runtime-ingestion",
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
|||||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||||
const checkpointReactor = yield* CheckpointReactor;
|
const checkpointReactor = yield* CheckpointReactor;
|
||||||
|
|
||||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
const start: OrchestrationReactorShape["start"] = Effect.gen(function* () {
|
||||||
yield* providerRuntimeIngestion.start();
|
yield* providerRuntimeIngestion.start;
|
||||||
yield* providerCommandReactor.start();
|
yield* providerCommandReactor.start;
|
||||||
yield* checkpointReactor.start();
|
yield* checkpointReactor.start;
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ import {
|
|||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ interface AttachmentSideEffects {
|
|||||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")(
|
const materializeAttachmentsForProjection = Effect.fn(
|
||||||
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
|
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
|
||||||
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||||
);
|
);
|
||||||
@@ -237,152 +238,131 @@ function collectThreadAttachmentRelativePaths(
|
|||||||
return relativePaths;
|
return relativePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* (
|
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||||
sideEffects: AttachmentSideEffects,
|
|
||||||
) {
|
|
||||||
const serverConfig = yield* Effect.service(ServerConfig);
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||||
const path = yield* Effect.service(Path.Path);
|
const path = yield* Effect.service(Path.Path);
|
||||||
|
|
||||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||||
const readAttachmentRootEntries = fileSystem
|
|
||||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
|
||||||
|
|
||||||
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
|
yield* Effect.forEach(
|
||||||
function* (threadSegment: string, entry: string) {
|
sideEffects.deletedThreadIds,
|
||||||
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
(threadId) =>
|
||||||
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
Effect.gen(function* () {
|
||||||
return;
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
}
|
if (!threadSegment) {
|
||||||
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||||
if (!attachmentId) {
|
threadId,
|
||||||
return;
|
});
|
||||||
}
|
return;
|
||||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
}
|
||||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
const entries = yield* fileSystem
|
||||||
return;
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
}
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
yield* Effect.forEach(
|
||||||
force: true,
|
entries,
|
||||||
});
|
(entry) =>
|
||||||
},
|
Effect.gen(function* () {
|
||||||
|
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
|
|
||||||
const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* (
|
|
||||||
threadId: string,
|
|
||||||
) {
|
|
||||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
|
||||||
if (!threadSegment) {
|
|
||||||
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
|
||||||
threadId,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const entries = yield* readAttachmentRootEntries;
|
|
||||||
yield* Effect.forEach(
|
|
||||||
entries,
|
|
||||||
(entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),
|
|
||||||
{
|
|
||||||
concurrency: 1,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* (
|
|
||||||
threadSegment: string,
|
|
||||||
keptThreadRelativePaths: Set<string>,
|
|
||||||
entry: string,
|
|
||||||
) {
|
|
||||||
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
|
||||||
if (relativePath.length === 0 || relativePath.includes("/")) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
|
||||||
if (!attachmentId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
|
||||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
|
||||||
const fileInfo = yield* fileSystem
|
|
||||||
.stat(absolutePath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!keptThreadRelativePaths.has(relativePath)) {
|
|
||||||
yield* fileSystem.remove(absolutePath, { force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* (
|
|
||||||
threadId: string,
|
|
||||||
keptThreadRelativePaths: Set<string>,
|
|
||||||
) {
|
|
||||||
if (sideEffects.deletedThreadIds.has(threadId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
|
||||||
if (!threadSegment) {
|
|
||||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const entries = yield* readAttachmentRootEntries;
|
|
||||||
yield* Effect.forEach(
|
|
||||||
entries,
|
|
||||||
(entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {
|
|
||||||
concurrency: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
sideEffects.prunedThreadRelativePaths.entries(),
|
sideEffects.prunedThreadRelativePaths.entries(),
|
||||||
([threadId, keptThreadRelativePaths]) =>
|
([threadId, keptThreadRelativePaths]) => {
|
||||||
pruneThreadAttachments(threadId, keptThreadRelativePaths),
|
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||||
|
return Effect.void;
|
||||||
|
}
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const entries = yield* fileSystem
|
||||||
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
|
yield* Effect.forEach(
|
||||||
|
entries,
|
||||||
|
(entry) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(absolutePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||||
|
yield* fileSystem.remove(absolutePath, { force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")(
|
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||||
function* () {
|
const sql = yield* SqlClient.SqlClient;
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const eventStore = yield* OrchestrationEventStore;
|
||||||
const eventStore = yield* OrchestrationEventStore;
|
const projectionStateRepository = yield* ProjectionStateRepository;
|
||||||
const projectionStateRepository = yield* ProjectionStateRepository;
|
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
|
||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
|
|
||||||
const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||||
"applyProjectsProjection",
|
Effect.gen(function* () {
|
||||||
)(function* (event, _attachmentSideEffects) {
|
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "project.created":
|
case "project.created":
|
||||||
yield* projectionProjectRepository.upsert({
|
yield* projectionProjectRepository.upsert({
|
||||||
projectId: event.payload.projectId,
|
projectId: event.payload.projectId,
|
||||||
title: event.payload.title,
|
title: event.payload.title,
|
||||||
workspaceRoot: event.payload.workspaceRoot,
|
workspaceRoot: event.payload.workspaceRoot,
|
||||||
defaultModelSelection: event.payload.defaultModelSelection,
|
defaultModel: event.payload.defaultModel,
|
||||||
scripts: event.payload.scripts,
|
scripts: event.payload.scripts,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
updatedAt: event.payload.updatedAt,
|
updatedAt: event.payload.updatedAt,
|
||||||
@@ -403,8 +383,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
...(event.payload.workspaceRoot !== undefined
|
...(event.payload.workspaceRoot !== undefined
|
||||||
? { workspaceRoot: event.payload.workspaceRoot }
|
? { workspaceRoot: event.payload.workspaceRoot }
|
||||||
: {}),
|
: {}),
|
||||||
...(event.payload.defaultModelSelection !== undefined
|
...(event.payload.defaultModel !== undefined
|
||||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
? { defaultModel: event.payload.defaultModel }
|
||||||
: {}),
|
: {}),
|
||||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||||
updatedAt: event.payload.updatedAt,
|
updatedAt: event.payload.updatedAt,
|
||||||
@@ -432,16 +412,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||||
"applyThreadsProjection",
|
Effect.gen(function* () {
|
||||||
)(function* (event, attachmentSideEffects) {
|
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.created":
|
case "thread.created":
|
||||||
yield* projectionThreadRepository.upsert({
|
yield* projectionThreadRepository.upsert({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
projectId: event.payload.projectId,
|
projectId: event.payload.projectId,
|
||||||
title: event.payload.title,
|
title: event.payload.title,
|
||||||
modelSelection: event.payload.modelSelection,
|
model: event.payload.model,
|
||||||
runtimeMode: event.payload.runtimeMode,
|
runtimeMode: event.payload.runtimeMode,
|
||||||
interactionMode: event.payload.interactionMode,
|
interactionMode: event.payload.interactionMode,
|
||||||
branch: event.payload.branch,
|
branch: event.payload.branch,
|
||||||
@@ -449,41 +428,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
latestTurnId: null,
|
latestTurnId: null,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
updatedAt: event.payload.updatedAt,
|
updatedAt: event.payload.updatedAt,
|
||||||
archivedAt: null,
|
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
|
||||||
case "thread.archived": {
|
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
});
|
|
||||||
if (Option.isNone(existingRow)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
yield* projectionThreadRepository.upsert({
|
|
||||||
...existingRow.value,
|
|
||||||
archivedAt: event.payload.archivedAt,
|
|
||||||
updatedAt: event.payload.updatedAt,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "thread.unarchived": {
|
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
});
|
|
||||||
if (Option.isNone(existingRow)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
yield* projectionThreadRepository.upsert({
|
|
||||||
...existingRow.value,
|
|
||||||
archivedAt: null,
|
|
||||||
updatedAt: event.payload.updatedAt,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "thread.meta-updated": {
|
case "thread.meta-updated": {
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
const existingRow = yield* projectionThreadRepository.getById({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
@@ -494,9 +442,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
yield* projectionThreadRepository.upsert({
|
yield* projectionThreadRepository.upsert({
|
||||||
...existingRow.value,
|
...existingRow.value,
|
||||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||||
...(event.payload.modelSelection !== undefined
|
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||||
? { modelSelection: event.payload.modelSelection }
|
|
||||||
: {}),
|
|
||||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||||
...(event.payload.worktreePath !== undefined
|
...(event.payload.worktreePath !== undefined
|
||||||
? { worktreePath: event.payload.worktreePath }
|
? { worktreePath: event.payload.worktreePath }
|
||||||
@@ -618,9 +564,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyThreadMessagesProjection",
|
event,
|
||||||
)(function* (event, attachmentSideEffects) {
|
attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.message-sent": {
|
case "thread.message-sent": {
|
||||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||||
@@ -693,9 +641,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyThreadProposedPlansProjection",
|
event,
|
||||||
)(function* (event, _attachmentSideEffects) {
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.proposed-plan-upserted":
|
case "thread.proposed-plan-upserted":
|
||||||
yield* projectionThreadProposedPlanRepository.upsert({
|
yield* projectionThreadProposedPlanRepository.upsert({
|
||||||
@@ -703,8 +653,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
turnId: event.payload.proposedPlan.turnId,
|
turnId: event.payload.proposedPlan.turnId,
|
||||||
planMarkdown: event.payload.proposedPlan.planMarkdown,
|
planMarkdown: event.payload.proposedPlan.planMarkdown,
|
||||||
implementedAt: event.payload.proposedPlan.implementedAt,
|
|
||||||
implementationThreadId: event.payload.proposedPlan.implementationThreadId,
|
|
||||||
createdAt: event.payload.proposedPlan.createdAt,
|
createdAt: event.payload.proposedPlan.createdAt,
|
||||||
updatedAt: event.payload.proposedPlan.updatedAt,
|
updatedAt: event.payload.proposedPlan.updatedAt,
|
||||||
});
|
});
|
||||||
@@ -744,9 +692,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyThreadActivitiesProjection",
|
event,
|
||||||
)(function* (event, _attachmentSideEffects) {
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended":
|
case "thread.activity-appended":
|
||||||
yield* projectionThreadActivityRepository.upsert({
|
yield* projectionThreadActivityRepository.upsert({
|
||||||
@@ -796,9 +746,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyThreadSessionsProjection",
|
event,
|
||||||
)(function* (event, _attachmentSideEffects) {
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
if (event.type !== "thread.session-set") {
|
if (event.type !== "thread.session-set") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -813,16 +765,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyThreadTurnsProjection",
|
event,
|
||||||
)(function* (event, _attachmentSideEffects) {
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.turn-start-requested": {
|
case "thread.turn-start-requested": {
|
||||||
yield* projectionTurnRepository.replacePendingTurnStart({
|
yield* projectionTurnRepository.replacePendingTurnStart({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
messageId: event.payload.messageId,
|
messageId: event.payload.messageId,
|
||||||
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
|
|
||||||
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
|
|
||||||
requestedAt: event.payload.createdAt,
|
requestedAt: event.payload.createdAt,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -852,16 +804,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
pendingMessageId:
|
pendingMessageId:
|
||||||
existingTurn.value.pendingMessageId ??
|
existingTurn.value.pendingMessageId ??
|
||||||
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
|
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
|
||||||
sourceProposedPlanThreadId:
|
|
||||||
existingTurn.value.sourceProposedPlanThreadId ??
|
|
||||||
(Option.isSome(pendingTurnStart)
|
|
||||||
? pendingTurnStart.value.sourceProposedPlanThreadId
|
|
||||||
: null),
|
|
||||||
sourceProposedPlanId:
|
|
||||||
existingTurn.value.sourceProposedPlanId ??
|
|
||||||
(Option.isSome(pendingTurnStart)
|
|
||||||
? pendingTurnStart.value.sourceProposedPlanId
|
|
||||||
: null),
|
|
||||||
startedAt:
|
startedAt:
|
||||||
existingTurn.value.startedAt ??
|
existingTurn.value.startedAt ??
|
||||||
(Option.isSome(pendingTurnStart)
|
(Option.isSome(pendingTurnStart)
|
||||||
@@ -880,12 +822,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
pendingMessageId: Option.isSome(pendingTurnStart)
|
pendingMessageId: Option.isSome(pendingTurnStart)
|
||||||
? pendingTurnStart.value.messageId
|
? pendingTurnStart.value.messageId
|
||||||
: null,
|
: null,
|
||||||
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
|
|
||||||
? pendingTurnStart.value.sourceProposedPlanThreadId
|
|
||||||
: null,
|
|
||||||
sourceProposedPlanId: Option.isSome(pendingTurnStart)
|
|
||||||
? pendingTurnStart.value.sourceProposedPlanId
|
|
||||||
: null,
|
|
||||||
assistantMessageId: null,
|
assistantMessageId: null,
|
||||||
state: "running",
|
state: "running",
|
||||||
requestedAt: Option.isSome(pendingTurnStart)
|
requestedAt: Option.isSome(pendingTurnStart)
|
||||||
@@ -939,8 +875,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
turnId: event.payload.turnId,
|
turnId: event.payload.turnId,
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
pendingMessageId: null,
|
pendingMessageId: null,
|
||||||
sourceProposedPlanThreadId: null,
|
|
||||||
sourceProposedPlanId: null,
|
|
||||||
assistantMessageId: event.payload.messageId,
|
assistantMessageId: event.payload.messageId,
|
||||||
state: event.payload.streaming ? "running" : "completed",
|
state: event.payload.streaming ? "running" : "completed",
|
||||||
requestedAt: event.payload.createdAt,
|
requestedAt: event.payload.createdAt,
|
||||||
@@ -976,8 +910,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
turnId: event.payload.turnId,
|
turnId: event.payload.turnId,
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
pendingMessageId: null,
|
pendingMessageId: null,
|
||||||
sourceProposedPlanThreadId: null,
|
|
||||||
sourceProposedPlanId: null,
|
|
||||||
assistantMessageId: null,
|
assistantMessageId: null,
|
||||||
state: "interrupted",
|
state: "interrupted",
|
||||||
requestedAt: event.payload.createdAt,
|
requestedAt: event.payload.createdAt,
|
||||||
@@ -1022,8 +954,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
turnId: event.payload.turnId,
|
turnId: event.payload.turnId,
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
pendingMessageId: null,
|
pendingMessageId: null,
|
||||||
sourceProposedPlanThreadId: null,
|
|
||||||
sourceProposedPlanId: null,
|
|
||||||
assistantMessageId: event.payload.assistantMessageId,
|
assistantMessageId: event.payload.assistantMessageId,
|
||||||
state: nextState,
|
state: nextState,
|
||||||
requestedAt: event.payload.completedAt,
|
requestedAt: event.payload.completedAt,
|
||||||
@@ -1069,11 +999,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||||
|
|
||||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||||
"applyPendingApprovalsProjection",
|
event,
|
||||||
)(function* (event, _attachmentSideEffects) {
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended": {
|
case "thread.activity-appended": {
|
||||||
const requestId =
|
const requestId =
|
||||||
@@ -1159,49 +1091,47 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const projectors: ReadonlyArray<ProjectorDefinition> = [
|
const projectors: ReadonlyArray<ProjectorDefinition> = [
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||||
apply: applyProjectsProjection,
|
apply: applyProjectsProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||||
apply: applyThreadMessagesProjection,
|
apply: applyThreadMessagesProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||||
apply: applyThreadProposedPlansProjection,
|
apply: applyThreadProposedPlansProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||||
apply: applyThreadActivitiesProjection,
|
apply: applyThreadActivitiesProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||||
apply: applyThreadSessionsProjection,
|
apply: applyThreadSessionsProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
||||||
apply: applyThreadTurnsProjection,
|
apply: applyThreadTurnsProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||||
apply: applyCheckpointsProjection,
|
apply: applyCheckpointsProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
|
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
|
||||||
apply: applyPendingApprovalsProjection,
|
apply: applyPendingApprovalsProjection,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
|
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||||
apply: applyThreadsProjection,
|
apply: applyThreadsProjection,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
projector: ProjectorDefinition,
|
Effect.gen(function* () {
|
||||||
event: OrchestrationEvent,
|
|
||||||
) {
|
|
||||||
const attachmentSideEffects: AttachmentSideEffects = {
|
const attachmentSideEffects: AttachmentSideEffects = {
|
||||||
deletedThreadIds: new Set<string>(),
|
deletedThreadIds: new Set<string>(),
|
||||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||||
@@ -1231,65 +1161,65 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||||
projectionStateRepository
|
projectionStateRepository
|
||||||
.getByProjector({
|
.getByProjector({
|
||||||
projector: projector.name,
|
projector: projector.name,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.flatMap((stateRow) =>
|
Effect.flatMap((stateRow) =>
|
||||||
Stream.runForEach(
|
Stream.runForEach(
|
||||||
eventStore.readFromSequence(
|
eventStore.readFromSequence(
|
||||||
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
|
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
|
||||||
),
|
|
||||||
(event) => runProjectorForEvent(projector, event),
|
|
||||||
),
|
),
|
||||||
|
(event) => runProjectorForEvent(projector, event),
|
||||||
),
|
),
|
||||||
);
|
|
||||||
|
|
||||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
|
||||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
|
||||||
concurrency: 1,
|
|
||||||
}).pipe(
|
|
||||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
|
||||||
Effect.provideService(Path.Path, path),
|
|
||||||
Effect.provideService(ServerConfig, serverConfig),
|
|
||||||
Effect.asVoid,
|
|
||||||
Effect.catchTag("SqlError", (sqlError) =>
|
|
||||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
||||||
projectors,
|
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||||
bootstrapProjector,
|
concurrency: 1,
|
||||||
{ concurrency: 1 },
|
}).pipe(
|
||||||
).pipe(
|
|
||||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
Effect.provideService(Path.Path, path),
|
Effect.provideService(Path.Path, path),
|
||||||
Effect.provideService(ServerConfig, serverConfig),
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
Effect.tap(() =>
|
|
||||||
Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
|
|
||||||
Effect.annotateLogs({ projectors: projectors.length }),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.catchTag("SqlError", (sqlError) =>
|
Effect.catchTag("SqlError", (sqlError) =>
|
||||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||||
bootstrap,
|
projectors,
|
||||||
projectEvent,
|
bootstrapProjector,
|
||||||
} satisfies OrchestrationProjectionPipelineShape;
|
{ concurrency: 1 },
|
||||||
},
|
).pipe(
|
||||||
);
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
|
Effect.asVoid,
|
||||||
|
Effect.tap(() =>
|
||||||
|
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||||
|
Effect.annotateLogs({ projectors: projectors.length }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.catchTag("SqlError", (sqlError) =>
|
||||||
|
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
bootstrap,
|
||||||
|
projectEvent,
|
||||||
|
} satisfies OrchestrationProjectionPipelineShape;
|
||||||
|
});
|
||||||
|
|
||||||
export const OrchestrationProjectionPipelineLive = Layer.effect(
|
export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
makeOrchestrationProjectionPipeline(),
|
makeOrchestrationProjectionPipeline,
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
|
|
||||||
yield* sql`DELETE FROM projection_projects`;
|
yield* sql`DELETE FROM projection_projects`;
|
||||||
yield* sql`DELETE FROM projection_state`;
|
yield* sql`DELETE FROM projection_state`;
|
||||||
yield* sql`DELETE FROM projection_thread_proposed_plans`;
|
|
||||||
yield* sql`DELETE FROM projection_turns`;
|
yield* sql`DELETE FROM projection_turns`;
|
||||||
|
|
||||||
yield* sql`
|
yield* sql`
|
||||||
@@ -34,7 +33,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
project_id,
|
project_id,
|
||||||
title,
|
title,
|
||||||
workspace_root,
|
workspace_root,
|
||||||
default_model_selection_json,
|
default_model,
|
||||||
scripts_json,
|
scripts_json,
|
||||||
created_at,
|
created_at,
|
||||||
updated_at,
|
updated_at,
|
||||||
@@ -44,7 +43,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
'project-1',
|
'project-1',
|
||||||
'Project 1',
|
'Project 1',
|
||||||
'/tmp/project-1',
|
'/tmp/project-1',
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
'gpt-5-codex',
|
||||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||||
'2026-02-24T00:00:00.000Z',
|
'2026-02-24T00:00:00.000Z',
|
||||||
'2026-02-24T00:00:01.000Z',
|
'2026-02-24T00:00:01.000Z',
|
||||||
@@ -57,7 +56,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
thread_id,
|
thread_id,
|
||||||
project_id,
|
project_id,
|
||||||
title,
|
title,
|
||||||
model_selection_json,
|
model,
|
||||||
branch,
|
branch,
|
||||||
worktree_path,
|
worktree_path,
|
||||||
latest_turn_id,
|
latest_turn_id,
|
||||||
@@ -69,7 +68,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
'thread-1',
|
'thread-1',
|
||||||
'project-1',
|
'project-1',
|
||||||
'Thread 1',
|
'Thread 1',
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
'gpt-5-codex',
|
||||||
NULL,
|
NULL,
|
||||||
NULL,
|
NULL,
|
||||||
'turn-1',
|
'turn-1',
|
||||||
@@ -102,29 +101,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
)
|
)
|
||||||
`;
|
`;
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_thread_proposed_plans (
|
|
||||||
plan_id,
|
|
||||||
thread_id,
|
|
||||||
turn_id,
|
|
||||||
plan_markdown,
|
|
||||||
implemented_at,
|
|
||||||
implementation_thread_id,
|
|
||||||
created_at,
|
|
||||||
updated_at
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'plan-1',
|
|
||||||
'thread-1',
|
|
||||||
'turn-1',
|
|
||||||
'# Ship it',
|
|
||||||
'2026-02-24T00:00:05.500Z',
|
|
||||||
'thread-2',
|
|
||||||
'2026-02-24T00:00:05.000Z',
|
|
||||||
'2026-02-24T00:00:05.500Z'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
yield* sql`
|
||||||
INSERT INTO projection_thread_activities (
|
INSERT INTO projection_thread_activities (
|
||||||
activity_id,
|
activity_id,
|
||||||
@@ -178,8 +154,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
thread_id,
|
thread_id,
|
||||||
turn_id,
|
turn_id,
|
||||||
pending_message_id,
|
pending_message_id,
|
||||||
source_proposed_plan_thread_id,
|
|
||||||
source_proposed_plan_id,
|
|
||||||
assistant_message_id,
|
assistant_message_id,
|
||||||
state,
|
state,
|
||||||
requested_at,
|
requested_at,
|
||||||
@@ -194,8 +168,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
'thread-1',
|
'thread-1',
|
||||||
'turn-1',
|
'turn-1',
|
||||||
NULL,
|
NULL,
|
||||||
'thread-1',
|
|
||||||
'plan-1',
|
|
||||||
'message-1',
|
'message-1',
|
||||||
'completed',
|
'completed',
|
||||||
'2026-02-24T00:00:08.000Z',
|
'2026-02-24T00:00:08.000Z',
|
||||||
@@ -234,10 +206,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
id: asProjectId("project-1"),
|
id: asProjectId("project-1"),
|
||||||
title: "Project 1",
|
title: "Project 1",
|
||||||
workspaceRoot: "/tmp/project-1",
|
workspaceRoot: "/tmp/project-1",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
scripts: [
|
scripts: [
|
||||||
{
|
{
|
||||||
id: "script-1",
|
id: "script-1",
|
||||||
@@ -257,10 +226,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
id: ThreadId.makeUnsafe("thread-1"),
|
id: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread 1",
|
title: "Thread 1",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -272,14 +238,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
startedAt: "2026-02-24T00:00:08.000Z",
|
startedAt: "2026-02-24T00:00:08.000Z",
|
||||||
completedAt: "2026-02-24T00:00:08.000Z",
|
completedAt: "2026-02-24T00:00:08.000Z",
|
||||||
assistantMessageId: asMessageId("message-1"),
|
assistantMessageId: asMessageId("message-1"),
|
||||||
sourceProposedPlan: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
planId: "plan-1",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
createdAt: "2026-02-24T00:00:02.000Z",
|
createdAt: "2026-02-24T00:00:02.000Z",
|
||||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||||
archivedAt: null,
|
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
messages: [
|
messages: [
|
||||||
{
|
{
|
||||||
@@ -292,17 +253,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
proposedPlans: [
|
proposedPlans: [],
|
||||||
{
|
|
||||||
id: "plan-1",
|
|
||||||
turnId: asTurnId("turn-1"),
|
|
||||||
planMarkdown: "# Ship it",
|
|
||||||
implementedAt: "2026-02-24T00:00:05.500Z",
|
|
||||||
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
|
|
||||||
createdAt: "2026-02-24T00:00:05.000Z",
|
|
||||||
updatedAt: "2026-02-24T00:00:05.500Z",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activities: [
|
activities: [
|
||||||
{
|
{
|
||||||
id: asEventId("activity-1"),
|
id: asEventId("activity-1"),
|
||||||
|
|||||||
@@ -4,10 +4,8 @@ import {
|
|||||||
MessageId,
|
MessageId,
|
||||||
NonNegativeInt,
|
NonNegativeInt,
|
||||||
OrchestrationCheckpointFile,
|
OrchestrationCheckpointFile,
|
||||||
OrchestrationProposedPlanId,
|
|
||||||
OrchestrationReadModel,
|
OrchestrationReadModel,
|
||||||
ProjectScript,
|
ProjectScript,
|
||||||
ThreadId,
|
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationCheckpointSummary,
|
type OrchestrationCheckpointSummary,
|
||||||
type OrchestrationLatestTurn,
|
type OrchestrationLatestTurn,
|
||||||
@@ -17,7 +15,6 @@ import {
|
|||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
ModelSelection,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, Schema, Struct } from "effect";
|
import { Effect, Layer, Schema, Struct } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
@@ -46,7 +43,6 @@ import {
|
|||||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
|
||||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -57,11 +53,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||||
Struct.assign({
|
|
||||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
payload: Schema.fromJsonString(Schema.Unknown),
|
payload: Schema.fromJsonString(Schema.Unknown),
|
||||||
@@ -82,8 +74,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
|||||||
startedAt: Schema.NullOr(IsoDateTime),
|
startedAt: Schema.NullOr(IsoDateTime),
|
||||||
completedAt: Schema.NullOr(IsoDateTime),
|
completedAt: Schema.NullOr(IsoDateTime),
|
||||||
assistantMessageId: Schema.NullOr(MessageId),
|
assistantMessageId: Schema.NullOr(MessageId),
|
||||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
|
||||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
|
||||||
});
|
});
|
||||||
const ProjectionStateDbRowSchema = ProjectionState;
|
const ProjectionStateDbRowSchema = ProjectionState;
|
||||||
|
|
||||||
@@ -147,7 +137,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
project_id AS "projectId",
|
project_id AS "projectId",
|
||||||
title,
|
title,
|
||||||
workspace_root AS "workspaceRoot",
|
workspace_root AS "workspaceRoot",
|
||||||
default_model_selection_json AS "defaultModelSelection",
|
default_model AS "defaultModel",
|
||||||
scripts_json AS "scripts",
|
scripts_json AS "scripts",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt",
|
updated_at AS "updatedAt",
|
||||||
@@ -166,7 +156,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
project_id AS "projectId",
|
project_id AS "projectId",
|
||||||
title,
|
title,
|
||||||
model_selection_json AS "modelSelection",
|
model,
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
interaction_mode AS "interactionMode",
|
interaction_mode AS "interactionMode",
|
||||||
branch,
|
branch,
|
||||||
@@ -174,7 +164,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
latest_turn_id AS "latestTurnId",
|
latest_turn_id AS "latestTurnId",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt",
|
updated_at AS "updatedAt",
|
||||||
archived_at AS "archivedAt",
|
|
||||||
deleted_at AS "deletedAt"
|
deleted_at AS "deletedAt"
|
||||||
FROM projection_threads
|
FROM projection_threads
|
||||||
ORDER BY created_at ASC, thread_id ASC
|
ORDER BY created_at ASC, thread_id ASC
|
||||||
@@ -211,8 +200,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
plan_markdown AS "planMarkdown",
|
plan_markdown AS "planMarkdown",
|
||||||
implemented_at AS "implementedAt",
|
|
||||||
implementation_thread_id AS "implementationThreadId",
|
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
FROM projection_thread_proposed_plans
|
FROM projection_thread_proposed_plans
|
||||||
@@ -297,9 +284,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
requested_at AS "requestedAt",
|
requested_at AS "requestedAt",
|
||||||
started_at AS "startedAt",
|
started_at AS "startedAt",
|
||||||
completed_at AS "completedAt",
|
completed_at AS "completedAt",
|
||||||
assistant_message_id AS "assistantMessageId",
|
assistant_message_id AS "assistantMessageId"
|
||||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
|
||||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
|
||||||
FROM projection_turns
|
FROM projection_turns
|
||||||
WHERE turn_id IS NOT NULL
|
WHERE turn_id IS NOT NULL
|
||||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||||
@@ -450,8 +435,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
id: row.planId,
|
id: row.planId,
|
||||||
turnId: row.turnId,
|
turnId: row.turnId,
|
||||||
planMarkdown: row.planMarkdown,
|
planMarkdown: row.planMarkdown,
|
||||||
implementedAt: row.implementedAt,
|
|
||||||
implementationThreadId: row.implementationThreadId,
|
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
});
|
});
|
||||||
@@ -514,14 +497,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
startedAt: row.startedAt,
|
startedAt: row.startedAt,
|
||||||
completedAt: row.completedAt,
|
completedAt: row.completedAt,
|
||||||
assistantMessageId: row.assistantMessageId,
|
assistantMessageId: row.assistantMessageId,
|
||||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
|
||||||
? {
|
|
||||||
sourceProposedPlan: {
|
|
||||||
threadId: row.sourceProposedPlanThreadId,
|
|
||||||
planId: row.sourceProposedPlanId,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,22 +513,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||||
id: row.projectId,
|
id: row.projectId,
|
||||||
title: row.title,
|
title: row.title,
|
||||||
workspaceRoot: row.workspaceRoot,
|
workspaceRoot: row.workspaceRoot,
|
||||||
defaultModelSelection: row.defaultModelSelection,
|
defaultModel: row.defaultModel,
|
||||||
scripts: row.scripts,
|
scripts: row.scripts,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
deletedAt: row.deletedAt,
|
deletedAt: row.deletedAt,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
|
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||||
id: row.threadId,
|
id: row.threadId,
|
||||||
projectId: row.projectId,
|
projectId: row.projectId,
|
||||||
title: row.title,
|
title: row.title,
|
||||||
modelSelection: row.modelSelection,
|
model: row.model,
|
||||||
runtimeMode: row.runtimeMode,
|
runtimeMode: row.runtimeMode,
|
||||||
interactionMode: row.interactionMode,
|
interactionMode: row.interactionMode,
|
||||||
branch: row.branch,
|
branch: row.branch,
|
||||||
@@ -561,7 +536,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
archivedAt: row.archivedAt,
|
|
||||||
deletedAt: row.deletedAt,
|
deletedAt: row.deletedAt,
|
||||||
messages: messagesByThread.get(row.threadId) ?? [],
|
messages: messagesByThread.get(row.threadId) ?? [],
|
||||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
CommandId,
|
CommandId,
|
||||||
@@ -16,8 +16,8 @@ import {
|
|||||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "../../git/Errors.ts";
|
||||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
@@ -34,7 +34,6 @@ import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
|||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||||
@@ -42,9 +41,6 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
|||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||||
|
|
||||||
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
|
|
||||||
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
|
|
||||||
|
|
||||||
async function waitFor(
|
async function waitFor(
|
||||||
predicate: () => boolean | Promise<boolean>,
|
predicate: () => boolean | Promise<boolean>,
|
||||||
timeoutMs = 2000,
|
timeoutMs = 2000,
|
||||||
@@ -71,7 +67,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
> | null = null;
|
> | null = null;
|
||||||
let scope: Scope.Closeable | null = null;
|
let scope: Scope.Closeable | null = null;
|
||||||
const createdStateDirs = new Set<string>();
|
const createdStateDirs = new Set<string>();
|
||||||
const createdBaseDirs = new Set<string>();
|
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
if (scope) {
|
if (scope) {
|
||||||
@@ -86,35 +81,35 @@ describe("ProviderCommandReactor", () => {
|
|||||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
createdStateDirs.clear();
|
createdStateDirs.clear();
|
||||||
for (const baseDir of createdBaseDirs) {
|
|
||||||
fs.rmSync(baseDir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
createdBaseDirs.clear();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
async function createHarness(input?: {
|
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||||
readonly baseDir?: string;
|
|
||||||
readonly threadModelSelection?: ModelSelection;
|
|
||||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
|
||||||
}) {
|
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||||
createdBaseDirs.add(baseDir);
|
|
||||||
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
|
|
||||||
createdStateDirs.add(stateDir);
|
createdStateDirs.add(stateDir);
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
let nextSessionIndex = 1;
|
let nextSessionIndex = 1;
|
||||||
const runtimeSessions: Array<ProviderSession> = [];
|
const runtimeSessions: Array<ProviderSession> = [];
|
||||||
const modelSelection = input?.threadModelSelection ?? {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
};
|
|
||||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||||
const sessionIndex = nextSessionIndex++;
|
const sessionIndex = nextSessionIndex++;
|
||||||
|
const provider =
|
||||||
|
typeof input === "object" &&
|
||||||
|
input !== null &&
|
||||||
|
"provider" in input &&
|
||||||
|
input.provider === "codex"
|
||||||
|
? input.provider
|
||||||
|
: "codex";
|
||||||
const resumeCursor =
|
const resumeCursor =
|
||||||
typeof input === "object" && input !== null && "resumeCursor" in input
|
typeof input === "object" && input !== null && "resumeCursor" in input
|
||||||
? input.resumeCursor
|
? input.resumeCursor
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const model =
|
||||||
|
typeof input === "object" &&
|
||||||
|
input !== null &&
|
||||||
|
"model" in input &&
|
||||||
|
typeof input.model === "string"
|
||||||
|
? input.model
|
||||||
|
: undefined;
|
||||||
const threadId =
|
const threadId =
|
||||||
typeof input === "object" &&
|
typeof input === "object" &&
|
||||||
input !== null &&
|
input !== null &&
|
||||||
@@ -123,7 +118,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
? ThreadId.makeUnsafe(input.threadId)
|
? ThreadId.makeUnsafe(input.threadId)
|
||||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||||
const session: ProviderSession = {
|
const session: ProviderSession = {
|
||||||
provider: modelSelection.provider,
|
provider,
|
||||||
status: "ready" as const,
|
status: "ready" as const,
|
||||||
runtimeMode:
|
runtimeMode:
|
||||||
typeof input === "object" &&
|
typeof input === "object" &&
|
||||||
@@ -132,9 +127,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
||||||
? input.runtimeMode
|
? input.runtimeMode
|
||||||
: "full-access",
|
: "full-access",
|
||||||
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
|
...(model !== undefined ? { model } : {}),
|
||||||
threadId,
|
threadId,
|
||||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
@@ -176,7 +171,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
: "renamed-branch",
|
: "renamed-branch",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
const generateBranchName = vi.fn(() =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new TextGenerationError({
|
new TextGenerationError({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
@@ -184,14 +179,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
const generateThreadTitle = vi.fn<TextGenerationShape["generateThreadTitle"]>((_) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "disabled in test harness",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||||
const service: ProviderServiceShape = {
|
const service: ProviderServiceShape = {
|
||||||
@@ -202,9 +189,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||||
listSessions: () => Effect.succeed(runtimeSessions),
|
listSessions: () => Effect.succeed(runtimeSessions),
|
||||||
getCapabilities: (_provider) =>
|
getCapabilities: (provider) =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||||
}),
|
}),
|
||||||
rollbackConversation: () => unsupported(),
|
rollbackConversation: () => unsupported(),
|
||||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||||
@@ -221,13 +208,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.mock(TextGeneration, {
|
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||||
generateBranchName,
|
|
||||||
generateThreadTitle,
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtime = ManagedRuntime.make(layer);
|
const runtime = ManagedRuntime.make(layer);
|
||||||
@@ -235,7 +218,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||||
const drain = () => Effect.runPromise(reactor.drain);
|
const drain = () => Effect.runPromise(reactor.drain);
|
||||||
|
|
||||||
await Effect.runPromise(
|
await Effect.runPromise(
|
||||||
@@ -245,7 +228,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Provider Project",
|
title: "Provider Project",
|
||||||
workspaceRoot: "/tmp/provider-project",
|
workspaceRoot: "/tmp/provider-project",
|
||||||
defaultModelSelection: modelSelection,
|
defaultModel: "gpt-5-codex",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -256,7 +239,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: modelSelection,
|
model: "gpt-5-codex",
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -275,7 +258,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
stopSession,
|
stopSession,
|
||||||
renameBranch,
|
renameBranch,
|
||||||
generateBranchName,
|
generateBranchName,
|
||||||
generateThreadTitle,
|
|
||||||
stateDir,
|
stateDir,
|
||||||
drain,
|
drain,
|
||||||
};
|
};
|
||||||
@@ -307,10 +289,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
cwd: "/tmp/provider-project",
|
cwd: "/tmp/provider-project",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -320,199 +299,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("generates a thread title on the first turn", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
|
||||||
harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" }));
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
title: seededTitle,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-title"),
|
|
||||||
role: "user",
|
|
||||||
text: "Please investigate reconnect failures after restarting the session.",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
titleSeed: seededTitle,
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
|
||||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({
|
|
||||||
message: "Please investigate reconnect failures after restarting the session.",
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
return (
|
|
||||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
|
||||||
"Generated title"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.title).toBe("Generated title");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not overwrite an existing custom thread title on the first turn", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
title: "Keep this custom title",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-title-preserve"),
|
|
||||||
role: "user",
|
|
||||||
text: "Please investigate reconnect failures after restarting the session.",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
titleSeed: seededTitle,
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.title).toBe("Keep this custom title");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const seededTitle = "Fix reconnect spinner on resume";
|
|
||||||
harness.generateThreadTitle.mockReturnValue(
|
|
||||||
Effect.succeed({
|
|
||||||
title: "Reconnect spinner resume bug",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
title: seededTitle,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-title-formatted"),
|
|
||||||
role: "user",
|
|
||||||
text: "[effort:high]\\n\\nFix reconnect spinner on resume",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
titleSeed: seededTitle,
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
return (
|
|
||||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
|
||||||
"Reconnect spinner resume bug"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("generates a worktree branch name for the first turn", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-branch"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
branch: "t3code/1234abcd",
|
|
||||||
worktreePath: "/tmp/provider-project-worktree",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
harness.generateBranchName.mockImplementation((input: unknown) =>
|
|
||||||
Effect.succeed({
|
|
||||||
branch:
|
|
||||||
typeof input === "object" &&
|
|
||||||
input !== null &&
|
|
||||||
"modelSelection" in input &&
|
|
||||||
typeof input.modelSelection === "object" &&
|
|
||||||
input.modelSelection !== null &&
|
|
||||||
"model" in input.modelSelection &&
|
|
||||||
typeof input.modelSelection.model === "string"
|
|
||||||
? `feature/${input.modelSelection.model}`
|
|
||||||
: "feature/generated",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-branch-model"),
|
|
||||||
role: "user",
|
|
||||||
text: "Add a safer reconnect backoff.",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
|
||||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
|
||||||
message: "Add a safer reconnect backoff.",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("forwards codex model options through session start and turn send", async () => {
|
it("forwards codex model options through session start and turn send", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -528,10 +314,10 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello fast mode",
|
text: "hello fast mode",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: {
|
provider: "codex",
|
||||||
provider: "codex",
|
model: "gpt-5.3-codex",
|
||||||
model: "gpt-5.3-codex",
|
modelOptions: {
|
||||||
options: {
|
codex: {
|
||||||
reasoningEffort: "high",
|
reasoningEffort: "high",
|
||||||
fastMode: true,
|
fastMode: true,
|
||||||
},
|
},
|
||||||
@@ -545,10 +331,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
modelSelection: {
|
model: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
modelOptions: {
|
||||||
model: "gpt-5.3-codex",
|
codex: {
|
||||||
options: {
|
|
||||||
reasoningEffort: "high",
|
reasoningEffort: "high",
|
||||||
fastMode: true,
|
fastMode: true,
|
||||||
},
|
},
|
||||||
@@ -556,10 +341,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
modelSelection: {
|
model: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
modelOptions: {
|
||||||
model: "gpt-5.3-codex",
|
codex: {
|
||||||
options: {
|
|
||||||
reasoningEffort: "high",
|
reasoningEffort: "high",
|
||||||
fastMode: true,
|
fastMode: true,
|
||||||
},
|
},
|
||||||
@@ -567,112 +351,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forwards claude effort options through session start and turn send", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-claude-effort"),
|
|
||||||
role: "user",
|
|
||||||
text: "hello with effort",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-claude-fast-mode"),
|
|
||||||
role: "user",
|
|
||||||
text: "hello with fast mode",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
options: {
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
options: {
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
options: {
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("forwards plan interaction mode to the provider turn request", async () => {
|
it("forwards plan interaction mode to the provider turn request", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -711,111 +389,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-provider-first"),
|
|
||||||
role: "user",
|
|
||||||
text: "hello claude",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find(
|
|
||||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
|
||||||
false
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(harness.startSession).not.toHaveBeenCalled();
|
|
||||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.session).toBeNull();
|
|
||||||
expect(
|
|
||||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
).toMatchObject({
|
|
||||||
summary: "Provider turn start failed",
|
|
||||||
payload: {
|
|
||||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
|
||||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-unsupported-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-unsupported-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
|
||||||
|
|
||||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
modelSelection: {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -862,77 +435,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("restarts claude sessions when claude effort changes", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-claude-effort-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first claude turn",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "medium",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-claude-effort-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second claude turn",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
|
||||||
resumeCursor: { opaque: "resume-1" },
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -1007,7 +509,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
resumeCursor: { opaque: "resume-1" },
|
resumeCursor: { opaque: "cursor-1" },
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
});
|
});
|
||||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||||
@@ -1020,125 +522,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
status: "ready",
|
|
||||||
providerName: "claudeAgent",
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.runtime-mode.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
|
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-provider-switch-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-provider-switch-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find(
|
|
||||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
|
||||||
false
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
|
||||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
|
||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
|
||||||
expect(thread?.session?.providerName).toBe("codex");
|
|
||||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
|
||||||
expect(
|
|
||||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
).toMatchObject({
|
|
||||||
payload: {
|
|
||||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not stop the active session when restart fails before rebind", async () => {
|
it("does not stop the active session when restart fails before rebind", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -1414,7 +797,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(failureActivity).toBeDefined();
|
expect(failureActivity).toBeDefined();
|
||||||
expect(failureActivity?.payload).toMatchObject({
|
expect(failureActivity?.payload).toMatchObject({
|
||||||
requestId: "approval-request-1",
|
requestId: "approval-request-1",
|
||||||
detail: expect.stringContaining("Stale pending approval request: approval-request-1"),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolvedActivity = thread?.activities.find(
|
const resolvedActivity = thread?.activities.find(
|
||||||
@@ -1427,117 +809,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(resolvedActivity).toBeUndefined();
|
expect(resolvedActivity).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
harness.respondToUserInput.mockImplementation(() =>
|
|
||||||
Effect.fail(
|
|
||||||
new ProviderAdapterRequestError({
|
|
||||||
provider: "claudeAgent",
|
|
||||||
method: "item/tool/respondToUserInput",
|
|
||||||
detail: "Unknown pending user-input request: user-input-request-1",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
status: "running",
|
|
||||||
providerName: "claudeAgent",
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.activity.append",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
activity: {
|
|
||||||
id: EventId.makeUnsafe("activity-user-input-requested"),
|
|
||||||
tone: "info",
|
|
||||||
kind: "user-input.requested",
|
|
||||||
summary: "User input requested",
|
|
||||||
payload: {
|
|
||||||
requestId: "user-input-request-1",
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
id: "sandbox_mode",
|
|
||||||
header: "Sandbox",
|
|
||||||
question: "Which mode should be used?",
|
|
||||||
options: [
|
|
||||||
{
|
|
||||||
label: "workspace-write",
|
|
||||||
description: "Allow workspace writes only",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
turnId: null,
|
|
||||||
createdAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.user-input.respond",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
requestId: asApprovalRequestId("user-input-request-1"),
|
|
||||||
answers: {
|
|
||||||
sandbox_mode: "workspace-write",
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find(
|
|
||||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
|
||||||
);
|
|
||||||
if (!thread) return false;
|
|
||||||
return thread.activities.some(
|
|
||||||
(activity) => activity.kind === "provider.user-input.respond.failed",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread).toBeDefined();
|
|
||||||
|
|
||||||
const failureActivity = thread?.activities.find(
|
|
||||||
(activity) => activity.kind === "provider.user-input.respond.failed",
|
|
||||||
);
|
|
||||||
expect(failureActivity).toBeDefined();
|
|
||||||
expect(failureActivity?.payload).toMatchObject({
|
|
||||||
requestId: "user-input-request-1",
|
|
||||||
detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"),
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolvedActivity = thread?.activities.find(
|
|
||||||
(activity) =>
|
|
||||||
activity.kind === "user-input.resolved" &&
|
|
||||||
typeof activity.payload === "object" &&
|
|
||||||
activity.payload !== null &&
|
|
||||||
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
|
|
||||||
);
|
|
||||||
expect(resolvedActivity).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
|
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|||||||
@@ -2,16 +2,17 @@ import {
|
|||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
CommandId,
|
CommandId,
|
||||||
EventId,
|
EventId,
|
||||||
type ModelSelection,
|
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
ProviderKind,
|
type ProviderModelOptions,
|
||||||
|
type ProviderKind,
|
||||||
|
type ProviderStartOptions,
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type RuntimeMode,
|
type RuntimeMode,
|
||||||
type TurnId,
|
type TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
|
||||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||||
|
|
||||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||||
@@ -24,7 +25,6 @@ import {
|
|||||||
ProviderCommandReactor,
|
ProviderCommandReactor,
|
||||||
type ProviderCommandReactorShape,
|
type ProviderCommandReactorShape,
|
||||||
} from "../Services/ProviderCommandReactor.ts";
|
} from "../Services/ProviderCommandReactor.ts";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
type ProviderIntentEvent = Extract<
|
type ProviderIntentEvent = Extract<
|
||||||
OrchestrationEvent,
|
OrchestrationEvent,
|
||||||
@@ -73,19 +73,6 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
|||||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||||
const DEFAULT_THREAD_TITLE = "New thread";
|
|
||||||
|
|
||||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
|
||||||
const trimmedCurrentTitle = currentTitle.trim();
|
|
||||||
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const trimmedTitleSeed = titleSeed?.trim();
|
|
||||||
return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0
|
|
||||||
? trimmedCurrentTitle === trimmedTitleSeed
|
|
||||||
: false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||||
const error = Cause.squash(cause);
|
const error = Cause.squash(cause);
|
||||||
@@ -103,21 +90,6 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
|
||||||
const error = Cause.squash(cause);
|
|
||||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
|
||||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
|
||||||
}
|
|
||||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
|
||||||
}
|
|
||||||
|
|
||||||
function stalePendingRequestDetail(
|
|
||||||
requestKind: "approval" | "user-input",
|
|
||||||
requestId: string,
|
|
||||||
): string {
|
|
||||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||||
}
|
}
|
||||||
@@ -150,7 +122,6 @@ const make = Effect.gen(function* () {
|
|||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const serverSettingsService = yield* ServerSettingsService;
|
|
||||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||||
@@ -164,7 +135,7 @@ const make = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const threadModelSelections = new Map<string, ModelSelection>();
|
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||||
|
|
||||||
const appendProviderFailureActivity = (input: {
|
const appendProviderFailureActivity = (input: {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
@@ -221,7 +192,10 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
createdAt: string,
|
createdAt: string,
|
||||||
options?: {
|
options?: {
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly provider?: ProviderKind;
|
||||||
|
readonly model?: string;
|
||||||
|
readonly modelOptions?: ProviderModelOptions;
|
||||||
|
readonly providerOptions?: ProviderStartOptions;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
@@ -231,25 +205,10 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const desiredRuntimeMode = thread.runtimeMode;
|
const desiredRuntimeMode = thread.runtimeMode;
|
||||||
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
|
const currentProvider: ProviderKind | undefined =
|
||||||
thread.session?.providerName,
|
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
|
||||||
)
|
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||||
? thread.session.providerName
|
const desiredModel = options?.model ?? thread.model;
|
||||||
: undefined;
|
|
||||||
const requestedModelSelection = options?.modelSelection;
|
|
||||||
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
|
|
||||||
if (
|
|
||||||
requestedModelSelection !== undefined &&
|
|
||||||
requestedModelSelection.provider !== threadProvider
|
|
||||||
) {
|
|
||||||
return yield* new ProviderAdapterRequestError({
|
|
||||||
provider: threadProvider,
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
|
||||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
|
||||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||||
thread,
|
thread,
|
||||||
projects: readModel.projects,
|
projects: readModel.projects,
|
||||||
@@ -266,9 +225,15 @@ const make = Effect.gen(function* () {
|
|||||||
}) =>
|
}) =>
|
||||||
providerService.startSession(threadId, {
|
providerService.startSession(threadId, {
|
||||||
threadId,
|
threadId,
|
||||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
...((input?.provider ?? preferredProvider)
|
||||||
|
? { provider: input?.provider ?? preferredProvider }
|
||||||
|
: {}),
|
||||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||||
modelSelection: desiredModelSelection,
|
...(desiredModel ? { model: desiredModel } : {}),
|
||||||
|
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||||
|
...(options?.providerOptions !== undefined
|
||||||
|
? { providerOptions: options.providerOptions }
|
||||||
|
: {}),
|
||||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||||
runtimeMode: desiredRuntimeMode,
|
runtimeMode: desiredRuntimeMode,
|
||||||
});
|
});
|
||||||
@@ -294,29 +259,16 @@ const make = Effect.gen(function* () {
|
|||||||
if (existingSessionThreadId) {
|
if (existingSessionThreadId) {
|
||||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||||
const providerChanged =
|
const providerChanged =
|
||||||
requestedModelSelection !== undefined &&
|
options?.provider !== undefined && options.provider !== currentProvider;
|
||||||
requestedModelSelection.provider !== currentProvider;
|
|
||||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||||
const sessionModelSwitch =
|
const sessionModelSwitch =
|
||||||
currentProvider === undefined
|
currentProvider === undefined
|
||||||
? "in-session"
|
? "in-session"
|
||||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||||
const modelChanged =
|
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||||
requestedModelSelection !== undefined &&
|
|
||||||
requestedModelSelection.model !== activeSession?.model;
|
|
||||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||||
const previousModelSelection = threadModelSelections.get(threadId);
|
|
||||||
const shouldRestartForModelSelectionChange =
|
|
||||||
currentProvider === "claudeAgent" &&
|
|
||||||
requestedModelSelection !== undefined &&
|
|
||||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
|
||||||
|
|
||||||
if (
|
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
|
||||||
!runtimeModeChanged &&
|
|
||||||
!providerChanged &&
|
|
||||||
!shouldRestartForModelChange &&
|
|
||||||
!shouldRestartForModelSelectionChange
|
|
||||||
) {
|
|
||||||
return existingSessionThreadId;
|
return existingSessionThreadId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,19 +280,19 @@ const make = Effect.gen(function* () {
|
|||||||
threadId,
|
threadId,
|
||||||
existingSessionThreadId,
|
existingSessionThreadId,
|
||||||
currentProvider,
|
currentProvider,
|
||||||
desiredProvider: desiredModelSelection.provider,
|
desiredProvider: options?.provider ?? currentProvider,
|
||||||
currentRuntimeMode: thread.session?.runtimeMode,
|
currentRuntimeMode: thread.session?.runtimeMode,
|
||||||
desiredRuntimeMode: thread.runtimeMode,
|
desiredRuntimeMode: thread.runtimeMode,
|
||||||
runtimeModeChanged,
|
runtimeModeChanged,
|
||||||
providerChanged,
|
providerChanged,
|
||||||
modelChanged,
|
modelChanged,
|
||||||
shouldRestartForModelChange,
|
shouldRestartForModelChange,
|
||||||
shouldRestartForModelSelectionChange,
|
|
||||||
hasResumeCursor: resumeCursor !== undefined,
|
hasResumeCursor: resumeCursor !== undefined,
|
||||||
});
|
});
|
||||||
const restartedSession = yield* startProviderSession(
|
const restartedSession = yield* startProviderSession({
|
||||||
resumeCursor !== undefined ? { resumeCursor } : undefined,
|
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||||
);
|
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||||
|
});
|
||||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||||
threadId,
|
threadId,
|
||||||
previousSessionId: existingSessionThreadId,
|
previousSessionId: existingSessionThreadId,
|
||||||
@@ -352,7 +304,9 @@ const make = Effect.gen(function* () {
|
|||||||
return restartedSession.threadId;
|
return restartedSession.threadId;
|
||||||
}
|
}
|
||||||
|
|
||||||
const startedSession = yield* startProviderSession(undefined);
|
const startedSession = yield* startProviderSession(
|
||||||
|
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||||
|
);
|
||||||
yield* bindSessionToThread(startedSession);
|
yield* bindSessionToThread(startedSession);
|
||||||
return startedSession.threadId;
|
return startedSession.threadId;
|
||||||
});
|
});
|
||||||
@@ -361,7 +315,10 @@ const make = Effect.gen(function* () {
|
|||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly messageText: string;
|
readonly messageText: string;
|
||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly provider?: ProviderKind;
|
||||||
|
readonly model?: string;
|
||||||
|
readonly modelOptions?: ProviderModelOptions;
|
||||||
|
readonly providerOptions?: ProviderStartOptions;
|
||||||
readonly interactionMode?: "default" | "plan";
|
readonly interactionMode?: "default" | "plan";
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
}) {
|
}) {
|
||||||
@@ -369,14 +326,15 @@ const make = Effect.gen(function* () {
|
|||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
yield* ensureSessionForThread(
|
if (input.providerOptions !== undefined) {
|
||||||
input.threadId,
|
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||||
input.createdAt,
|
|
||||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
|
||||||
);
|
|
||||||
if (input.modelSelection !== undefined) {
|
|
||||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
|
||||||
}
|
}
|
||||||
|
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||||
|
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||||
|
...(input.model !== undefined ? { model: input.model } : {}),
|
||||||
|
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||||
|
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||||
|
});
|
||||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||||
const normalizedAttachments = input.attachments ?? [];
|
const normalizedAttachments = input.attachments ?? [];
|
||||||
const activeSession = yield* providerService
|
const activeSession = yield* providerService
|
||||||
@@ -388,23 +346,14 @@ const make = Effect.gen(function* () {
|
|||||||
activeSession === undefined
|
activeSession === undefined
|
||||||
? "in-session"
|
? "in-session"
|
||||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||||
const requestedModelSelection =
|
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
|
||||||
const modelForTurn =
|
|
||||||
sessionModelSwitch === "unsupported"
|
|
||||||
? activeSession?.model !== undefined
|
|
||||||
? {
|
|
||||||
...requestedModelSelection,
|
|
||||||
model: activeSession.model,
|
|
||||||
}
|
|
||||||
: requestedModelSelection
|
|
||||||
: input.modelSelection;
|
|
||||||
|
|
||||||
yield* providerService.sendTurn({
|
yield* providerService.sendTurn({
|
||||||
threadId: input.threadId,
|
threadId: input.threadId,
|
||||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||||
|
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -413,6 +362,7 @@ const make = Effect.gen(function* () {
|
|||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly branch: string | null;
|
readonly branch: string | null;
|
||||||
readonly worktreePath: string | null;
|
readonly worktreePath: string | null;
|
||||||
|
readonly messageId: string;
|
||||||
readonly messageText: string;
|
readonly messageText: string;
|
||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
}) {
|
}) {
|
||||||
@@ -423,85 +373,57 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const thread = yield* resolveThread(input.threadId);
|
||||||
|
if (!thread) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userMessages = thread.messages.filter((message) => message.role === "user");
|
||||||
|
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const oldBranch = input.branch;
|
const oldBranch = input.branch;
|
||||||
const cwd = input.worktreePath;
|
const cwd = input.worktreePath;
|
||||||
const attachments = input.attachments ?? [];
|
const attachments = input.attachments ?? [];
|
||||||
yield* Effect.gen(function* () {
|
yield* textGeneration
|
||||||
const { textGenerationModelSelection: modelSelection } =
|
.generateBranchName({
|
||||||
yield* serverSettingsService.getSettings;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
|
||||||
cwd,
|
cwd,
|
||||||
message: input.messageText,
|
message: input.messageText,
|
||||||
...(attachments.length > 0 ? { attachments } : {}),
|
...(attachments.length > 0 ? { attachments } : {}),
|
||||||
modelSelection,
|
})
|
||||||
});
|
.pipe(
|
||||||
if (!generated) return;
|
Effect.catch((error) =>
|
||||||
|
Effect.logWarning(
|
||||||
|
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.flatMap((generated) => {
|
||||||
|
if (!generated) return Effect.void;
|
||||||
|
|
||||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||||
if (targetBranch === oldBranch) return;
|
if (targetBranch === oldBranch) return Effect.void;
|
||||||
|
|
||||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
return Effect.flatMap(
|
||||||
yield* orchestrationEngine.dispatch({
|
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||||
type: "thread.meta.update",
|
(renamed) =>
|
||||||
commandId: serverCommandId("worktree-branch-rename"),
|
orchestrationEngine.dispatch({
|
||||||
threadId: input.threadId,
|
type: "thread.meta.update",
|
||||||
branch: renamed.branch,
|
commandId: serverCommandId("worktree-branch-rename"),
|
||||||
worktreePath: cwd,
|
threadId: input.threadId,
|
||||||
});
|
branch: renamed.branch,
|
||||||
}).pipe(
|
worktreePath: cwd,
|
||||||
Effect.catchCause((cause) =>
|
}),
|
||||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
);
|
||||||
threadId: input.threadId,
|
|
||||||
cwd,
|
|
||||||
oldBranch,
|
|
||||||
cause: Cause.pretty(cause),
|
|
||||||
}),
|
}),
|
||||||
),
|
Effect.catchCause((cause) =>
|
||||||
);
|
Effect.logWarning(
|
||||||
});
|
"provider command reactor failed to generate or rename worktree branch",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
|
||||||
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
|
),
|
||||||
readonly threadId: ThreadId;
|
),
|
||||||
readonly cwd: string;
|
);
|
||||||
readonly messageText: string;
|
|
||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
|
||||||
readonly titleSeed?: string;
|
|
||||||
}) {
|
|
||||||
const attachments = input.attachments ?? [];
|
|
||||||
yield* Effect.gen(function* () {
|
|
||||||
const { textGenerationModelSelection: modelSelection } =
|
|
||||||
yield* serverSettingsService.getSettings;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: input.cwd,
|
|
||||||
message: input.messageText,
|
|
||||||
...(attachments.length > 0 ? { attachments } : {}),
|
|
||||||
modelSelection,
|
|
||||||
});
|
|
||||||
if (!generated) return;
|
|
||||||
|
|
||||||
const thread = yield* resolveThread(input.threadId);
|
|
||||||
if (!thread) return;
|
|
||||||
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* orchestrationEngine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: serverCommandId("thread-title-rename"),
|
|
||||||
threadId: input.threadId,
|
|
||||||
title: generated.title,
|
|
||||||
});
|
|
||||||
}).pipe(
|
|
||||||
Effect.catchCause((cause) =>
|
|
||||||
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
|
|
||||||
threadId: input.threadId,
|
|
||||||
cwd: input.cwd,
|
|
||||||
cause: Cause.pretty(cause),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||||
@@ -530,57 +452,30 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isFirstUserMessageTurn =
|
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
||||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
threadId: event.payload.threadId,
|
||||||
if (isFirstUserMessageTurn) {
|
branch: thread.branch,
|
||||||
const generationCwd =
|
worktreePath: thread.worktreePath,
|
||||||
resolveThreadWorkspaceCwd({
|
messageId: message.id,
|
||||||
thread,
|
messageText: message.text,
|
||||||
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
}) ?? process.cwd();
|
}).pipe(Effect.forkScoped);
|
||||||
const generationInput = {
|
|
||||||
messageText: message.text,
|
|
||||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
|
||||||
...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
|
|
||||||
};
|
|
||||||
|
|
||||||
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
branch: thread.branch,
|
|
||||||
worktreePath: thread.worktreePath,
|
|
||||||
...generationInput,
|
|
||||||
}).pipe(Effect.forkScoped);
|
|
||||||
|
|
||||||
if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {
|
|
||||||
yield* maybeGenerateThreadTitleForFirstTurn({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
cwd: generationCwd,
|
|
||||||
...generationInput,
|
|
||||||
}).pipe(Effect.forkScoped);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* sendTurnForThread({
|
yield* sendTurnForThread({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
messageText: message.text,
|
messageText: message.text,
|
||||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
...(event.payload.modelSelection !== undefined
|
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||||
? { modelSelection: event.payload.modelSelection }
|
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||||
|
...(event.payload.modelOptions !== undefined
|
||||||
|
? { modelOptions: event.payload.modelOptions }
|
||||||
|
: {}),
|
||||||
|
...(event.payload.providerOptions !== undefined
|
||||||
|
? { providerOptions: event.payload.providerOptions }
|
||||||
: {}),
|
: {}),
|
||||||
interactionMode: event.payload.interactionMode,
|
interactionMode: event.payload.interactionMode,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
}).pipe(
|
});
|
||||||
Effect.catchCause((cause) =>
|
|
||||||
appendProviderFailureActivity({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
kind: "provider.turn.start.failed",
|
|
||||||
summary: "Provider turn start failed",
|
|
||||||
detail: Cause.pretty(cause),
|
|
||||||
turnId: null,
|
|
||||||
createdAt: event.payload.createdAt,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const processTurnInterruptRequested = Effect.fnUntraced(function* (
|
const processTurnInterruptRequested = Effect.fnUntraced(function* (
|
||||||
@@ -639,9 +534,7 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
kind: "provider.approval.respond.failed",
|
kind: "provider.approval.respond.failed",
|
||||||
summary: "Provider approval response failed",
|
summary: "Provider approval response failed",
|
||||||
detail: isUnknownPendingApprovalRequestError(cause)
|
detail: Cause.pretty(cause),
|
||||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
|
||||||
: Cause.pretty(cause),
|
|
||||||
turnId: null,
|
turnId: null,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
requestId: event.payload.requestId,
|
requestId: event.payload.requestId,
|
||||||
@@ -685,9 +578,7 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
kind: "provider.user-input.respond.failed",
|
kind: "provider.user-input.respond.failed",
|
||||||
summary: "Provider user input response failed",
|
summary: "Provider user input response failed",
|
||||||
detail: isUnknownPendingUserInputRequestError(cause)
|
detail: Cause.pretty(cause),
|
||||||
? stalePendingRequestDetail("user-input", event.payload.requestId)
|
|
||||||
: Cause.pretty(cause),
|
|
||||||
turnId: null,
|
turnId: null,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
requestId: event.payload.requestId,
|
requestId: event.payload.requestId,
|
||||||
@@ -724,40 +615,41 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
|
const processDomainEvent = (event: ProviderIntentEvent) =>
|
||||||
event: ProviderIntentEvent,
|
Effect.gen(function* () {
|
||||||
) {
|
switch (event.type) {
|
||||||
switch (event.type) {
|
case "thread.runtime-mode-set": {
|
||||||
case "thread.runtime-mode-set": {
|
const thread = yield* resolveThread(event.payload.threadId);
|
||||||
const thread = yield* resolveThread(event.payload.threadId);
|
if (!thread?.session || thread.session.status === "stopped") {
|
||||||
if (!thread?.session || thread.session.status === "stopped") {
|
return;
|
||||||
|
}
|
||||||
|
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||||
|
yield* ensureSessionForThread(
|
||||||
|
event.payload.threadId,
|
||||||
|
event.occurredAt,
|
||||||
|
cachedProviderOptions !== undefined
|
||||||
|
? { providerOptions: cachedProviderOptions }
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
case "thread.turn-start-requested":
|
||||||
yield* ensureSessionForThread(
|
yield* processTurnStartRequested(event);
|
||||||
event.payload.threadId,
|
return;
|
||||||
event.occurredAt,
|
case "thread.turn-interrupt-requested":
|
||||||
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
yield* processTurnInterruptRequested(event);
|
||||||
);
|
return;
|
||||||
return;
|
case "thread.approval-response-requested":
|
||||||
|
yield* processApprovalResponseRequested(event);
|
||||||
|
return;
|
||||||
|
case "thread.user-input-response-requested":
|
||||||
|
yield* processUserInputResponseRequested(event);
|
||||||
|
return;
|
||||||
|
case "thread.session-stop-requested":
|
||||||
|
yield* processSessionStopRequested(event);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
case "thread.turn-start-requested":
|
});
|
||||||
yield* processTurnStartRequested(event);
|
|
||||||
return;
|
|
||||||
case "thread.turn-interrupt-requested":
|
|
||||||
yield* processTurnInterruptRequested(event);
|
|
||||||
return;
|
|
||||||
case "thread.approval-response-requested":
|
|
||||||
yield* processApprovalResponseRequested(event);
|
|
||||||
return;
|
|
||||||
case "thread.user-input-response-requested":
|
|
||||||
yield* processUserInputResponseRequested(event);
|
|
||||||
return;
|
|
||||||
case "thread.session-stop-requested":
|
|
||||||
yield* processSessionStopRequested(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const processDomainEventSafely = (event: ProviderIntentEvent) =>
|
const processDomainEventSafely = (event: ProviderIntentEvent) =>
|
||||||
processDomainEvent(event).pipe(
|
processDomainEvent(event).pipe(
|
||||||
@@ -774,24 +666,22 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
const worker = yield* makeDrainableWorker(processDomainEventSafely);
|
const worker = yield* makeDrainableWorker(processDomainEventSafely);
|
||||||
|
|
||||||
const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
|
const start: ProviderCommandReactorShape["start"] = Effect.forkScoped(
|
||||||
const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
|
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||||
if (
|
if (
|
||||||
event.type === "thread.runtime-mode-set" ||
|
event.type !== "thread.runtime-mode-set" &&
|
||||||
event.type === "thread.turn-start-requested" ||
|
event.type !== "thread.turn-start-requested" &&
|
||||||
event.type === "thread.turn-interrupt-requested" ||
|
event.type !== "thread.turn-interrupt-requested" &&
|
||||||
event.type === "thread.approval-response-requested" ||
|
event.type !== "thread.approval-response-requested" &&
|
||||||
event.type === "thread.user-input-response-requested" ||
|
event.type !== "thread.user-input-response-requested" &&
|
||||||
event.type === "thread.session-stop-requested"
|
event.type !== "thread.session-stop-requested"
|
||||||
) {
|
) {
|
||||||
return yield* worker.enqueue(event);
|
return Effect.void;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
yield* Effect.forkScoped(
|
return worker.enqueue(event);
|
||||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
|
}),
|
||||||
);
|
).pipe(Effect.asVoid);
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
start,
|
start,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,121 +0,0 @@
|
|||||||
import { Effect, FileSystem, Path } from "effect";
|
|
||||||
import {
|
|
||||||
type ClientOrchestrationCommand,
|
|
||||||
type OrchestrationCommand,
|
|
||||||
OrchestrationDispatchCommandError,
|
|
||||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
|
|
||||||
import { ServerConfig } from "../config";
|
|
||||||
import { parseBase64DataUrl } from "../imageMime";
|
|
||||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
|
|
||||||
|
|
||||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const serverConfig = yield* ServerConfig;
|
|
||||||
const workspacePaths = yield* WorkspacePaths;
|
|
||||||
|
|
||||||
const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
|
|
||||||
workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new OrchestrationDispatchCommandError({
|
|
||||||
message: cause.message,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (command.type === "project.create") {
|
|
||||||
return {
|
|
||||||
...command,
|
|
||||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
|
||||||
} satisfies OrchestrationCommand;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
|
|
||||||
return {
|
|
||||||
...command,
|
|
||||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
|
||||||
} satisfies OrchestrationCommand;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (command.type !== "thread.turn.start") {
|
|
||||||
return command as OrchestrationCommand;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalizedAttachments = yield* Effect.forEach(
|
|
||||||
command.message.attachments,
|
|
||||||
(attachment) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
|
||||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
|
||||||
return yield* new OrchestrationDispatchCommandError({
|
|
||||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const bytes = Buffer.from(parsed.base64, "base64");
|
|
||||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
|
||||||
return yield* new OrchestrationDispatchCommandError({
|
|
||||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const attachmentId = createAttachmentId(command.threadId);
|
|
||||||
if (!attachmentId) {
|
|
||||||
return yield* new OrchestrationDispatchCommandError({
|
|
||||||
message: "Failed to create a safe attachment id.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const persistedAttachment = {
|
|
||||||
type: "image" as const,
|
|
||||||
id: attachmentId,
|
|
||||||
name: attachment.name,
|
|
||||||
mimeType: parsed.mimeType.toLowerCase(),
|
|
||||||
sizeBytes: bytes.byteLength,
|
|
||||||
};
|
|
||||||
|
|
||||||
const attachmentPath = resolveAttachmentPath({
|
|
||||||
attachmentsDir: serverConfig.attachmentsDir,
|
|
||||||
attachment: persistedAttachment,
|
|
||||||
});
|
|
||||||
if (!attachmentPath) {
|
|
||||||
return yield* new OrchestrationDispatchCommandError({
|
|
||||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
() =>
|
|
||||||
new OrchestrationDispatchCommandError({
|
|
||||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
() =>
|
|
||||||
new OrchestrationDispatchCommandError({
|
|
||||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return persistedAttachment;
|
|
||||||
}),
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...command,
|
|
||||||
message: {
|
|
||||||
...command.message,
|
|
||||||
attachments: normalizedAttachments,
|
|
||||||
},
|
|
||||||
} satisfies OrchestrationCommand;
|
|
||||||
});
|
|
||||||
@@ -3,12 +3,10 @@ import {
|
|||||||
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
|
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
|
||||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
|
||||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
|
||||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||||
@@ -28,12 +26,10 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem
|
|||||||
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||||
|
|
||||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
|
||||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
|
||||||
|
|
||||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export interface CheckpointReactorShape {
|
|||||||
* Consumes both orchestration-domain and provider-runtime events via an
|
* Consumes both orchestration-domain and provider-runtime events via an
|
||||||
* internal queue.
|
* internal queue.
|
||||||
*/
|
*/
|
||||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves when the internal processing queue is empty and idle.
|
* Resolves when the internal processing queue is empty and idle.
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export interface OrchestrationReactorShape {
|
|||||||
* The returned effect must be run in a scope so all worker fibers can be
|
* The returned effect must be run in a scope so all worker fibers can be
|
||||||
* finalized on shutdown.
|
* finalized on shutdown.
|
||||||
*/
|
*/
|
||||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export interface ProviderCommandReactorShape {
|
|||||||
* Filters orchestration domain events to provider-intent types before
|
* Filters orchestration domain events to provider-intent types before
|
||||||
* processing.
|
* processing.
|
||||||
*/
|
*/
|
||||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves when the internal processing queue is empty and idle.
|
* Resolves when the internal processing queue is empty and idle.
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export interface ProviderRuntimeIngestionShape {
|
|||||||
* Uses an internal queue and continues after non-interrupt failures by
|
* Uses an internal queue and continues after non-interrupt failures by
|
||||||
* logging warnings.
|
* logging warnings.
|
||||||
*/
|
*/
|
||||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves when the internal processing queue is empty and idle.
|
* Resolves when the internal processing queue is empty and idle.
|
||||||
|
|||||||
@@ -28,10 +28,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
id: ProjectId.makeUnsafe("project-a"),
|
id: ProjectId.makeUnsafe("project-a"),
|
||||||
title: "Project A",
|
title: "Project A",
|
||||||
workspaceRoot: "/tmp/project-a",
|
workspaceRoot: "/tmp/project-a",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -41,10 +38,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
id: ProjectId.makeUnsafe("project-b"),
|
id: ProjectId.makeUnsafe("project-b"),
|
||||||
title: "Project B",
|
title: "Project B",
|
||||||
workspaceRoot: "/tmp/project-b",
|
workspaceRoot: "/tmp/project-b",
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -56,17 +50,13 @@ const readModel: OrchestrationReadModel = {
|
|||||||
id: ThreadId.makeUnsafe("thread-1"),
|
id: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: ProjectId.makeUnsafe("project-a"),
|
projectId: ProjectId.makeUnsafe("project-a"),
|
||||||
title: "Thread A",
|
title: "Thread A",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
archivedAt: null,
|
|
||||||
latestTurn: null,
|
latestTurn: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
@@ -79,17 +69,13 @@ const readModel: OrchestrationReadModel = {
|
|||||||
id: ThreadId.makeUnsafe("thread-2"),
|
id: ThreadId.makeUnsafe("thread-2"),
|
||||||
projectId: ProjectId.makeUnsafe("project-b"),
|
projectId: ProjectId.makeUnsafe("project-b"),
|
||||||
title: "Thread B",
|
title: "Thread B",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
archivedAt: null,
|
|
||||||
latestTurn: null,
|
latestTurn: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
@@ -158,10 +144,7 @@ describe("commandInvariants", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||||
projectId: ProjectId.makeUnsafe("project-a"),
|
projectId: ProjectId.makeUnsafe("project-a"),
|
||||||
title: "new",
|
title: "new",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -182,10 +165,7 @@ describe("commandInvariants", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: ProjectId.makeUnsafe("project-a"),
|
projectId: ProjectId.makeUnsafe("project-a"),
|
||||||
title: "dup",
|
title: "dup",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
|
|||||||
@@ -88,44 +88,6 @@ export function requireThread(input: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function requireThreadArchived(input: {
|
|
||||||
readonly readModel: OrchestrationReadModel;
|
|
||||||
readonly command: OrchestrationCommand;
|
|
||||||
readonly threadId: ThreadId;
|
|
||||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
|
||||||
return requireThread(input).pipe(
|
|
||||||
Effect.flatMap((thread) =>
|
|
||||||
thread.archivedAt !== null
|
|
||||||
? Effect.succeed(thread)
|
|
||||||
: Effect.fail(
|
|
||||||
invariantError(
|
|
||||||
input.command.type,
|
|
||||||
`Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function requireThreadNotArchived(input: {
|
|
||||||
readonly readModel: OrchestrationReadModel;
|
|
||||||
readonly command: OrchestrationCommand;
|
|
||||||
readonly threadId: ThreadId;
|
|
||||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
|
||||||
return requireThread(input).pipe(
|
|
||||||
Effect.flatMap((thread) =>
|
|
||||||
thread.archivedAt === null
|
|
||||||
? Effect.succeed(thread)
|
|
||||||
: Effect.fail(
|
|
||||||
invariantError(
|
|
||||||
input.command.type,
|
|
||||||
`Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function requireThreadAbsent(input: {
|
export function requireThreadAbsent(input: {
|
||||||
readonly readModel: OrchestrationReadModel;
|
readonly readModel: OrchestrationReadModel;
|
||||||
readonly command: OrchestrationCommand;
|
readonly command: OrchestrationCommand;
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-scripts"),
|
projectId: asProjectId("project-scripts"),
|
||||||
title: "Scripts",
|
title: "Scripts",
|
||||||
workspaceRoot: "/tmp/scripts",
|
workspaceRoot: "/tmp/scripts",
|
||||||
defaultModelSelection: null,
|
defaultModel: null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Project",
|
title: "Project",
|
||||||
workspaceRoot: "/tmp/project",
|
workspaceRoot: "/tmp/project",
|
||||||
defaultModelSelection: null,
|
defaultModel: null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -136,10 +136,7 @@ describe("decider project scripts", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -162,10 +159,10 @@ describe("decider project scripts", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: {
|
provider: "codex",
|
||||||
provider: "codex",
|
model: "gpt-5.3-codex",
|
||||||
model: "gpt-5.3-codex",
|
modelOptions: {
|
||||||
options: {
|
codex: {
|
||||||
reasoningEffort: "high",
|
reasoningEffort: "high",
|
||||||
fastMode: true,
|
fastMode: true,
|
||||||
},
|
},
|
||||||
@@ -188,13 +185,14 @@ describe("decider project scripts", () => {
|
|||||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
||||||
expect(turnStartEvent.payload).toMatchObject({
|
expect(turnStartEvent.payload).toMatchObject({
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
messageId: asMessageId("message-user-1"),
|
messageId: asMessageId("message-user-1"),
|
||||||
modelSelection: {
|
provider: "codex",
|
||||||
provider: "codex",
|
model: "gpt-5.3-codex",
|
||||||
model: "gpt-5.3-codex",
|
modelOptions: {
|
||||||
options: {
|
codex: {
|
||||||
reasoningEffort: "high",
|
reasoningEffort: "high",
|
||||||
fastMode: true,
|
fastMode: true,
|
||||||
},
|
},
|
||||||
@@ -222,7 +220,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Project",
|
title: "Project",
|
||||||
workspaceRoot: "/tmp/project",
|
workspaceRoot: "/tmp/project",
|
||||||
defaultModelSelection: null,
|
defaultModel: null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -245,10 +243,7 @@ describe("decider project scripts", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -304,7 +299,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Project",
|
title: "Project",
|
||||||
workspaceRoot: "/tmp/project",
|
workspaceRoot: "/tmp/project",
|
||||||
defaultModelSelection: null,
|
defaultModel: null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -327,10 +322,7 @@ describe("decider project scripts", () => {
|
|||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ import {
|
|||||||
requireProject,
|
requireProject,
|
||||||
requireProjectAbsent,
|
requireProjectAbsent,
|
||||||
requireThread,
|
requireThread,
|
||||||
requireThreadArchived,
|
|
||||||
requireThreadAbsent,
|
requireThreadAbsent,
|
||||||
requireThreadNotArchived,
|
|
||||||
} from "./commandInvariants.ts";
|
} from "./commandInvariants.ts";
|
||||||
|
|
||||||
const nowIso = () => new Date().toISOString();
|
const nowIso = () => new Date().toISOString();
|
||||||
|
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
|
||||||
|
|
||||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||||
aggregateKind: "thread",
|
aggregateKind: "thread",
|
||||||
@@ -77,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
projectId: command.projectId,
|
projectId: command.projectId,
|
||||||
title: command.title,
|
title: command.title,
|
||||||
workspaceRoot: command.workspaceRoot,
|
workspaceRoot: command.workspaceRoot,
|
||||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
defaultModel: command.defaultModel ?? null,
|
||||||
scripts: [],
|
scripts: [],
|
||||||
createdAt: command.createdAt,
|
createdAt: command.createdAt,
|
||||||
updatedAt: command.createdAt,
|
updatedAt: command.createdAt,
|
||||||
@@ -104,9 +104,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
projectId: command.projectId,
|
projectId: command.projectId,
|
||||||
...(command.title !== undefined ? { title: command.title } : {}),
|
...(command.title !== undefined ? { title: command.title } : {}),
|
||||||
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
||||||
...(command.defaultModelSelection !== undefined
|
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
|
||||||
? { defaultModelSelection: command.defaultModelSelection }
|
|
||||||
: {}),
|
|
||||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||||
updatedAt: occurredAt,
|
updatedAt: occurredAt,
|
||||||
},
|
},
|
||||||
@@ -158,7 +156,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
threadId: command.threadId,
|
threadId: command.threadId,
|
||||||
projectId: command.projectId,
|
projectId: command.projectId,
|
||||||
title: command.title,
|
title: command.title,
|
||||||
modelSelection: command.modelSelection,
|
model: command.model,
|
||||||
runtimeMode: command.runtimeMode,
|
runtimeMode: command.runtimeMode,
|
||||||
interactionMode: command.interactionMode,
|
interactionMode: command.interactionMode,
|
||||||
branch: command.branch,
|
branch: command.branch,
|
||||||
@@ -191,51 +189,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
case "thread.archive": {
|
|
||||||
yield* requireThreadNotArchived({
|
|
||||||
readModel,
|
|
||||||
command,
|
|
||||||
threadId: command.threadId,
|
|
||||||
});
|
|
||||||
const occurredAt = nowIso();
|
|
||||||
return {
|
|
||||||
...withEventBase({
|
|
||||||
aggregateKind: "thread",
|
|
||||||
aggregateId: command.threadId,
|
|
||||||
occurredAt,
|
|
||||||
commandId: command.commandId,
|
|
||||||
}),
|
|
||||||
type: "thread.archived",
|
|
||||||
payload: {
|
|
||||||
threadId: command.threadId,
|
|
||||||
archivedAt: occurredAt,
|
|
||||||
updatedAt: occurredAt,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
case "thread.unarchive": {
|
|
||||||
yield* requireThreadArchived({
|
|
||||||
readModel,
|
|
||||||
command,
|
|
||||||
threadId: command.threadId,
|
|
||||||
});
|
|
||||||
const occurredAt = nowIso();
|
|
||||||
return {
|
|
||||||
...withEventBase({
|
|
||||||
aggregateKind: "thread",
|
|
||||||
aggregateId: command.threadId,
|
|
||||||
occurredAt,
|
|
||||||
commandId: command.commandId,
|
|
||||||
}),
|
|
||||||
type: "thread.unarchived",
|
|
||||||
payload: {
|
|
||||||
threadId: command.threadId,
|
|
||||||
updatedAt: occurredAt,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
case "thread.meta.update": {
|
case "thread.meta.update": {
|
||||||
yield* requireThread({
|
yield* requireThread({
|
||||||
readModel,
|
readModel,
|
||||||
@@ -254,9 +207,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
payload: {
|
payload: {
|
||||||
threadId: command.threadId,
|
threadId: command.threadId,
|
||||||
...(command.title !== undefined ? { title: command.title } : {}),
|
...(command.title !== undefined ? { title: command.title } : {}),
|
||||||
...(command.modelSelection !== undefined
|
...(command.model !== undefined ? { model: command.model } : {}),
|
||||||
? { modelSelection: command.modelSelection }
|
|
||||||
: {}),
|
|
||||||
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
||||||
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
||||||
updatedAt: occurredAt,
|
updatedAt: occurredAt,
|
||||||
@@ -311,35 +262,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "thread.turn.start": {
|
case "thread.turn.start": {
|
||||||
const targetThread = yield* requireThread({
|
yield* requireThread({
|
||||||
readModel,
|
readModel,
|
||||||
command,
|
command,
|
||||||
threadId: command.threadId,
|
threadId: command.threadId,
|
||||||
});
|
});
|
||||||
const sourceProposedPlan = command.sourceProposedPlan;
|
|
||||||
const sourceThread = sourceProposedPlan
|
|
||||||
? yield* requireThread({
|
|
||||||
readModel,
|
|
||||||
command,
|
|
||||||
threadId: sourceProposedPlan.threadId,
|
|
||||||
})
|
|
||||||
: null;
|
|
||||||
const sourcePlan =
|
|
||||||
sourceProposedPlan && sourceThread
|
|
||||||
? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
|
|
||||||
: null;
|
|
||||||
if (sourceProposedPlan && !sourcePlan) {
|
|
||||||
return yield* new OrchestrationCommandInvariantError({
|
|
||||||
commandType: command.type,
|
|
||||||
detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
|
|
||||||
return yield* new OrchestrationCommandInvariantError({
|
|
||||||
commandType: command.type,
|
|
||||||
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||||
...withEventBase({
|
...withEventBase({
|
||||||
aggregateKind: "thread",
|
aggregateKind: "thread",
|
||||||
@@ -372,13 +299,19 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
payload: {
|
payload: {
|
||||||
threadId: command.threadId,
|
threadId: command.threadId,
|
||||||
messageId: command.message.messageId,
|
messageId: command.message.messageId,
|
||||||
...(command.modelSelection !== undefined
|
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||||
? { modelSelection: command.modelSelection }
|
...(command.model !== undefined ? { model: command.model } : {}),
|
||||||
|
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||||
|
...(command.providerOptions !== undefined
|
||||||
|
? { providerOptions: command.providerOptions }
|
||||||
: {}),
|
: {}),
|
||||||
...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
|
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||||
runtimeMode: targetThread.runtimeMode,
|
runtimeMode:
|
||||||
interactionMode: targetThread.interactionMode,
|
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
command.runtimeMode,
|
||||||
|
interactionMode:
|
||||||
|
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||||
|
command.interactionMode,
|
||||||
createdAt: command.createdAt,
|
createdAt: command.createdAt,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Loaded 100 of 381 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user