Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
387a577e3c |
No files matched your search
@@ -93,8 +93,6 @@ Examples:
|
|||||||
|
|
||||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
A known environment may or may not know the target `environmentId` before first successful connect.
|
||||||
|
|
||||||
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
|
|
||||||
|
|
||||||
### AccessEndpoint
|
### AccessEndpoint
|
||||||
|
|
||||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
An `AccessEndpoint` is one concrete way to reach a known environment.
|
||||||
@@ -110,67 +108,6 @@ A single environment may have many endpoints:
|
|||||||
|
|
||||||
The environment stays the same. Only the access path changes.
|
The environment stays the same. Only the access path changes.
|
||||||
|
|
||||||
### AdvertisedEndpoint
|
|
||||||
|
|
||||||
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
|
|
||||||
|
|
||||||
`AdvertisedEndpoint` is deliberately narrower than the full access model:
|
|
||||||
|
|
||||||
- it describes a concrete HTTP and WebSocket base URL pair
|
|
||||||
- it can mark the endpoint as default, available, or unavailable
|
|
||||||
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
|
|
||||||
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
|
|
||||||
|
|
||||||
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
|
|
||||||
|
|
||||||
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
|
|
||||||
|
|
||||||
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
|
|
||||||
|
|
||||||
When no user default is saved, endpoint selection should prefer:
|
|
||||||
|
|
||||||
1. endpoints compatible with the hosted HTTPS app
|
|
||||||
2. explicitly default endpoints
|
|
||||||
3. non-loopback endpoints
|
|
||||||
4. loopback endpoints only for same-machine clients
|
|
||||||
|
|
||||||
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
|
|
||||||
|
|
||||||
### Endpoint providers
|
|
||||||
|
|
||||||
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
|
|
||||||
|
|
||||||
The provider boundary is intentionally outside the core environment model:
|
|
||||||
|
|
||||||
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
|
|
||||||
- providers discover or synthesize endpoints
|
|
||||||
- providers return normalized `AdvertisedEndpoint` records
|
|
||||||
- the UI and pairing logic select from those records without knowing provider-specific commands
|
|
||||||
|
|
||||||
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
|
|
||||||
|
|
||||||
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
|
|
||||||
|
|
||||||
### Hosted pairing request
|
|
||||||
|
|
||||||
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
|
||||||
```
|
|
||||||
|
|
||||||
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
|
|
||||||
|
|
||||||
Important constraints:
|
|
||||||
|
|
||||||
- the hosted app does not proxy HTTP or WebSocket traffic
|
|
||||||
- the backend must still be reachable directly from the browser
|
|
||||||
- HTTPS pages can only connect to HTTPS/WSS backends
|
|
||||||
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
|
|
||||||
- the token belongs in the URL hash so it is not sent to the hosted app origin
|
|
||||||
|
|
||||||
### RepositoryIdentity
|
### RepositoryIdentity
|
||||||
|
|
||||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
||||||
@@ -214,8 +151,6 @@ Benefits:
|
|||||||
- no client-specific process management required
|
- no client-specific process management required
|
||||||
- best fit for hosted or self-managed remote T3 deployments
|
- best fit for hosted or self-managed remote T3 deployments
|
||||||
|
|
||||||
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
|
|
||||||
|
|
||||||
### 2. Tunneled WebSocket access
|
### 2. Tunneled WebSocket access
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
@@ -235,8 +170,6 @@ This is especially useful when:
|
|||||||
- mobile must reach a desktop-hosted environment
|
- mobile must reach a desktop-hosted environment
|
||||||
- a machine should be reachable without exposing raw LAN or public ports
|
- a machine should be reachable without exposing raw LAN or public ports
|
||||||
|
|
||||||
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
|
|
||||||
|
|
||||||
### 3. Desktop-managed SSH access
|
### 3. Desktop-managed SSH access
|
||||||
|
|
||||||
SSH is an access and launch helper, not a separate environment type.
|
SSH is an access and launch helper, not a separate environment type.
|
||||||
@@ -252,8 +185,6 @@ After that, the renderer should still connect using an ordinary WebSocket URL ag
|
|||||||
|
|
||||||
This keeps the renderer transport model consistent with every other access method.
|
This keeps the renderer transport model consistent with every other access method.
|
||||||
|
|
||||||
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
|
|
||||||
|
|
||||||
## Launch methods
|
## Launch methods
|
||||||
|
|
||||||
Launch methods answer a different question:
|
Launch methods answer a different question:
|
||||||
@@ -296,15 +227,6 @@ The recommended T3 flow is:
|
|||||||
4. Desktop establishes local port forwarding.
|
4. Desktop establishes local port forwarding.
|
||||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
||||||
|
|
||||||
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
|
|
||||||
|
|
||||||
Failure handling should be explicit:
|
|
||||||
|
|
||||||
- SSH authentication failure should surface before any environment is saved
|
|
||||||
- remote launch failure should include remote logs or the launcher command output when available
|
|
||||||
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
|
|
||||||
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
|
|
||||||
|
|
||||||
### 3. Client-managed local publish
|
### 3. Client-managed local publish
|
||||||
|
|
||||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
||||||
@@ -345,8 +267,6 @@ T3 already supports a WebSocket auth token on the server. That should become a f
|
|||||||
|
|
||||||
For publicly reachable environments, authenticated access should be treated as required.
|
For publicly reachable environments, authenticated access should be treated as required.
|
||||||
|
|
||||||
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
|
|
||||||
|
|
||||||
## Relationship to Zed
|
## Relationship to Zed
|
||||||
|
|
||||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||||
|
|||||||
@@ -30,6 +30,3 @@ github:Yash-Singh1
|
|||||||
github:eggfriedrice24
|
github:eggfriedrice24
|
||||||
github:Ymit24
|
github:Ymit24
|
||||||
github:shivamhwp
|
github:shivamhwp
|
||||||
github:jappyjan
|
|
||||||
github:justsomelegs
|
|
||||||
github:UtkarshUsername
|
|
||||||
@@ -30,7 +30,7 @@ jobs:
|
|||||||
check_changes:
|
check_changes:
|
||||||
name: Check for changes since last nightly
|
name: Check for changes since last nightly
|
||||||
if: github.event_name == 'schedule'
|
if: github.event_name == 'schedule'
|
||||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
runs-on: ubuntu-24.04
|
||||||
outputs:
|
outputs:
|
||||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||||
steps:
|
steps:
|
||||||
@@ -376,16 +376,13 @@ jobs:
|
|||||||
registry-url: https://registry.npmjs.org
|
registry-url: https://registry.npmjs.org
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
run: bun install --frozen-lockfile
|
||||||
|
|
||||||
- name: Align package versions to release version
|
- name: Align package versions to release version
|
||||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||||
|
|
||||||
- name: Build web package
|
|
||||||
run: bun --filter=@t3tools/web run build
|
|
||||||
|
|
||||||
- name: Build CLI package
|
- name: Build CLI package
|
||||||
run: bun --filter=t3 run build
|
run: bun run build --filter=@t3tools/web --filter=t3
|
||||||
|
|
||||||
- name: Publish CLI package
|
- name: Publish CLI package
|
||||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||||
@@ -394,7 +391,7 @@ jobs:
|
|||||||
name: Publish GitHub Release
|
name: Publish GitHub Release
|
||||||
needs: [preflight, build, publish_cli]
|
needs: [preflight, build, publish_cli]
|
||||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- id: app_token
|
- id: app_token
|
||||||
@@ -421,7 +418,7 @@ jobs:
|
|||||||
node-version-file: package.json
|
node-version-file: package.json
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
run: bun install --frozen-lockfile
|
||||||
|
|
||||||
- name: Download all desktop artifacts
|
- name: Download all desktop artifacts
|
||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
@@ -555,7 +552,7 @@ jobs:
|
|||||||
node-version-file: package.json
|
node-version-file: package.json
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
run: bun install --frozen-lockfile
|
||||||
|
|
||||||
- id: update_versions
|
- id: update_versions
|
||||||
name: Update version strings
|
name: Update version strings
|
||||||
@@ -565,7 +562,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Format package.json files
|
- name: Format package.json files
|
||||||
if: steps.update_versions.outputs.changed == 'true'
|
if: steps.update_versions.outputs.changed == 'true'
|
||||||
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||||
|
|
||||||
- name: Refresh lockfile
|
- name: Refresh lockfile
|
||||||
if: steps.update_versions.outputs.changed == 'true'
|
if: steps.update_versions.outputs.changed == 'true'
|
||||||
@@ -588,60 +585,3 @@ jobs:
|
|||||||
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"
|
||||||
git push origin HEAD:main
|
git push origin HEAD:main
|
||||||
|
|
||||||
announce_discord:
|
|
||||||
name: Announce release on Discord
|
|
||||||
if: |
|
|
||||||
always() && !cancelled() &&
|
|
||||||
needs.preflight.result == 'success' &&
|
|
||||||
needs.release.result == 'success' &&
|
|
||||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
|
||||||
needs: [preflight, release, finalize]
|
|
||||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
ref: ${{ needs.preflight.outputs.ref }}
|
|
||||||
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: oven-sh/setup-bun@v2
|
|
||||||
with:
|
|
||||||
bun-version-file: package.json
|
|
||||||
|
|
||||||
- name: Setup Node
|
|
||||||
uses: actions/setup-node@v6
|
|
||||||
with:
|
|
||||||
node-version-file: package.json
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
|
||||||
|
|
||||||
- name: Announce prerelease on Discord
|
|
||||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
|
||||||
continue-on-error: true
|
|
||||||
env:
|
|
||||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
|
||||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
|
||||||
run: |
|
|
||||||
node scripts/notify-discord-release.ts prerelease \
|
|
||||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
|
||||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
|
||||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
|
||||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
|
||||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
|
||||||
|
|
||||||
- name: Announce latest release on Discord
|
|
||||||
if: needs.preflight.outputs.make_latest == 'true'
|
|
||||||
continue-on-error: true
|
|
||||||
env:
|
|
||||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
|
||||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
|
||||||
run: |
|
|
||||||
node scripts/notify-discord-release.ts latest \
|
|
||||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
|
||||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
|
||||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
|
||||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
|
||||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
|
||||||
@@ -22,4 +22,3 @@ apps/web/src/components/__screenshots__
|
|||||||
__screenshots__/
|
__screenshots__/
|
||||||
.tanstack
|
.tanstack
|
||||||
squashfs-root/
|
squashfs-root/
|
||||||
.vercel
|
|
||||||
@@ -1,350 +0,0 @@
|
|||||||
# Remote Endpoints and Hosted Static App Plan
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
|
|
||||||
Make remote access feel first-class while keeping the free DIY path open.
|
|
||||||
|
|
||||||
The immediate product goal is:
|
|
||||||
|
|
||||||
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
|
|
||||||
- users can generate a hosted pairing link for `app.t3.codes`
|
|
||||||
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
|
|
||||||
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
|
|
||||||
|
|
||||||
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
|
|
||||||
|
|
||||||
## Current State
|
|
||||||
|
|
||||||
Already present or in progress:
|
|
||||||
|
|
||||||
- Server auth distinguishes bootstrap credentials from session credentials.
|
|
||||||
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
|
|
||||||
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
|
|
||||||
- Remote environment WebSocket connections use a short-lived WebSocket token.
|
|
||||||
- Pairing URLs can carry tokens in the URL fragment.
|
|
||||||
- Hosted `/pair?host=...#token=...` can add a saved environment.
|
|
||||||
- Hosted static startup can avoid assuming the page origin is the backend.
|
|
||||||
|
|
||||||
Main gaps:
|
|
||||||
|
|
||||||
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
|
|
||||||
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
|
|
||||||
- Tailscale/MagicDNS endpoints are not detected or surfaced.
|
|
||||||
- Hosted-static empty/offline states are still thin.
|
|
||||||
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
|
|
||||||
|
|
||||||
## Core Decision: Add `AdvertisedEndpoint`
|
|
||||||
|
|
||||||
Add a new first-class contract instead of extending the environment descriptor.
|
|
||||||
|
|
||||||
### Why not extend `ExecutionEnvironmentDescriptor`
|
|
||||||
|
|
||||||
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- environment id
|
|
||||||
- label
|
|
||||||
- platform
|
|
||||||
- server version
|
|
||||||
- capabilities
|
|
||||||
|
|
||||||
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- loopback URL
|
|
||||||
- LAN URL
|
|
||||||
- Tailscale IP URL
|
|
||||||
- MagicDNS/Serve URL
|
|
||||||
- manual URL
|
|
||||||
- future T3 Tunnel URL
|
|
||||||
- browser compatibility and exposure level
|
|
||||||
|
|
||||||
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
|
|
||||||
|
|
||||||
### Target Contract
|
|
||||||
|
|
||||||
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
type AdvertisedEndpointProvider =
|
|
||||||
| "loopback"
|
|
||||||
| "lan"
|
|
||||||
| "tailscale-ip"
|
|
||||||
| "tailscale-magicdns"
|
|
||||||
| "manual"
|
|
||||||
| "t3-tunnel";
|
|
||||||
|
|
||||||
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
|
|
||||||
|
|
||||||
type AdvertisedEndpointCompatibility = {
|
|
||||||
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
|
|
||||||
desktopApp: "compatible" | "unknown";
|
|
||||||
};
|
|
||||||
|
|
||||||
type AdvertisedEndpoint = {
|
|
||||||
id: string;
|
|
||||||
provider: AdvertisedEndpointProvider;
|
|
||||||
label: string;
|
|
||||||
httpBaseUrl: string;
|
|
||||||
wsBaseUrl: string;
|
|
||||||
visibility: AdvertisedEndpointVisibility;
|
|
||||||
compatibility: AdvertisedEndpointCompatibility;
|
|
||||||
source: "server" | "desktop" | "user";
|
|
||||||
status: "available" | "unavailable" | "unknown";
|
|
||||||
isDefault?: boolean;
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
|
|
||||||
|
|
||||||
## HTTP/WS and HTTPS/WSS Readiness
|
|
||||||
|
|
||||||
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
|
|
||||||
|
|
||||||
What is ready:
|
|
||||||
|
|
||||||
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
|
|
||||||
- Saved environments store both HTTP and WebSocket base URLs.
|
|
||||||
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
|
|
||||||
- WebSocket connections can use a dynamically issued `wsToken`.
|
|
||||||
- Server CORS support exists for browser remote auth endpoints.
|
|
||||||
|
|
||||||
What is not solved by code alone:
|
|
||||||
|
|
||||||
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
|
|
||||||
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
|
|
||||||
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
|
|
||||||
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
|
|
||||||
|
|
||||||
Policy:
|
|
||||||
|
|
||||||
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
|
|
||||||
- Mark endpoint compatibility at the product layer.
|
|
||||||
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Endpoint Sources
|
|
||||||
|
|
||||||
Endpoint records can come from several providers:
|
|
||||||
|
|
||||||
1. **Server runtime**
|
|
||||||
- headless bind host and port
|
|
||||||
- server-known explicit advertised host config
|
|
||||||
|
|
||||||
2. **Desktop shell**
|
|
||||||
- loopback backend URL
|
|
||||||
- LAN exposure state
|
|
||||||
- network interface discovery
|
|
||||||
- Tailscale CLI/status discovery
|
|
||||||
|
|
||||||
3. **User configuration**
|
|
||||||
- manually added hostnames
|
|
||||||
- preferred endpoint labels
|
|
||||||
- hidden/disabled endpoints
|
|
||||||
|
|
||||||
4. **Future cloud provider**
|
|
||||||
- T3 Tunnel endpoint
|
|
||||||
- billing/account status
|
|
||||||
- tunnel lifecycle state
|
|
||||||
|
|
||||||
### Endpoint Registry
|
|
||||||
|
|
||||||
Create a central runtime registry:
|
|
||||||
|
|
||||||
- `packages/contracts/src/remoteAccess.ts`
|
|
||||||
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
|
|
||||||
- `apps/server/src/remoteAccess/*` for server/headless endpoints
|
|
||||||
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
|
|
||||||
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
|
|
||||||
|
|
||||||
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
|
|
||||||
|
|
||||||
### Pairing Link Generation
|
|
||||||
|
|
||||||
Move hosted pairing link generation to endpoint-driven input:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
buildHostedPairingUrl({
|
|
||||||
endpoint: AdvertisedEndpoint,
|
|
||||||
token,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
Generated URL:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
|
|
||||||
```
|
|
||||||
|
|
||||||
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
|
|
||||||
|
|
||||||
## Phase 1: Endpoint Abstraction
|
|
||||||
|
|
||||||
### Goals
|
|
||||||
|
|
||||||
- Centralize URL normalization, protocol derivation, and compatibility checks.
|
|
||||||
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
|
|
||||||
- Preserve all current remote behavior.
|
|
||||||
|
|
||||||
### Tasks
|
|
||||||
|
|
||||||
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
|
|
||||||
2. Add shared helpers:
|
|
||||||
- normalize HTTP base URL
|
|
||||||
- derive WebSocket base URL
|
|
||||||
- classify loopback/private/LAN/Tailscale/public host
|
|
||||||
- classify hosted HTTPS compatibility
|
|
||||||
3. Add server endpoint discovery:
|
|
||||||
- loopback endpoint
|
|
||||||
- configured non-loopback endpoint
|
|
||||||
- explicit advertised host override
|
|
||||||
4. Add desktop endpoint discovery:
|
|
||||||
- local loopback
|
|
||||||
- LAN exposure endpoint
|
|
||||||
- endpoint status labels
|
|
||||||
5. Add WebSocket/API method or existing config field for endpoint snapshots.
|
|
||||||
6. Refactor settings connections UI:
|
|
||||||
- render endpoint rows
|
|
||||||
- endpoint picker for pairing link copy
|
|
||||||
- show compatibility warnings
|
|
||||||
7. Refactor hosted link builder to accept endpoint records.
|
|
||||||
8. Add tests for URL normalization and compatibility classification.
|
|
||||||
|
|
||||||
### Acceptance Criteria
|
|
||||||
|
|
||||||
- Existing LAN/network access UI still works.
|
|
||||||
- Pairing links are generated from endpoint records.
|
|
||||||
- Loopback endpoints never produce hosted pairing links silently.
|
|
||||||
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
|
|
||||||
- No remote environment runtime changes are required for existing saved environments.
|
|
||||||
|
|
||||||
## Phase 2: BYO Tailscale/MagicDNS
|
|
||||||
|
|
||||||
### Goals
|
|
||||||
|
|
||||||
- Detect free DIY Tailscale reachability.
|
|
||||||
- Surface Tailscale endpoints as normal advertised endpoints.
|
|
||||||
- Keep users in control of their own tailnet.
|
|
||||||
|
|
||||||
### Tasks
|
|
||||||
|
|
||||||
1. Detect Tailscale IPs from network interfaces:
|
|
||||||
- IPv4 `100.64.0.0/10`
|
|
||||||
- mark as `provider: "tailscale-ip"`
|
|
||||||
2. Add optional desktop-side `tailscale status --json` discovery:
|
|
||||||
- MagicDNS hostname
|
|
||||||
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
|
|
||||||
- graceful failure if CLI is missing
|
|
||||||
3. Add manual Tailscale endpoint override:
|
|
||||||
- hostname
|
|
||||||
- label
|
|
||||||
- preferred/default flag
|
|
||||||
4. Show Tailscale endpoint rows in settings:
|
|
||||||
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
|
|
||||||
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
|
|
||||||
5. Generate pairing links using selected Tailscale endpoint.
|
|
||||||
6. Document DIY setup:
|
|
||||||
- local desktop-to-desktop over Tailscale
|
|
||||||
- hosted app requirements
|
|
||||||
- why HTTPS matters
|
|
||||||
|
|
||||||
### Acceptance Criteria
|
|
||||||
|
|
||||||
- A machine on Tailscale shows a Tailscale endpoint without paid features.
|
|
||||||
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
|
|
||||||
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
|
|
||||||
- Tailscale is optional and never required for regular LAN/loopback use.
|
|
||||||
|
|
||||||
## Phase 3: Hosted Static App Completion
|
|
||||||
|
|
||||||
### Goals
|
|
||||||
|
|
||||||
- `app.t3.codes` works as a real client shell.
|
|
||||||
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
|
|
||||||
|
|
||||||
### Tasks
|
|
||||||
|
|
||||||
1. Finish hosted-static root behavior:
|
|
||||||
- no primary backend required
|
|
||||||
- saved environment hydration before initial routing decisions
|
|
||||||
- first saved environment selected as active
|
|
||||||
2. Add hosted empty state:
|
|
||||||
- no saved environments
|
|
||||||
- paste pairing URL
|
|
||||||
- add host + token
|
|
||||||
3. Add offline saved environment UI:
|
|
||||||
- last connected
|
|
||||||
- reconnect
|
|
||||||
- remove
|
|
||||||
- copy/add alternate endpoint
|
|
||||||
4. Audit primary-backend assumptions:
|
|
||||||
- command palette
|
|
||||||
- settings pages
|
|
||||||
- server config atom defaults
|
|
||||||
- keybindings
|
|
||||||
- provider/model lists
|
|
||||||
- update/desktop-only affordances
|
|
||||||
5. Add route tests for:
|
|
||||||
- hosted `/pair?host=...#token=...`
|
|
||||||
- hosted root with no saved environments
|
|
||||||
- hosted root with saved environment
|
|
||||||
- primary backend unavailable but saved environment present
|
|
||||||
6. Add deployment hardening:
|
|
||||||
- SPA fallback
|
|
||||||
- strict CSP
|
|
||||||
- no third-party scripts
|
|
||||||
- no query token logging
|
|
||||||
- disable or hide source maps in production if needed
|
|
||||||
7. Add browser error messages:
|
|
||||||
- mixed content
|
|
||||||
- unreachable backend
|
|
||||||
- CORS failure
|
|
||||||
- certificate failure
|
|
||||||
|
|
||||||
### Acceptance Criteria
|
|
||||||
|
|
||||||
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
|
|
||||||
- A saved environment can be used without any backend at `app.t3.codes`.
|
|
||||||
- Offline machines show a useful state instead of a generic boot error.
|
|
||||||
- HTTP endpoints are still supported in desktop/native/local contexts.
|
|
||||||
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
|
|
||||||
|
|
||||||
## Phase 4: Future T3 Tunnel Provider
|
|
||||||
|
|
||||||
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
|
|
||||||
|
|
||||||
Future tunnel provider responsibilities:
|
|
||||||
|
|
||||||
- create endpoint with `provider: "t3-tunnel"`
|
|
||||||
- surface tunnel status
|
|
||||||
- provide stable HTTPS URL
|
|
||||||
- use existing backend pairing/session auth
|
|
||||||
- never bypass server auth
|
|
||||||
|
|
||||||
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
|
|
||||||
|
|
||||||
## Security Checklist
|
|
||||||
|
|
||||||
- Pairing tokens are short-lived and one-time.
|
|
||||||
- Generated hosted pairing links put tokens in the fragment.
|
|
||||||
- The backend remains the authorization boundary.
|
|
||||||
- Endpoint discovery never disables backend auth.
|
|
||||||
- Hosted app does not silently downgrade to HTTP.
|
|
||||||
- Tunnel/public endpoints require explicit user action.
|
|
||||||
- Client sessions remain revocable.
|
|
||||||
- Endpoint URLs and request logs must avoid recording pairing tokens.
|
|
||||||
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
|
|
||||||
|
|
||||||
## Verification
|
|
||||||
|
|
||||||
Each implementation PR should run:
|
|
||||||
|
|
||||||
- `bun fmt`
|
|
||||||
- `bun lint`
|
|
||||||
- `bun typecheck`
|
|
||||||
- focused tests for changed backend/web behavior
|
|
||||||
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
|
|
||||||
|
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
# Version Control Phase 1: VCS Driver Foundation
|
|
||||||
|
|
||||||
## Goal
|
|
||||||
|
|
||||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
|
||||||
|
|
||||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
|
||||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
|
||||||
- Add server services under `apps/server/src/vcs`:
|
|
||||||
- `Services/VcsDriver.ts`
|
|
||||||
- `Services/VcsRepositoryResolver.ts`
|
|
||||||
- `Services/VcsProcess.ts`
|
|
||||||
- `Layers/GitVcsDriver.ts`
|
|
||||||
- `errors.ts`
|
|
||||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
|
||||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
|
||||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
|
||||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
|
||||||
- No T3 Review implementation yet.
|
|
||||||
- No broad UI redesign.
|
|
||||||
|
|
||||||
## Driver Model
|
|
||||||
|
|
||||||
Use provider-neutral nouns in new APIs:
|
|
||||||
|
|
||||||
- `VcsDriver`: local repository mechanics.
|
|
||||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
|
||||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
|
||||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
|
||||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
|
||||||
|
|
||||||
The initial driver capabilities should be explicit:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface VcsDriverCapabilities {
|
|
||||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
|
||||||
readonly supportsWorktrees: boolean;
|
|
||||||
readonly supportsBookmarks: boolean;
|
|
||||||
readonly supportsAtomicSnapshot: boolean;
|
|
||||||
readonly supportsPushDefaultRemote: boolean;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
|
||||||
|
|
||||||
- `detectRepository(cwd)`
|
|
||||||
- `status(cwd, options)`
|
|
||||||
- `listRefs(cwd, query/pagination)`
|
|
||||||
- `checkoutRef(cwd, ref)`
|
|
||||||
- `createRef(cwd, ref, from?)`
|
|
||||||
- `createWorkspace(cwd, ref, path?)`
|
|
||||||
- `removeWorkspace(path)`
|
|
||||||
- `prepareChangeContext(cwd, filePaths?)`
|
|
||||||
- `createChange(cwd, message, options)`
|
|
||||||
- `push(cwd, target?)`
|
|
||||||
- `rangeContext(cwd, base, head)`
|
|
||||||
- `listWorkspaceFiles(cwd, options)`
|
|
||||||
|
|
||||||
## Effect Process Layer
|
|
||||||
|
|
||||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
|
||||||
|
|
||||||
Requirements:
|
|
||||||
|
|
||||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
|
||||||
- Support scoped acquisition/release for long-running commands and interruption.
|
|
||||||
- Support bounded stdout/stderr collection with truncation markers.
|
|
||||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
|
||||||
- Support stdin.
|
|
||||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
|
||||||
- Stream output lines to progress callbacks as Effects.
|
|
||||||
- Return a typed `ProcessOutput` value for successful execution.
|
|
||||||
- Fail with typed errors, not generic thrown exceptions.
|
|
||||||
|
|
||||||
Errors should be schema-backed tagged classes, for example:
|
|
||||||
|
|
||||||
- `VcsProcessSpawnError`
|
|
||||||
- `VcsProcessExitError`
|
|
||||||
- `VcsProcessTimeoutError`
|
|
||||||
- `VcsOutputDecodeError`
|
|
||||||
- `VcsRepositoryDetectionError`
|
|
||||||
- `VcsUnsupportedOperationError`
|
|
||||||
|
|
||||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
|
||||||
|
|
||||||
## Git Driver Rewrite
|
|
||||||
|
|
||||||
Rewrite Git support against `VcsProcess`.
|
|
||||||
|
|
||||||
Carry forward current behavior from:
|
|
||||||
|
|
||||||
- `apps/server/src/git/Layers/GitCore.ts`
|
|
||||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
|
||||||
- current Git status/branch/worktree contracts
|
|
||||||
|
|
||||||
But split the implementation into smaller modules:
|
|
||||||
|
|
||||||
- command execution and hardening config
|
|
||||||
- repository detection
|
|
||||||
- status parsing
|
|
||||||
- branch/ref parsing
|
|
||||||
- worktree operations
|
|
||||||
- commit/range context generation
|
|
||||||
- push/pull operations
|
|
||||||
|
|
||||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
|
||||||
|
|
||||||
## Freshness and Local Caching
|
|
||||||
|
|
||||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
|
||||||
|
|
||||||
Treat these as live/local:
|
|
||||||
|
|
||||||
- repository detection for the active cwd
|
|
||||||
- working copy dirty state
|
|
||||||
- staged/unstaged/untracked file summaries
|
|
||||||
- current branch/bookmark/change name
|
|
||||||
- local branch/bookmark lists
|
|
||||||
- local worktree/workspace lists
|
|
||||||
|
|
||||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
|
||||||
|
|
||||||
Treat these as cached or explicit-refresh only:
|
|
||||||
|
|
||||||
- remote tracking branch refreshes
|
|
||||||
- ahead/behind counts that require network fetches
|
|
||||||
- default branch discovery from a remote provider
|
|
||||||
- remote branch lists beyond locally known refs
|
|
||||||
|
|
||||||
The VCS driver should expose freshness metadata with status results:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface VcsFreshness {
|
|
||||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
|
||||||
readonly observedAt: string;
|
|
||||||
readonly expiresAt?: string;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
|
||||||
|
|
||||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
|
||||||
|
|
||||||
- key by resolved repository root plus VCS kind
|
|
||||||
- invalidate on cwd/root changes and workspace mutation operations
|
|
||||||
- use short TTLs for local status caches when filesystem events are unavailable
|
|
||||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
|
||||||
|
|
||||||
## Cutover Policy
|
|
||||||
|
|
||||||
Prefer direct migration and deletion over compatibility wrappers.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
|
||||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
|
||||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
|
||||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
|
||||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
|
||||||
- No new feature work may depend on transitional modules.
|
|
||||||
|
|
||||||
Expected transitional candidates:
|
|
||||||
|
|
||||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
|
||||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
|
||||||
|
|
||||||
- non-repository detection
|
|
||||||
- status for clean/dirty/untracked/staged states
|
|
||||||
- branch/ref list with pagination
|
|
||||||
- checkout/create branch
|
|
||||||
- worktree create/remove
|
|
||||||
- commit context generation with file filters
|
|
||||||
- commit creation with hook progress events
|
|
||||||
- push behavior against a local bare remote
|
|
||||||
- status polling does not perform remote network refresh by default
|
|
||||||
- concurrent duplicate status requests are coalesced
|
|
||||||
- bounded output/truncation
|
|
||||||
- timeout/interruption
|
|
||||||
- typed error shape for command failure and missing executable
|
|
||||||
|
|
||||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
|
||||||
|
|
||||||
## Migration Steps
|
|
||||||
|
|
||||||
1. Add `vcs` contracts and tagged errors.
|
|
||||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
|
||||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
|
||||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
|
||||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
|
||||||
6. Move commit/range/push callers to the VCS service directly.
|
|
||||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
|
||||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
|
||||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
|
||||||
- New Git implementation does not depend on `processRunner.ts`.
|
|
||||||
- New errors are typed and inspectable by tests.
|
|
||||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
|
||||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
|
||||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
|
||||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
|
||||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
# Version Control Phase 2: Source Control Provider Foundation
|
|
||||||
|
|
||||||
## Goal
|
|
||||||
|
|
||||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
|
||||||
|
|
||||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
|
||||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
|
||||||
- Add server services under `apps/server/src/sourceControl`:
|
|
||||||
- `Services/SourceControlProvider.ts`
|
|
||||||
- `Services/SourceControlProviderRegistry.ts`
|
|
||||||
- `Services/SourceControlProcess.ts`
|
|
||||||
- `Layers/GitHubSourceControlProvider.ts`
|
|
||||||
- `errors.ts`
|
|
||||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
|
||||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
|
||||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
|
||||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
|
||||||
- No in-app review UI yet.
|
|
||||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
|
||||||
|
|
||||||
## Provider Model
|
|
||||||
|
|
||||||
Use provider-neutral names:
|
|
||||||
|
|
||||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
|
||||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
|
||||||
- `ChangeRequestThread`: review or discussion thread.
|
|
||||||
- `ChangeRequestComment`: top-level or inline comment.
|
|
||||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
|
||||||
|
|
||||||
Core provider operations:
|
|
||||||
|
|
||||||
- `detectRemote(remoteUrl)`
|
|
||||||
- `checkAuth(cwd)`
|
|
||||||
- `getRepository(cwd | remoteUrl)`
|
|
||||||
- `getDefaultTargetRef(repository)`
|
|
||||||
- `listChangeRequests(repository, filters)`
|
|
||||||
- `getChangeRequest(repository, reference)`
|
|
||||||
- `createChangeRequest(repository, input)`
|
|
||||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
|
||||||
- `getCloneUrls(repository)`
|
|
||||||
|
|
||||||
Review-facing operations should be designed now, even if unimplemented:
|
|
||||||
|
|
||||||
- `listReviewThreads(changeRequest)`
|
|
||||||
- `createReviewComment(changeRequest, input)`
|
|
||||||
- `replyToReviewThread(thread, input)`
|
|
||||||
- `resolveReviewThread(thread)`
|
|
||||||
- `submitReview(changeRequest, input)`
|
|
||||||
|
|
||||||
Each operation should be guarded by capabilities:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface SourceControlProviderCapabilities {
|
|
||||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
|
||||||
readonly supportsCreateChangeRequest: boolean;
|
|
||||||
readonly supportsCheckoutChangeRequest: boolean;
|
|
||||||
readonly supportsReviewThreads: boolean;
|
|
||||||
readonly supportsInlineComments: boolean;
|
|
||||||
readonly supportsDraftChangeRequests: boolean;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Provider Registry
|
|
||||||
|
|
||||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
- Detection should be pure where possible and testable without spawning CLIs.
|
|
||||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
|
||||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
|
||||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
|
||||||
|
|
||||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
|
||||||
|
|
||||||
## Rate Limits and Provider Caching
|
|
||||||
|
|
||||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
|
||||||
|
|
||||||
Default behavior:
|
|
||||||
|
|
||||||
- Pure URL/remote parsing is always live because it is local.
|
|
||||||
- Provider detection from local remotes is live-local.
|
|
||||||
- Authentication checks are cached.
|
|
||||||
- Repository metadata is cached.
|
|
||||||
- Default branch metadata is cached.
|
|
||||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
|
||||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
|
||||||
- Create/update operations invalidate affected cache keys immediately after success.
|
|
||||||
|
|
||||||
The provider API should make freshness explicit:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface SourceControlFreshness {
|
|
||||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
|
||||||
readonly observedAt: string;
|
|
||||||
readonly expiresAt?: string;
|
|
||||||
readonly stale?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ProviderRefreshPolicy =
|
|
||||||
| "cache-first"
|
|
||||||
| "stale-while-revalidate"
|
|
||||||
| "force-refresh"
|
|
||||||
| "local-only";
|
|
||||||
```
|
|
||||||
|
|
||||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
|
||||||
|
|
||||||
Use Effect `Cache` for provider data:
|
|
||||||
|
|
||||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
|
||||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
|
||||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
|
||||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
|
||||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
|
||||||
|
|
||||||
Provider drivers should surface rate-limit signals when available:
|
|
||||||
|
|
||||||
- remaining quota
|
|
||||||
- reset time
|
|
||||||
- retry-after duration
|
|
||||||
- whether the limit is primary, secondary/abuse, or unknown
|
|
||||||
|
|
||||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
|
||||||
|
|
||||||
Avoid rate-limit footguns:
|
|
||||||
|
|
||||||
- no provider calls from render loops or fast status polling
|
|
||||||
- no listing all PRs/MRs across all repos to infer one branch state
|
|
||||||
- no silent GitHub fallback for unknown providers
|
|
||||||
- no unbounded cache cardinality for branch names or free-form search queries
|
|
||||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
|
||||||
|
|
||||||
## GitHub Provider Rewrite
|
|
||||||
|
|
||||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
|
||||||
|
|
||||||
Carry forward behavior from:
|
|
||||||
|
|
||||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
|
||||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
|
||||||
- `apps/server/src/git/githubPullRequests.ts`
|
|
||||||
- GitHub-specific `GitManager` PR paths
|
|
||||||
|
|
||||||
Implementation requirements:
|
|
||||||
|
|
||||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
|
||||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
|
||||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
|
||||||
- Keep stdout/stderr bounded.
|
|
||||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
|
||||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
|
||||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
|
||||||
|
|
||||||
## GitManager Cutover
|
|
||||||
|
|
||||||
Refactor `GitManager` so it coordinates three independent services:
|
|
||||||
|
|
||||||
- `VcsDriver` for local repository mechanics.
|
|
||||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
|
||||||
- `TextGeneration` for message/body generation.
|
|
||||||
|
|
||||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
|
||||||
|
|
||||||
The Commit + PR flow should become:
|
|
||||||
|
|
||||||
1. Resolve VCS repository and local status.
|
|
||||||
2. Resolve source-control provider from remotes.
|
|
||||||
3. Generate commit content through the existing text generation service.
|
|
||||||
4. Create local change through `VcsDriver`.
|
|
||||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
|
||||||
6. Generate change-request title/body.
|
|
||||||
7. Create the change request through `SourceControlProvider`.
|
|
||||||
|
|
||||||
## Cutover Policy
|
|
||||||
|
|
||||||
This phase should aggressively remove old GitHub-specific internals.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
|
||||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
|
||||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
|
||||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
|
||||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
|
||||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
|
||||||
|
|
||||||
## GitLab and Azure Readiness
|
|
||||||
|
|
||||||
Use the triaged references as implementation inputs, not merge targets:
|
|
||||||
|
|
||||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
|
||||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
|
||||||
|
|
||||||
The abstraction should let Phase 3 add:
|
|
||||||
|
|
||||||
- `GitLabSourceControlProvider` using `glab`.
|
|
||||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
|
||||||
|
|
||||||
No provider should need to edit GitHub code to join the registry.
|
|
||||||
|
|
||||||
## T3 Review Design Constraint
|
|
||||||
|
|
||||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
|
||||||
|
|
||||||
That means contracts should include stable IDs and enough metadata for:
|
|
||||||
|
|
||||||
- file-level diffs
|
|
||||||
- inline review threads
|
|
||||||
- resolved/unresolved state
|
|
||||||
- top-level discussion comments
|
|
||||||
- pending review submission
|
|
||||||
- provider URL back-links
|
|
||||||
|
|
||||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
Add tests at three levels:
|
|
||||||
|
|
||||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
|
||||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
|
||||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
|
||||||
|
|
||||||
Required cases:
|
|
||||||
|
|
||||||
- GitHub PR URL, number, and branch-ish references.
|
|
||||||
- GitLab MR URL/reference parsing.
|
|
||||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
|
||||||
- unknown provider returns unsupported-operation errors.
|
|
||||||
- missing CLI and auth failures produce distinct typed errors.
|
|
||||||
- invalid CLI JSON fails at decode boundary with useful context.
|
|
||||||
|
|
||||||
## Migration Steps
|
|
||||||
|
|
||||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
|
||||||
2. Add shared remote/reference parser helpers and tests.
|
|
||||||
3. Add `SourceControlProcess` and provider errors.
|
|
||||||
4. Add provider registry with GitHub-only registration.
|
|
||||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
|
||||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
|
||||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
|
||||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
|
||||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
|
||||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
|
||||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
|
||||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
|
||||||
- Unknown/unsupported providers fail explicitly and visibly.
|
|
||||||
- GitHub command execution does not depend on `processRunner.ts`.
|
|
||||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
|
||||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
|
||||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
|
||||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
|
||||||
@@ -10,5 +10,3 @@
|
|||||||
8. `08-precommit-format-and-lint.md`
|
8. `08-precommit-format-and-lint.md`
|
||||||
9. `09-event-state-test-expansion.md`
|
9. `09-event-state-test-expansion.md`
|
||||||
10. `10-unify-process-session-abstraction.md`
|
10. `10-unify-process-session-abstraction.md`
|
||||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
|
||||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
# T3 Code
|
# T3 Code
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
> T3 Code currently supports Codex and Claude.
|
||||||
> Install and authenticate at least one provider before use:
|
> Install and authenticate at least one provider before use:
|
||||||
>
|
>
|
||||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
> - Claude: install Claude Code and run `claude auth login`
|
||||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
|
||||||
|
|
||||||
### Run without installing
|
### Run without installing
|
||||||
|
|
||||||
|
|||||||
@@ -22,41 +22,9 @@ If you are already running the desktop app and want to make it reachable from ot
|
|||||||
|
|
||||||
1. Open **Settings** → **Connections**.
|
1. Open **Settings** → **Connections**.
|
||||||
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
||||||
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
|
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
|
||||||
4. Use **Create Link** to generate a pairing link you can share with another device.
|
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||||
|
|
||||||
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
|
|
||||||
|
|
||||||
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
|
|
||||||
available. You can set another endpoint as the default from the expanded endpoint list.
|
|
||||||
|
|
||||||
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
|
|
||||||
automatically.
|
|
||||||
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
|
|
||||||
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
|
|
||||||
|
|
||||||
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
|
|
||||||
|
|
||||||
### Tailscale Endpoints
|
|
||||||
|
|
||||||
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
|
|
||||||
|
|
||||||
Depending on your Tailscale setup, this may include:
|
|
||||||
|
|
||||||
- the machine's `100.x.y.z` Tailnet IP
|
|
||||||
- a MagicDNS name
|
|
||||||
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
|
|
||||||
|
|
||||||
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
|
|
||||||
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
|
|
||||||
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
|
|
||||||
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
|
|
||||||
Serve to proxy HTTPS traffic to the local backend.
|
|
||||||
|
|
||||||
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
|
|
||||||
|
|
||||||
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
|
|
||||||
|
|
||||||
### Option 2: Headless Server (CLI)
|
### Option 2: Headless Server (CLI)
|
||||||
|
|
||||||
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
||||||
@@ -79,42 +47,14 @@ From there, connect from another device in either of these ways:
|
|||||||
- scan the QR code on your phone
|
- scan the QR code on your phone
|
||||||
- in the desktop app, enter the full pairing URL
|
- in the desktop app, enter the full pairing URL
|
||||||
- in the desktop app, enter the host and token separately
|
- in the desktop app, enter the host and token separately
|
||||||
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
|
|
||||||
|
|
||||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
||||||
|
|
||||||
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx t3 serve --tailscale-serve
|
|
||||||
```
|
|
||||||
|
|
||||||
By default this configures Tailscale Serve on HTTPS port 443 and advertises
|
|
||||||
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
|
|
||||||
```
|
|
||||||
|
|
||||||
> Note
|
> Note
|
||||||
> The GUIs do not currently support adding projects on remote environments.
|
> The GUIs do not currently support adding projects on remote environments.
|
||||||
> For now, use `t3 project ...` on the server machine instead.
|
> For now, use `t3 project ...` on the server machine instead.
|
||||||
> Full GUI support for remote project management is coming soon.
|
> Full GUI support for remote project management is coming soon.
|
||||||
|
|
||||||
### Option 3: Desktop-Managed SSH Launch
|
|
||||||
|
|
||||||
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
|
|
||||||
|
|
||||||
1. Open **Settings** → **Connections**.
|
|
||||||
2. Under **Remote Environments**, choose **Add environment**.
|
|
||||||
3. Select the SSH launch flow.
|
|
||||||
4. Enter the SSH target, such as `[email protected]`.
|
|
||||||
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
|
|
||||||
|
|
||||||
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
|
|
||||||
|
|
||||||
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
|
|
||||||
|
|
||||||
## How Pairing Works
|
## How Pairing Works
|
||||||
|
|
||||||
The remote device does not need a long-lived secret up front.
|
The remote device does not need a long-lived secret up front.
|
||||||
@@ -127,20 +67,6 @@ Instead:
|
|||||||
|
|
||||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||||
|
|
||||||
## Hosted Web App Pairing
|
|
||||||
|
|
||||||
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
|
||||||
```
|
|
||||||
|
|
||||||
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
|
|
||||||
|
|
||||||
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
|
|
||||||
|
|
||||||
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
|
|
||||||
|
|
||||||
## Managing Access Later
|
## Managing Access Later
|
||||||
|
|
||||||
Use `t3 auth` to manage access after the initial pairing flow.
|
Use `t3 auth` to manage access after the initial pairing flow.
|
||||||
@@ -158,5 +84,4 @@ Use `t3 auth --help` and the nested subcommand help pages for the full reference
|
|||||||
- Treat pairing URLs and pairing tokens like passwords.
|
- Treat pairing URLs and pairing tokens like passwords.
|
||||||
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
||||||
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
||||||
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
|
|
||||||
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@t3tools/desktop",
|
"name": "@t3tools/desktop",
|
||||||
"version": "0.0.22",
|
"version": "0.0.20",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist-electron/main.cjs",
|
"main": "dist-electron/main.cjs",
|
||||||
@@ -15,17 +15,13 @@
|
|||||||
"smoke-test": "node scripts/smoke-test.mjs"
|
"smoke-test": "node scripts/smoke-test.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@effect/platform-node": "catalog:",
|
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"electron": "40.9.3",
|
"electron": "40.6.0",
|
||||||
"electron-updater": "^6.6.2"
|
"electron-updater": "^6.6.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@t3tools/client-runtime": "workspace:*",
|
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
"@t3tools/shared": "workspace:*",
|
"@t3tools/shared": "workspace:*",
|
||||||
"@t3tools/ssh": "workspace:*",
|
|
||||||
"@t3tools/tailscale": "workspace:*",
|
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"effect-acp": "workspace:*",
|
"effect-acp": "workspace:*",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
|
|||||||
@@ -49,14 +49,10 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const clientSettings: ClientSettings = {
|
const clientSettings: ClientSettings = {
|
||||||
autoOpenPlanSidebar: false,
|
|
||||||
confirmThreadArchive: true,
|
confirmThreadArchive: true,
|
||||||
confirmThreadDelete: false,
|
confirmThreadDelete: false,
|
||||||
dismissedProviderUpdateNotificationKeys: [],
|
|
||||||
diffIgnoreWhitespace: true,
|
|
||||||
diffWordWrap: true,
|
diffWordWrap: true,
|
||||||
favorites: [],
|
favorites: [],
|
||||||
providerModelPreferences: {},
|
|
||||||
sidebarProjectGroupingMode: "repository_path",
|
sidebarProjectGroupingMode: "repository_path",
|
||||||
sidebarProjectGroupingOverrides: {
|
sidebarProjectGroupingOverrides: {
|
||||||
"environment-1:/tmp/project-a": "separate",
|
"environment-1:/tmp/project-a": "separate",
|
||||||
@@ -73,12 +69,6 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
|||||||
wsBaseUrl: "wss://remote.example.com/",
|
wsBaseUrl: "wss://remote.example.com/",
|
||||||
createdAt: "2026-04-09T00:00:00.000Z",
|
createdAt: "2026-04-09T00:00:00.000Z",
|
||||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||||
desktopSsh: {
|
|
||||||
alias: "devbox",
|
|
||||||
hostname: "devbox.example.com",
|
|
||||||
username: "julius",
|
|
||||||
port: 22,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("clientPersistence", () => {
|
describe("clientPersistence", () => {
|
||||||
|
|||||||
@@ -57,12 +57,6 @@ function isPersistedSavedEnvironmentStorageRecord(
|
|||||||
typeof value.wsBaseUrl === "string" &&
|
typeof value.wsBaseUrl === "string" &&
|
||||||
typeof value.createdAt === "string" &&
|
typeof value.createdAt === "string" &&
|
||||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
||||||
(value.desktopSsh === undefined ||
|
|
||||||
(Predicate.isObject(value.desktopSsh) &&
|
|
||||||
typeof value.desktopSsh.alias === "string" &&
|
|
||||||
typeof value.desktopSsh.hostname === "string" &&
|
|
||||||
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
|
|
||||||
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
|
|
||||||
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -83,7 +77,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
|
|||||||
function toPersistedSavedEnvironmentRecord(
|
function toPersistedSavedEnvironmentRecord(
|
||||||
record: PersistedSavedEnvironmentStorageRecord,
|
record: PersistedSavedEnvironmentStorageRecord,
|
||||||
): PersistedSavedEnvironmentRecord {
|
): PersistedSavedEnvironmentRecord {
|
||||||
const nextRecord = {
|
return {
|
||||||
environmentId: record.environmentId,
|
environmentId: record.environmentId,
|
||||||
label: record.label,
|
label: record.label,
|
||||||
httpBaseUrl: record.httpBaseUrl,
|
httpBaseUrl: record.httpBaseUrl,
|
||||||
@@ -91,7 +85,6 @@ function toPersistedSavedEnvironmentRecord(
|
|||||||
createdAt: record.createdAt,
|
createdAt: record.createdAt,
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
lastConnectedAt: record.lastConnectedAt,
|
||||||
};
|
};
|
||||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||||
@@ -141,7 +134,6 @@ export function writeSavedEnvironmentRegistry(
|
|||||||
wsBaseUrl: record.wsBaseUrl,
|
wsBaseUrl: record.wsBaseUrl,
|
||||||
createdAt: record.createdAt,
|
createdAt: record.createdAt,
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
lastConnectedAt: record.lastConnectedAt,
|
||||||
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
|
|
||||||
encryptedBearerToken,
|
encryptedBearerToken,
|
||||||
}
|
}
|
||||||
: record;
|
: record;
|
||||||
@@ -197,7 +189,7 @@ export function writeSavedEnvironmentSecret(input: {
|
|||||||
const encryptedBearerToken = input.secretStorage
|
const encryptedBearerToken = input.secretStorage
|
||||||
.encryptString(input.secret)
|
.encryptString(input.secret)
|
||||||
.toString("base64");
|
.toString("base64");
|
||||||
const nextRecord = {
|
return {
|
||||||
environmentId: record.environmentId,
|
environmentId: record.environmentId,
|
||||||
label: record.label,
|
label: record.label,
|
||||||
httpBaseUrl: record.httpBaseUrl,
|
httpBaseUrl: record.httpBaseUrl,
|
||||||
@@ -205,8 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
|
|||||||
createdAt: record.createdAt,
|
createdAt: record.createdAt,
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
lastConnectedAt: record.lastConnectedAt,
|
||||||
encryptedBearerToken,
|
encryptedBearerToken,
|
||||||
};
|
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
|
||||||
}),
|
}),
|
||||||
} satisfies SavedEnvironmentRegistryDocument);
|
} satisfies SavedEnvironmentRegistryDocument);
|
||||||
return found;
|
return found;
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
readDesktopSettings,
|
readDesktopSettings,
|
||||||
resolveDefaultDesktopSettings,
|
resolveDefaultDesktopSettings,
|
||||||
setDesktopServerExposurePreference,
|
setDesktopServerExposurePreference,
|
||||||
setDesktopTailscaleServePreference,
|
|
||||||
setDesktopUpdateChannelPreference,
|
setDesktopUpdateChannelPreference,
|
||||||
writeDesktopSettings,
|
writeDesktopSettings,
|
||||||
} from "./desktopSettings.ts";
|
} from "./desktopSettings.ts";
|
||||||
@@ -36,8 +35,6 @@ describe("desktopSettings", () => {
|
|||||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||||
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "nightly",
|
updateChannel: "nightly",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
});
|
});
|
||||||
@@ -48,16 +45,12 @@ describe("desktopSettings", () => {
|
|||||||
|
|
||||||
writeDesktopSettings(settingsPath, {
|
writeDesktopSettings(settingsPath, {
|
||||||
serverExposureMode: "network-accessible",
|
serverExposureMode: "network-accessible",
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: true,
|
updateChannelConfiguredByUser: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||||
serverExposureMode: "network-accessible",
|
serverExposureMode: "network-accessible",
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: true,
|
updateChannelConfiguredByUser: true,
|
||||||
});
|
});
|
||||||
@@ -68,8 +61,6 @@ describe("desktopSettings", () => {
|
|||||||
setDesktopServerExposurePreference(
|
setDesktopServerExposurePreference(
|
||||||
{
|
{
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
},
|
},
|
||||||
@@ -77,50 +68,6 @@ describe("desktopSettings", () => {
|
|||||||
),
|
),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
serverExposureMode: "network-accessible",
|
serverExposureMode: "network-accessible",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
|
||||||
updateChannelConfiguredByUser: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("persists the requested Tailscale Serve preference", () => {
|
|
||||||
expect(
|
|
||||||
setDesktopTailscaleServePreference(
|
|
||||||
{
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
|
||||||
updateChannelConfiguredByUser: false,
|
|
||||||
},
|
|
||||||
{ enabled: true, port: 8443 },
|
|
||||||
),
|
|
||||||
).toEqual({
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
updateChannel: "latest",
|
|
||||||
updateChannelConfiguredByUser: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
|
|
||||||
expect(
|
|
||||||
setDesktopTailscaleServePreference(
|
|
||||||
{
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
updateChannel: "latest",
|
|
||||||
updateChannelConfiguredByUser: false,
|
|
||||||
},
|
|
||||||
{ enabled: true },
|
|
||||||
),
|
|
||||||
).toEqual({
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
});
|
});
|
||||||
@@ -131,8 +78,6 @@ describe("desktopSettings", () => {
|
|||||||
setDesktopUpdateChannelPreference(
|
setDesktopUpdateChannelPreference(
|
||||||
{
|
{
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
},
|
},
|
||||||
@@ -140,8 +85,6 @@ describe("desktopSettings", () => {
|
|||||||
),
|
),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "nightly",
|
updateChannel: "nightly",
|
||||||
updateChannelConfiguredByUser: true,
|
updateChannelConfiguredByUser: true,
|
||||||
});
|
});
|
||||||
@@ -160,8 +103,6 @@ describe("desktopSettings", () => {
|
|||||||
|
|
||||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "nightly",
|
updateChannel: "nightly",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
});
|
});
|
||||||
@@ -180,8 +121,6 @@ describe("desktopSettings", () => {
|
|||||||
|
|
||||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "nightly",
|
updateChannel: "nightly",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
});
|
});
|
||||||
@@ -201,30 +140,8 @@ describe("desktopSettings", () => {
|
|||||||
|
|
||||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: true,
|
updateChannelConfiguredByUser: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
|
|
||||||
const settingsPath = makeSettingsPath();
|
|
||||||
fs.writeFileSync(
|
|
||||||
settingsPath,
|
|
||||||
JSON.stringify({
|
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 0,
|
|
||||||
}),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
updateChannel: "latest",
|
|
||||||
updateChannelConfiguredByUser: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -6,18 +6,12 @@ import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
|||||||
|
|
||||||
export interface DesktopSettings {
|
export interface DesktopSettings {
|
||||||
readonly serverExposureMode: DesktopServerExposureMode;
|
readonly serverExposureMode: DesktopServerExposureMode;
|
||||||
readonly tailscaleServeEnabled: boolean;
|
|
||||||
readonly tailscaleServePort: number;
|
|
||||||
readonly updateChannel: DesktopUpdateChannel;
|
readonly updateChannel: DesktopUpdateChannel;
|
||||||
readonly updateChannelConfiguredByUser: boolean;
|
readonly updateChannelConfiguredByUser: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
|
||||||
|
|
||||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||||
serverExposureMode: "local-only",
|
serverExposureMode: "local-only",
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
|
||||||
updateChannel: "latest",
|
updateChannel: "latest",
|
||||||
updateChannelConfiguredByUser: false,
|
updateChannelConfiguredByUser: false,
|
||||||
};
|
};
|
||||||
@@ -41,29 +35,6 @@ export function setDesktopServerExposurePreference(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setDesktopTailscaleServePreference(
|
|
||||||
settings: DesktopSettings,
|
|
||||||
input: { readonly enabled: boolean; readonly port?: number },
|
|
||||||
): DesktopSettings {
|
|
||||||
const port =
|
|
||||||
input.port === undefined
|
|
||||||
? settings.tailscaleServePort
|
|
||||||
: normalizeTailscaleServePort(input.port);
|
|
||||||
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
|
|
||||||
? settings
|
|
||||||
: {
|
|
||||||
...settings,
|
|
||||||
tailscaleServeEnabled: input.enabled,
|
|
||||||
tailscaleServePort: port,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeTailscaleServePort(value: unknown): number {
|
|
||||||
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
|
|
||||||
? value
|
|
||||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setDesktopUpdateChannelPreference(
|
export function setDesktopUpdateChannelPreference(
|
||||||
settings: DesktopSettings,
|
settings: DesktopSettings,
|
||||||
requestedChannel: DesktopUpdateChannel,
|
requestedChannel: DesktopUpdateChannel,
|
||||||
@@ -86,8 +57,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
|
|||||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||||
const parsed = JSON.parse(raw) as {
|
const parsed = JSON.parse(raw) as {
|
||||||
readonly serverExposureMode?: unknown;
|
readonly serverExposureMode?: unknown;
|
||||||
readonly tailscaleServeEnabled?: unknown;
|
|
||||||
readonly tailscaleServePort?: unknown;
|
|
||||||
readonly updateChannel?: unknown;
|
readonly updateChannel?: unknown;
|
||||||
readonly updateChannelConfiguredByUser?: unknown;
|
readonly updateChannelConfiguredByUser?: unknown;
|
||||||
};
|
};
|
||||||
@@ -103,8 +72,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
|
|||||||
return {
|
return {
|
||||||
serverExposureMode:
|
serverExposureMode:
|
||||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
|
||||||
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
|
|
||||||
updateChannel:
|
updateChannel:
|
||||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||||
? parsedUpdateChannel
|
? parsedUpdateChannel
|
||||||
|
|||||||
+5
-128
@@ -36,14 +36,11 @@ import { autoUpdater } from "electron-updater";
|
|||||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
|
||||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
||||||
import {
|
import {
|
||||||
type DesktopSettings,
|
|
||||||
DEFAULT_DESKTOP_SETTINGS,
|
DEFAULT_DESKTOP_SETTINGS,
|
||||||
readDesktopSettings,
|
readDesktopSettings,
|
||||||
setDesktopServerExposurePreference,
|
setDesktopServerExposurePreference,
|
||||||
setDesktopTailscaleServePreference,
|
|
||||||
setDesktopUpdateChannelPreference,
|
setDesktopUpdateChannelPreference,
|
||||||
writeDesktopSettings,
|
writeDesktopSettings,
|
||||||
} from "./desktopSettings.ts";
|
} from "./desktopSettings.ts";
|
||||||
@@ -58,11 +55,7 @@ import {
|
|||||||
} from "./clientPersistence.ts";
|
} from "./clientPersistence.ts";
|
||||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
||||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||||
import {
|
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||||
resolveDesktopCoreAdvertisedEndpoints,
|
|
||||||
resolveDesktopServerExposure,
|
|
||||||
} from "./serverExposure.ts";
|
|
||||||
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
|
|
||||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||||
@@ -83,7 +76,6 @@ import {
|
|||||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
|
||||||
|
|
||||||
syncShellEnvironment();
|
syncShellEnvironment();
|
||||||
|
|
||||||
@@ -110,8 +102,6 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr
|
|||||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||||
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
|
||||||
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
|
||||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||||
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
||||||
@@ -120,11 +110,6 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
|
|||||||
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);
|
||||||
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
|
|
||||||
// for a built server entry, for example:
|
|
||||||
// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"
|
|
||||||
const DEV_REMOTE_T3_SERVER_ENTRY_PATH =
|
|
||||||
process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ?? "";
|
|
||||||
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
|
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
|
||||||
isDevelopment,
|
isDevelopment,
|
||||||
appVersion: app.getVersion(),
|
appVersion: app.getVersion(),
|
||||||
@@ -312,9 +297,6 @@ function backendChildEnv(): NodeJS.ProcessEnv {
|
|||||||
delete env.T3CODE_DESKTOP_WS_URL;
|
delete env.T3CODE_DESKTOP_WS_URL;
|
||||||
delete env.T3CODE_DESKTOP_LAN_ACCESS;
|
delete env.T3CODE_DESKTOP_LAN_ACCESS;
|
||||||
delete env.T3CODE_DESKTOP_LAN_HOST;
|
delete env.T3CODE_DESKTOP_LAN_HOST;
|
||||||
delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS;
|
|
||||||
delete env.T3CODE_TAILSCALE_SERVE;
|
|
||||||
delete env.T3CODE_TAILSCALE_SERVE_PORT;
|
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,32 +305,9 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
|
|||||||
mode: desktopServerExposureMode,
|
mode: desktopServerExposureMode,
|
||||||
endpointUrl: backendEndpointUrl,
|
endpointUrl: backendEndpointUrl,
|
||||||
advertisedHost: backendAdvertisedHost,
|
advertisedHost: backendAdvertisedHost,
|
||||||
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
|
|
||||||
tailscaleServePort: desktopSettings.tailscaleServePort,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getDesktopAdvertisedEndpoints() {
|
|
||||||
const exposure = resolveDesktopServerExposure({
|
|
||||||
mode: desktopServerExposureMode,
|
|
||||||
port: backendPort,
|
|
||||||
networkInterfaces: OS.networkInterfaces(),
|
|
||||||
...(backendAdvertisedHost ? { advertisedHostOverride: backendAdvertisedHost } : {}),
|
|
||||||
});
|
|
||||||
const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
|
|
||||||
port: backendPort,
|
|
||||||
exposure,
|
|
||||||
customHttpsEndpointUrls: resolveCustomHttpsEndpointUrls(),
|
|
||||||
});
|
|
||||||
const tailscaleEndpoints = await resolveTailscaleAdvertisedEndpoints({
|
|
||||||
port: backendPort,
|
|
||||||
serveEnabled: desktopSettings.tailscaleServeEnabled,
|
|
||||||
servePort: desktopSettings.tailscaleServePort,
|
|
||||||
networkInterfaces: OS.networkInterfaces(),
|
|
||||||
});
|
|
||||||
return [...coreEndpoints, ...tailscaleEndpoints];
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDesktopSecretStorage() {
|
function getDesktopSecretStorage() {
|
||||||
return {
|
return {
|
||||||
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
|
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
|
||||||
@@ -362,19 +321,9 @@ function resolveAdvertisedHostOverride(): string | undefined {
|
|||||||
return override && override.length > 0 ? override : undefined;
|
return override && override.length > 0 ? override : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveCustomHttpsEndpointUrls(): readonly string[] {
|
|
||||||
return (process.env.T3CODE_DESKTOP_HTTPS_ENDPOINTS ?? "")
|
|
||||||
.split(",")
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter((entry) => entry.length > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function applyDesktopServerExposureMode(
|
async function applyDesktopServerExposureMode(
|
||||||
mode: DesktopServerExposureMode,
|
mode: DesktopServerExposureMode,
|
||||||
options?: {
|
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
|
||||||
readonly persist?: boolean;
|
|
||||||
readonly rejectIfUnavailable?: boolean;
|
|
||||||
},
|
|
||||||
): Promise<DesktopServerExposureState> {
|
): Promise<DesktopServerExposureState> {
|
||||||
const advertisedHostOverride = resolveAdvertisedHostOverride();
|
const advertisedHostOverride = resolveAdvertisedHostOverride();
|
||||||
const requestedMode = mode;
|
const requestedMode = mode;
|
||||||
@@ -412,17 +361,6 @@ async function applyDesktopServerExposureMode(
|
|||||||
return getDesktopServerExposureState();
|
return getDesktopServerExposureState();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function applyDesktopTailscaleServeEnabled(
|
|
||||||
nextSettings: DesktopSettings,
|
|
||||||
): Promise<DesktopServerExposureState> {
|
|
||||||
desktopSettings = nextSettings;
|
|
||||||
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
|
|
||||||
relaunchDesktopApp(
|
|
||||||
desktopSettings.tailscaleServeEnabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled",
|
|
||||||
);
|
|
||||||
return getDesktopServerExposureState();
|
|
||||||
}
|
|
||||||
|
|
||||||
function relaunchDesktopApp(reason: string): void {
|
function relaunchDesktopApp(reason: string): void {
|
||||||
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
|
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
@@ -435,7 +373,6 @@ function relaunchDesktopApp(reason: string): void {
|
|||||||
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
|
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
|
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
if (isDevelopment) {
|
if (isDevelopment) {
|
||||||
@@ -692,22 +629,6 @@ let updateInstallInFlight = false;
|
|||||||
let updaterConfigured = false;
|
let updaterConfigured = false;
|
||||||
let updateState: DesktopUpdateState = initialUpdateState();
|
let updateState: DesktopUpdateState = initialUpdateState();
|
||||||
|
|
||||||
const desktopSshEnvironmentBridge = new DesktopSshEnvironmentBridge({
|
|
||||||
getMainWindow: () => mainWindow,
|
|
||||||
resolveCliRunner: (): RemoteT3RunnerOptions => {
|
|
||||||
if (isDevelopment && DEV_REMOTE_T3_SERVER_ENTRY_PATH.length > 0) {
|
|
||||||
return { nodeScriptPath: DEV_REMOTE_T3_SERVER_ENTRY_PATH };
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
packageSpec: resolveRemoteT3CliPackageSpec({
|
|
||||||
appVersion: app.getVersion(),
|
|
||||||
updateChannel: desktopSettings.updateChannel,
|
|
||||||
isDevelopment,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||||
if (updateInstallInFlight) return "install";
|
if (updateInstallInFlight) return "install";
|
||||||
if (updateDownloadInFlight) return "download";
|
if (updateDownloadInFlight) return "download";
|
||||||
@@ -1259,10 +1180,7 @@ async function checkForUpdates(reason: string): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function downloadAvailableUpdate(): Promise<{
|
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||||
accepted: boolean;
|
|
||||||
completed: boolean;
|
|
||||||
}> {
|
|
||||||
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
|
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
|
||||||
return { accepted: false, completed: false };
|
return { accepted: false, completed: false };
|
||||||
}
|
}
|
||||||
@@ -1284,10 +1202,7 @@ async function downloadAvailableUpdate(): Promise<{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function installDownloadedUpdate(): Promise<{
|
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||||
accepted: boolean;
|
|
||||||
completed: boolean;
|
|
||||||
}> {
|
|
||||||
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
|
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
|
||||||
return { accepted: false, completed: false };
|
return { accepted: false, completed: false };
|
||||||
}
|
}
|
||||||
@@ -1487,8 +1402,6 @@ function startBackend(): void {
|
|||||||
t3Home: BASE_DIR,
|
t3Home: BASE_DIR,
|
||||||
host: backendBindHost,
|
host: backendBindHost,
|
||||||
desktopBootstrapToken: backendBootstrapToken,
|
desktopBootstrapToken: backendBootstrapToken,
|
||||||
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
|
|
||||||
tailscaleServePort: desktopSettings.tailscaleServePort,
|
|
||||||
...(backendObservabilitySettings.otlpTracesUrl
|
...(backendObservabilitySettings.otlpTracesUrl
|
||||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -1734,8 +1647,6 @@ function registerIpcHandlers(): void {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
||||||
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
||||||
|
|
||||||
@@ -1758,31 +1669,6 @@ function registerIpcHandlers(): void {
|
|||||||
return nextState;
|
return nextState;
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.removeHandler(SET_TAILSCALE_SERVE_ENABLED_CHANNEL);
|
|
||||||
ipcMain.handle(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, async (_event, rawInput: unknown) => {
|
|
||||||
if (typeof rawInput !== "object" || rawInput === null) {
|
|
||||||
throw new Error("Invalid Tailscale Serve input.");
|
|
||||||
}
|
|
||||||
const input = rawInput as {
|
|
||||||
readonly enabled?: unknown;
|
|
||||||
readonly port?: unknown;
|
|
||||||
};
|
|
||||||
if (typeof input.enabled !== "boolean") {
|
|
||||||
throw new Error("Invalid Tailscale Serve input.");
|
|
||||||
}
|
|
||||||
const nextSettings = setDesktopTailscaleServePreference(desktopSettings, {
|
|
||||||
enabled: input.enabled,
|
|
||||||
...(typeof input.port === "number" ? { port: input.port } : {}),
|
|
||||||
});
|
|
||||||
if (nextSettings === desktopSettings) {
|
|
||||||
return getDesktopServerExposureState();
|
|
||||||
}
|
|
||||||
return applyDesktopTailscaleServeEnabled(nextSettings);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL);
|
|
||||||
ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints());
|
|
||||||
|
|
||||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
|
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
|
||||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||||
@@ -2073,10 +1959,7 @@ function createWindow(): BrowserWindow {
|
|||||||
const externalUrl = getSafeExternalUrl(params.linkURL);
|
const externalUrl = getSafeExternalUrl(params.linkURL);
|
||||||
if (externalUrl) {
|
if (externalUrl) {
|
||||||
menuTemplate.push(
|
menuTemplate.push(
|
||||||
{
|
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
|
||||||
label: "Copy Link",
|
|
||||||
click: () => clipboard.writeText(params.linkURL),
|
|
||||||
},
|
|
||||||
{ type: "separator" },
|
{ type: "separator" },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2136,9 +2019,6 @@ function createWindow(): BrowserWindow {
|
|||||||
}
|
}
|
||||||
|
|
||||||
window.on("closed", () => {
|
window.on("closed", () => {
|
||||||
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
|
|
||||||
"SSH authentication was cancelled because the app window closed.",
|
|
||||||
);
|
|
||||||
if (mainWindow === window) {
|
if (mainWindow === window) {
|
||||||
mainWindow = null;
|
mainWindow = null;
|
||||||
}
|
}
|
||||||
@@ -2230,7 +2110,6 @@ app.on("before-quit", () => {
|
|||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
cancelBackendReadinessWait();
|
cancelBackendReadinessWait();
|
||||||
stopBackend();
|
stopBackend();
|
||||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2280,7 +2159,6 @@ if (process.platform !== "win32") {
|
|||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
cancelBackendReadinessWait();
|
cancelBackendReadinessWait();
|
||||||
stopBackend();
|
stopBackend();
|
||||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
app.quit();
|
app.quit();
|
||||||
});
|
});
|
||||||
@@ -2291,7 +2169,6 @@ if (process.platform !== "win32") {
|
|||||||
writeDesktopLogHeader("SIGTERM received");
|
writeDesktopLogHeader("SIGTERM received");
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
stopBackend();
|
stopBackend();
|
||||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
app.quit();
|
app.quit();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -22,36 +22,8 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
|
|||||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
|
||||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
|
||||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
|
||||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
|
||||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
|
||||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
|
||||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
|
||||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
|
||||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
|
||||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||||
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
|
||||||
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
|
||||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
|
||||||
|
|
||||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
|
||||||
if (
|
|
||||||
typeof result === "object" &&
|
|
||||||
result !== null &&
|
|
||||||
"type" in result &&
|
|
||||||
result.type === SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
|
||||||
) {
|
|
||||||
const message =
|
|
||||||
"message" in result && typeof result.message === "string"
|
|
||||||
? result.message
|
|
||||||
: "SSH authentication cancelled.";
|
|
||||||
throw new Error(message);
|
|
||||||
}
|
|
||||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getAppBranding: () => {
|
getAppBranding: () => {
|
||||||
@@ -79,39 +51,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
|||||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
||||||
removeSavedEnvironmentSecret: (environmentId) =>
|
removeSavedEnvironmentSecret: (environmentId) =>
|
||||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||||
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
|
|
||||||
ensureSshEnvironment: async (target, options) =>
|
|
||||||
unwrapEnsureSshEnvironmentResult(
|
|
||||||
await ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
|
|
||||||
),
|
|
||||||
disconnectSshEnvironment: (target) =>
|
|
||||||
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
|
|
||||||
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
|
|
||||||
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
|
|
||||||
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
|
|
||||||
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
|
|
||||||
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
|
|
||||||
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
|
|
||||||
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
|
|
||||||
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
|
|
||||||
onSshPasswordPrompt: (listener) => {
|
|
||||||
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
|
|
||||||
if (typeof request !== "object" || request === null) return;
|
|
||||||
listener(request as Parameters<typeof listener>[0]);
|
|
||||||
};
|
|
||||||
|
|
||||||
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
|
||||||
return () => {
|
|
||||||
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
|
||||||
};
|
|
||||||
},
|
|
||||||
resolveSshPasswordPrompt: (requestId, password) =>
|
|
||||||
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
|
|
||||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||||
setTailscaleServeEnabled: (input) =>
|
|
||||||
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
|
||||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
|
||||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||||
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),
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import {
|
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
|
||||||
resolveDesktopCoreAdvertisedEndpoints,
|
|
||||||
resolveDesktopServerExposure,
|
|
||||||
resolveLanAdvertisedHost,
|
|
||||||
} from "./serverExposure.ts";
|
|
||||||
|
|
||||||
describe("resolveLanAdvertisedHost", () => {
|
describe("resolveLanAdvertisedHost", () => {
|
||||||
it("prefers an explicit host override", () => {
|
it("prefers an explicit host override", () => {
|
||||||
@@ -78,121 +74,6 @@ describe("resolveLanAdvertisedHost", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
|
|
||||||
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
|
|
||||||
const exposure = resolveDesktopServerExposure({
|
|
||||||
mode: "network-accessible",
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {
|
|
||||||
en0: [
|
|
||||||
{
|
|
||||||
address: "192.168.1.44",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: false,
|
|
||||||
netmask: "255.255.255.0",
|
|
||||||
cidr: "192.168.1.44/24",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(
|
|
||||||
resolveDesktopCoreAdvertisedEndpoints({
|
|
||||||
port: 3773,
|
|
||||||
exposure,
|
|
||||||
customHttpsEndpointUrls: [
|
|
||||||
"https://desktop.example.ts.net",
|
|
||||||
"http://desktop.example.test:3773",
|
|
||||||
"not-a-url",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
).toEqual([
|
|
||||||
{
|
|
||||||
id: "desktop-loopback:3773",
|
|
||||||
label: "This machine",
|
|
||||||
provider: {
|
|
||||||
id: "desktop-core",
|
|
||||||
label: "Desktop",
|
|
||||||
kind: "core",
|
|
||||||
isAddon: false,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "http://127.0.0.1:3773/",
|
|
||||||
wsBaseUrl: "ws://127.0.0.1:3773/",
|
|
||||||
reachability: "loopback",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "mixed-content-blocked",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "desktop-core",
|
|
||||||
status: "available",
|
|
||||||
description: "Loopback endpoint for this desktop app.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "desktop-lan:http://192.168.1.44:3773",
|
|
||||||
label: "Local network",
|
|
||||||
provider: {
|
|
||||||
id: "desktop-core",
|
|
||||||
label: "Desktop",
|
|
||||||
kind: "core",
|
|
||||||
isAddon: false,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "http://192.168.1.44:3773/",
|
|
||||||
wsBaseUrl: "ws://192.168.1.44:3773/",
|
|
||||||
reachability: "lan",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "mixed-content-blocked",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "desktop-core",
|
|
||||||
status: "available",
|
|
||||||
isDefault: true,
|
|
||||||
description: "Reachable from devices on the same network.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "manual:https://desktop.example.ts.net",
|
|
||||||
label: "Custom HTTPS",
|
|
||||||
provider: {
|
|
||||||
id: "manual",
|
|
||||||
label: "Manual",
|
|
||||||
kind: "manual",
|
|
||||||
isAddon: false,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "https://desktop.example.ts.net/",
|
|
||||||
wsBaseUrl: "wss://desktop.example.ts.net/",
|
|
||||||
reachability: "public",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "compatible",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "user",
|
|
||||||
status: "unknown",
|
|
||||||
description: "User-configured HTTPS endpoint for this desktop backend.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "manual:http://desktop.example.test:3773",
|
|
||||||
label: "Custom endpoint",
|
|
||||||
provider: {
|
|
||||||
id: "manual",
|
|
||||||
label: "Manual",
|
|
||||||
kind: "manual",
|
|
||||||
isAddon: false,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "http://desktop.example.test:3773/",
|
|
||||||
wsBaseUrl: "ws://desktop.example.test:3773/",
|
|
||||||
reachability: "public",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "mixed-content-blocked",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "user",
|
|
||||||
status: "unknown",
|
|
||||||
description: "User-configured endpoint for this desktop backend.",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveDesktopServerExposure", () => {
|
describe("resolveDesktopServerExposure", () => {
|
||||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -1,13 +1,5 @@
|
|||||||
import type { NetworkInterfaceInfo } from "node:os";
|
import type { NetworkInterfaceInfo } from "node:os";
|
||||||
import {
|
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||||
createAdvertisedEndpoint,
|
|
||||||
type CreateAdvertisedEndpointInput,
|
|
||||||
} from "@t3tools/client-runtime";
|
|
||||||
import type {
|
|
||||||
AdvertisedEndpoint,
|
|
||||||
AdvertisedEndpointProvider,
|
|
||||||
DesktopServerExposureMode,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||||
@@ -21,26 +13,6 @@ export interface DesktopServerExposure {
|
|||||||
readonly advertisedHost: string | null;
|
readonly advertisedHost: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DesktopAdvertisedEndpointInput {
|
|
||||||
readonly port: number;
|
|
||||||
readonly exposure: DesktopServerExposure;
|
|
||||||
readonly customHttpsEndpointUrls?: readonly string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
|
||||||
id: "desktop-core",
|
|
||||||
label: "Desktop",
|
|
||||||
kind: "core",
|
|
||||||
isAddon: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
|
||||||
id: "manual",
|
|
||||||
label: "Manual",
|
|
||||||
kind: "manual",
|
|
||||||
isAddon: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
||||||
const normalized = value?.trim();
|
const normalized = value?.trim();
|
||||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||||
@@ -49,14 +21,6 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
|
|||||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||||
|
|
||||||
function isHttpsEndpointUrl(value: string): boolean {
|
|
||||||
try {
|
|
||||||
return new URL(value).protocol === "https:";
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveLanAdvertisedHost(
|
export function resolveLanAdvertisedHost(
|
||||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
||||||
explicitHost: string | undefined,
|
explicitHost: string | undefined,
|
||||||
@@ -114,75 +78,3 @@ export function resolveDesktopServerExposure(input: {
|
|||||||
advertisedHost,
|
advertisedHost,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function createDesktopEndpoint(
|
|
||||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
|
||||||
): AdvertisedEndpoint {
|
|
||||||
return createAdvertisedEndpoint({
|
|
||||||
...input,
|
|
||||||
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
|
|
||||||
source: "desktop-core",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function createManualEndpoint(
|
|
||||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
|
||||||
): AdvertisedEndpoint {
|
|
||||||
return createAdvertisedEndpoint({
|
|
||||||
...input,
|
|
||||||
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
|
|
||||||
source: "user",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveDesktopCoreAdvertisedEndpoints(
|
|
||||||
input: DesktopAdvertisedEndpointInput,
|
|
||||||
): readonly AdvertisedEndpoint[] {
|
|
||||||
const endpoints: AdvertisedEndpoint[] = [
|
|
||||||
createDesktopEndpoint({
|
|
||||||
id: `desktop-loopback:${input.port}`,
|
|
||||||
label: "This machine",
|
|
||||||
httpBaseUrl: input.exposure.localHttpUrl,
|
|
||||||
reachability: "loopback",
|
|
||||||
status: "available",
|
|
||||||
description: "Loopback endpoint for this desktop app.",
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
|
|
||||||
if (input.exposure.endpointUrl) {
|
|
||||||
endpoints.push(
|
|
||||||
createDesktopEndpoint({
|
|
||||||
id: `desktop-lan:${input.exposure.endpointUrl}`,
|
|
||||||
label: "Local network",
|
|
||||||
httpBaseUrl: input.exposure.endpointUrl,
|
|
||||||
reachability: "lan",
|
|
||||||
status: "available",
|
|
||||||
isDefault: true,
|
|
||||||
description: "Reachable from devices on the same network.",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
|
|
||||||
try {
|
|
||||||
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
|
|
||||||
endpoints.push(
|
|
||||||
createManualEndpoint({
|
|
||||||
id: `manual:${customEndpointUrl}`,
|
|
||||||
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
|
|
||||||
httpBaseUrl: customEndpointUrl,
|
|
||||||
reachability: "public",
|
|
||||||
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
|
|
||||||
status: "unknown",
|
|
||||||
description: isHttpsEndpoint
|
|
||||||
? "User-configured HTTPS endpoint for this desktop backend."
|
|
||||||
: "User-configured endpoint for this desktop backend.",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
// Ignore malformed user-configured endpoints without dropping valid endpoints.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return endpoints;
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import * as FS from "node:fs";
|
|
||||||
import * as OS from "node:os";
|
|
||||||
import * as Path from "node:path";
|
|
||||||
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
|
||||||
|
|
||||||
import { discoverDesktopSshHosts, isSshPasswordPromptCancellation } from "./sshEnvironment.ts";
|
|
||||||
|
|
||||||
const tempDirectories: string[] = [];
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
for (const directory of tempDirectories.splice(0)) {
|
|
||||||
FS.rmSync(directory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function makeTempHomeDir(): string {
|
|
||||||
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
|
|
||||||
tempDirectories.push(directory);
|
|
||||||
return directory;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("sshEnvironment", () => {
|
|
||||||
it("treats password prompt timeouts as cancellable authentication prompts", () => {
|
|
||||||
expect(
|
|
||||||
isSshPasswordPromptCancellation(
|
|
||||||
new SshPasswordPromptError({
|
|
||||||
message: "SSH authentication timed out for devbox.",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("wires desktop host discovery through the ssh package runtime", async () => {
|
|
||||||
const homeDir = makeTempHomeDir();
|
|
||||||
const sshDir = Path.join(homeDir, ".ssh");
|
|
||||||
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
|
|
||||||
FS.writeFileSync(
|
|
||||||
Path.join(sshDir, "config"),
|
|
||||||
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
FS.writeFileSync(
|
|
||||||
Path.join(sshDir, "config.d", "team.conf"),
|
|
||||||
[
|
|
||||||
"Host staging",
|
|
||||||
" HostName staging.example.com",
|
|
||||||
"Host *",
|
|
||||||
" ServerAliveInterval 30",
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
FS.writeFileSync(
|
|
||||||
Path.join(sshDir, "known_hosts"),
|
|
||||||
[
|
|
||||||
"known.example.com ssh-ed25519 AAAA",
|
|
||||||
"|1|hashed|entry ssh-ed25519 AAAA",
|
|
||||||
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
|
|
||||||
{
|
|
||||||
alias: "bastion.example.com",
|
|
||||||
hostname: "bastion.example.com",
|
|
||||||
username: null,
|
|
||||||
port: null,
|
|
||||||
source: "known-hosts",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
alias: "devbox",
|
|
||||||
hostname: "devbox",
|
|
||||||
username: null,
|
|
||||||
port: null,
|
|
||||||
source: "ssh-config",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
alias: "known.example.com",
|
|
||||||
hostname: "known.example.com",
|
|
||||||
username: null,
|
|
||||||
port: null,
|
|
||||||
source: "known-hosts",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
alias: "staging",
|
|
||||||
hostname: "staging",
|
|
||||||
username: null,
|
|
||||||
port: null,
|
|
||||||
source: "ssh-config",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,420 +0,0 @@
|
|||||||
import * as Crypto from "node:crypto";
|
|
||||||
|
|
||||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import type {
|
|
||||||
AuthBearerBootstrapResult,
|
|
||||||
AuthSessionState,
|
|
||||||
AuthWebSocketTokenResult,
|
|
||||||
DesktopDiscoveredSshHost,
|
|
||||||
DesktopSshEnvironmentTarget,
|
|
||||||
DesktopSshPasswordPromptRequest,
|
|
||||||
ExecutionEnvironmentDescriptor,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import {
|
|
||||||
SshPasswordPrompt,
|
|
||||||
type SshPasswordPromptShape,
|
|
||||||
type SshPasswordRequest,
|
|
||||||
} from "@t3tools/ssh/auth";
|
|
||||||
import { discoverSshHosts } from "@t3tools/ssh/config";
|
|
||||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
|
||||||
import {
|
|
||||||
fetchLoopbackSshJson,
|
|
||||||
SshEnvironmentManager,
|
|
||||||
type RemoteT3RunnerOptions,
|
|
||||||
} from "@t3tools/ssh/tunnel";
|
|
||||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
|
||||||
|
|
||||||
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
|
||||||
|
|
||||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
|
||||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
|
||||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
|
||||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
|
||||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
|
||||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
|
||||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
|
||||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
|
||||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
|
||||||
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
|
||||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
|
||||||
|
|
||||||
interface DesktopSshEnvironmentManagerOptions {
|
|
||||||
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
|
|
||||||
readonly resolveCliPackageSpec?: () => string;
|
|
||||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sshRuntime = ManagedRuntime.make(
|
|
||||||
Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, NetService.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
function createDesktopSshRuntime(
|
|
||||||
passwordPrompt: SshPasswordPromptShape,
|
|
||||||
scope: Scope.Scope,
|
|
||||||
options: DesktopSshEnvironmentManagerOptions,
|
|
||||||
) {
|
|
||||||
return ManagedRuntime.make(
|
|
||||||
Layer.mergeAll(
|
|
||||||
NodeServices.layer,
|
|
||||||
NodeHttpClient.layerUndici,
|
|
||||||
NetService.layer,
|
|
||||||
Layer.succeed(Scope.Scope, scope),
|
|
||||||
Layer.succeed(SshPasswordPrompt, SshPasswordPrompt.of(passwordPrompt)),
|
|
||||||
SshEnvironmentManager.layer({
|
|
||||||
...(options.resolveCliPackageSpec === undefined
|
|
||||||
? {}
|
|
||||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
|
||||||
...(options.resolveCliRunner === undefined
|
|
||||||
? {}
|
|
||||||
: { resolveCliRunner: options.resolveCliRunner }),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function discoverDesktopSshHosts(input?: {
|
|
||||||
readonly homeDir?: string;
|
|
||||||
}): Promise<readonly DesktopDiscoveredSshHost[]> {
|
|
||||||
return await sshRuntime.runPromise(discoverSshHosts(input ?? {}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export class DesktopSshEnvironmentManager {
|
|
||||||
private readonly runtime: ReturnType<typeof createDesktopSshRuntime>;
|
|
||||||
private readonly scope: Scope.Scope;
|
|
||||||
|
|
||||||
constructor(options: DesktopSshEnvironmentManagerOptions = {}) {
|
|
||||||
const passwordPrompt: SshPasswordPromptShape = {
|
|
||||||
isAvailable: options.passwordProvider !== undefined,
|
|
||||||
request: (request) => {
|
|
||||||
const passwordProvider = options.passwordProvider;
|
|
||||||
if (!passwordProvider) {
|
|
||||||
return Effect.succeed(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Effect.tryPromise({
|
|
||||||
try: () => passwordProvider(request),
|
|
||||||
catch: (cause) =>
|
|
||||||
new SshPasswordPromptError({
|
|
||||||
message: cause instanceof Error ? cause.message : "SSH password prompt failed.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
this.scope = Effect.runSync(Scope.make());
|
|
||||||
this.runtime = createDesktopSshRuntime(passwordPrompt, this.scope, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {
|
|
||||||
return await discoverDesktopSshHosts();
|
|
||||||
}
|
|
||||||
|
|
||||||
async ensureEnvironment(
|
|
||||||
target: DesktopSshEnvironmentTarget,
|
|
||||||
options?: { readonly issuePairingToken?: boolean },
|
|
||||||
) {
|
|
||||||
return await this.runtime.runPromise(
|
|
||||||
Effect.service(SshEnvironmentManager).pipe(
|
|
||||||
Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async disconnectEnvironment(target: DesktopSshEnvironmentTarget): Promise<void> {
|
|
||||||
await this.runtime.runPromise(
|
|
||||||
Effect.service(SshEnvironmentManager).pipe(
|
|
||||||
Effect.flatMap((manager) => manager.disconnectEnvironment(target)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async dispose(): Promise<void> {
|
|
||||||
await this.runtime.runPromise(Scope.close(this.scope, Exit.void));
|
|
||||||
await this.runtime.dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
|
|
||||||
if (typeof rawTarget !== "object" || rawTarget === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
|
|
||||||
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
target.username !== null &&
|
|
||||||
target.username !== undefined &&
|
|
||||||
typeof target.username !== "string"
|
|
||||||
) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const alias = target.alias.trim();
|
|
||||||
const hostname = target.hostname.trim();
|
|
||||||
if (alias.length === 0 || hostname.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
alias,
|
|
||||||
hostname,
|
|
||||||
username: target.username?.trim() || null,
|
|
||||||
port: target.port ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Minimal subset of Electron's BrowserWindow used by the SSH bridge. */
|
|
||||||
export interface DesktopSshBridgeWindow {
|
|
||||||
isDestroyed(): boolean;
|
|
||||||
isMinimized(): boolean;
|
|
||||||
restore(): void;
|
|
||||||
focus(): void;
|
|
||||||
readonly webContents: {
|
|
||||||
send(channel: string, ...args: readonly unknown[]): void;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Minimal subset of Electron's ipcMain used by the SSH bridge. */
|
|
||||||
export interface DesktopSshBridgeIpcMain {
|
|
||||||
removeHandler(channel: string): void;
|
|
||||||
handle(
|
|
||||||
channel: string,
|
|
||||||
listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,
|
|
||||||
): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DesktopSshEnvironmentBridgeOptions {
|
|
||||||
readonly getMainWindow: () => DesktopSshBridgeWindow | null;
|
|
||||||
readonly resolveCliPackageSpec?: () => string;
|
|
||||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
|
||||||
readonly passwordPromptTimeoutMs?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PendingSshPasswordPrompt {
|
|
||||||
readonly resolve: (password: string | null) => void;
|
|
||||||
readonly reject: (error: Error) => void;
|
|
||||||
readonly timeout: ReturnType<typeof setTimeout>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {
|
|
||||||
const message = error instanceof SshPasswordPromptError ? error.message.toLowerCase() : "";
|
|
||||||
return (
|
|
||||||
error instanceof SshPasswordPromptError &&
|
|
||||||
(message.includes("cancelled") || message.includes("timed out"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
|
|
||||||
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
|
|
||||||
*/
|
|
||||||
export class DesktopSshEnvironmentBridge {
|
|
||||||
private readonly options: DesktopSshEnvironmentBridgeOptions;
|
|
||||||
private readonly manager: DesktopSshEnvironmentManager;
|
|
||||||
private readonly pendingPrompts = new Map<string, PendingSshPasswordPrompt>();
|
|
||||||
private readonly passwordPromptTimeoutMs: number;
|
|
||||||
|
|
||||||
constructor(options: DesktopSshEnvironmentBridgeOptions) {
|
|
||||||
this.options = options;
|
|
||||||
this.passwordPromptTimeoutMs =
|
|
||||||
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
|
|
||||||
this.manager = new DesktopSshEnvironmentManager({
|
|
||||||
passwordProvider: (request) => this.requestPasswordFromRenderer(request),
|
|
||||||
...(options.resolveCliPackageSpec === undefined
|
|
||||||
? {}
|
|
||||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
|
||||||
...(options.resolveCliRunner === undefined
|
|
||||||
? {}
|
|
||||||
: { resolveCliRunner: options.resolveCliRunner }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
registerIpcHandlers(ipcMain: DesktopSshBridgeIpcMain): void {
|
|
||||||
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
|
|
||||||
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () => this.manager.discoverHosts());
|
|
||||||
|
|
||||||
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
|
|
||||||
ipcMain.handle(ENSURE_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget, rawOptions) => {
|
|
||||||
const target = getSafeDesktopSshTarget(rawTarget);
|
|
||||||
if (!target) {
|
|
||||||
throw new Error("Invalid desktop SSH target.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const issuePairingToken =
|
|
||||||
typeof rawOptions === "object" &&
|
|
||||||
rawOptions !== null &&
|
|
||||||
"issuePairingToken" in rawOptions &&
|
|
||||||
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await this.manager.ensureEnvironment(target, {
|
|
||||||
issuePairingToken,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (isSshPasswordPromptCancellation(error)) {
|
|
||||||
return {
|
|
||||||
type: SSH_PASSWORD_PROMPT_CANCELLED_RESULT,
|
|
||||||
message: error.message,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
|
|
||||||
ipcMain.handle(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget) => {
|
|
||||||
const target = getSafeDesktopSshTarget(rawTarget);
|
|
||||||
if (!target) {
|
|
||||||
throw new Error("Invalid desktop SSH target.");
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.manager.disconnectEnvironment(target);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
|
|
||||||
ipcMain.handle(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, async (_event, rawHttpBaseUrl) =>
|
|
||||||
sshRuntime.runPromise(
|
|
||||||
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
|
|
||||||
httpBaseUrl: rawHttpBaseUrl,
|
|
||||||
pathname: "/.well-known/t3/environment",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
|
||||||
async (_event, rawHttpBaseUrl, rawCredential) =>
|
|
||||||
sshRuntime.runPromise(
|
|
||||||
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
|
|
||||||
httpBaseUrl: rawHttpBaseUrl,
|
|
||||||
pathname: "/api/auth/bootstrap/bearer",
|
|
||||||
method: "POST",
|
|
||||||
body: { credential: rawCredential },
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
FETCH_SSH_SESSION_STATE_CHANNEL,
|
|
||||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
|
||||||
sshRuntime.runPromise(
|
|
||||||
fetchLoopbackSshJson<AuthSessionState>({
|
|
||||||
httpBaseUrl: rawHttpBaseUrl,
|
|
||||||
pathname: "/api/auth/session",
|
|
||||||
bearerToken: rawBearerToken,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
|
||||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
|
||||||
sshRuntime.runPromise(
|
|
||||||
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
|
|
||||||
httpBaseUrl: rawHttpBaseUrl,
|
|
||||||
pathname: "/api/auth/ws-token",
|
|
||||||
method: "POST",
|
|
||||||
bearerToken: rawBearerToken,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
|
||||||
async (_event, rawRequestId, rawPassword) => {
|
|
||||||
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
|
|
||||||
throw new Error("Invalid SSH password prompt id.");
|
|
||||||
}
|
|
||||||
if (rawPassword !== null && typeof rawPassword !== "string") {
|
|
||||||
throw new Error("Invalid SSH password prompt response.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const pending = this.pendingPrompts.get(rawRequestId);
|
|
||||||
if (!pending) {
|
|
||||||
throw new Error("SSH password prompt expired. Try connecting again.");
|
|
||||||
}
|
|
||||||
|
|
||||||
clearTimeout(pending.timeout);
|
|
||||||
this.pendingPrompts.delete(rawRequestId);
|
|
||||||
pending.resolve(rawPassword);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
cancelPendingPasswordPrompts(reason: string): void {
|
|
||||||
for (const [requestId, pending] of this.pendingPrompts) {
|
|
||||||
clearTimeout(pending.timeout);
|
|
||||||
this.pendingPrompts.delete(requestId);
|
|
||||||
pending.reject(new Error(reason));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async dispose(): Promise<void> {
|
|
||||||
this.cancelPendingPasswordPrompts("SSH environment bridge disposed.");
|
|
||||||
await this.manager.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
|
|
||||||
const window = this.options.getMainWindow();
|
|
||||||
if (!window || window.isDestroyed()) {
|
|
||||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const request: DesktopSshPasswordPromptRequest = {
|
|
||||||
requestId: Crypto.randomUUID(),
|
|
||||||
destination: input.destination,
|
|
||||||
username: input.username,
|
|
||||||
prompt: input.prompt,
|
|
||||||
expiresAt: new Date(Date.now() + this.passwordPromptTimeoutMs).toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
return await new Promise<string | null>((resolve, reject) => {
|
|
||||||
const rejectPrompt = (error: Error) => {
|
|
||||||
clearTimeout(timeout);
|
|
||||||
this.pendingPrompts.delete(request.requestId);
|
|
||||||
reject(error);
|
|
||||||
};
|
|
||||||
const timeout = setTimeout(() => {
|
|
||||||
this.pendingPrompts.delete(request.requestId);
|
|
||||||
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
|
|
||||||
}, this.passwordPromptTimeoutMs);
|
|
||||||
timeout.unref();
|
|
||||||
|
|
||||||
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (window.isDestroyed()) {
|
|
||||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
|
||||||
}
|
|
||||||
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
|
|
||||||
if (window.isDestroyed()) {
|
|
||||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
|
||||||
}
|
|
||||||
if (window.isMinimized()) {
|
|
||||||
window.restore();
|
|
||||||
}
|
|
||||||
if (window.isDestroyed()) {
|
|
||||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
|
||||||
}
|
|
||||||
window.focus();
|
|
||||||
} catch (error) {
|
|
||||||
rejectPrompt(
|
|
||||||
error instanceof Error
|
|
||||||
? error
|
|
||||||
: new Error("T3 Code window is not available for SSH authentication."),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import { Effect } from "effect";
|
|
||||||
|
|
||||||
import {
|
|
||||||
isTailscaleIpv4Address,
|
|
||||||
parseTailscaleMagicDnsName,
|
|
||||||
resolveTailscaleAdvertisedEndpoints,
|
|
||||||
} from "./tailscaleEndpointProvider.ts";
|
|
||||||
|
|
||||||
describe("tailscale endpoint provider", () => {
|
|
||||||
it("detects Tailnet IPv4 addresses", () => {
|
|
||||||
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
|
|
||||||
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
|
|
||||||
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
|
|
||||||
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses MagicDNS names from tailscale status", async () => {
|
|
||||||
expect(
|
|
||||||
Effect.runSync(
|
|
||||||
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
|
|
||||||
),
|
|
||||||
).toBe("desktop.tail.ts.net");
|
|
||||||
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
|
|
||||||
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
|
|
||||||
await expect(
|
|
||||||
resolveTailscaleAdvertisedEndpoints({
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {
|
|
||||||
tailscale0: [
|
|
||||||
{
|
|
||||||
address: "100.100.100.100",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: false,
|
|
||||||
netmask: "255.192.0.0",
|
|
||||||
cidr: "100.100.100.100/10",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
|
||||||
}),
|
|
||||||
).resolves.toEqual([
|
|
||||||
{
|
|
||||||
id: "tailscale-ip:http://100.100.100.100:3773",
|
|
||||||
label: "Tailscale IP",
|
|
||||||
provider: {
|
|
||||||
id: "tailscale",
|
|
||||||
label: "Tailscale",
|
|
||||||
kind: "private-network",
|
|
||||||
isAddon: true,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "http://100.100.100.100:3773/",
|
|
||||||
wsBaseUrl: "ws://100.100.100.100:3773/",
|
|
||||||
reachability: "private-network",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "mixed-content-blocked",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "desktop-addon",
|
|
||||||
status: "available",
|
|
||||||
description: "Reachable from devices on the same Tailnet.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
|
||||||
label: "Tailscale HTTPS",
|
|
||||||
provider: {
|
|
||||||
id: "tailscale",
|
|
||||||
label: "Tailscale",
|
|
||||||
kind: "private-network",
|
|
||||||
isAddon: true,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
|
||||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
|
||||||
reachability: "private-network",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "requires-configuration",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "desktop-addon",
|
|
||||||
status: "unavailable",
|
|
||||||
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
|
|
||||||
await expect(
|
|
||||||
resolveTailscaleAdvertisedEndpoints({
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {},
|
|
||||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
|
||||||
serveEnabled: true,
|
|
||||||
probe: async () => true,
|
|
||||||
}),
|
|
||||||
).resolves.toEqual([
|
|
||||||
{
|
|
||||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
|
||||||
label: "Tailscale HTTPS",
|
|
||||||
provider: {
|
|
||||||
id: "tailscale",
|
|
||||||
label: "Tailscale",
|
|
||||||
kind: "private-network",
|
|
||||||
isAddon: true,
|
|
||||||
},
|
|
||||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
|
||||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
|
||||||
reachability: "private-network",
|
|
||||||
compatibility: {
|
|
||||||
hostedHttpsApp: "compatible",
|
|
||||||
desktopApp: "compatible",
|
|
||||||
},
|
|
||||||
source: "desktop-addon",
|
|
||||||
status: "available",
|
|
||||||
description: "HTTPS endpoint served by Tailscale Serve.",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
import type { NetworkInterfaceInfo } from "node:os";
|
|
||||||
|
|
||||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import {
|
|
||||||
createAdvertisedEndpoint,
|
|
||||||
type CreateAdvertisedEndpointInput,
|
|
||||||
} from "@t3tools/client-runtime";
|
|
||||||
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
|
|
||||||
import {
|
|
||||||
buildTailscaleHttpsBaseUrl,
|
|
||||||
isTailscaleIpv4Address,
|
|
||||||
parseTailscaleMagicDnsName,
|
|
||||||
probeTailscaleHttpsEndpoint,
|
|
||||||
readTailscaleStatus,
|
|
||||||
} from "@t3tools/tailscale";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
|
||||||
|
|
||||||
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
|
|
||||||
|
|
||||||
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
|
||||||
id: "tailscale",
|
|
||||||
label: "Tailscale",
|
|
||||||
kind: "private-network",
|
|
||||||
isAddon: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
function createTailscaleEndpoint(
|
|
||||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
|
||||||
): AdvertisedEndpoint {
|
|
||||||
return createAdvertisedEndpoint({
|
|
||||||
...input,
|
|
||||||
provider: TAILSCALE_ENDPOINT_PROVIDER,
|
|
||||||
source: "desktop-addon",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveTailscaleIpAdvertisedEndpoints(input: {
|
|
||||||
readonly port: number;
|
|
||||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
|
||||||
}): readonly AdvertisedEndpoint[] {
|
|
||||||
const seen = new Set<string>();
|
|
||||||
const endpoints: AdvertisedEndpoint[] = [];
|
|
||||||
|
|
||||||
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
|
|
||||||
if (!interfaceAddresses) continue;
|
|
||||||
|
|
||||||
for (const address of interfaceAddresses) {
|
|
||||||
if (address.internal) continue;
|
|
||||||
if (address.family !== "IPv4") continue;
|
|
||||||
if (!isTailscaleIpv4Address(address.address)) continue;
|
|
||||||
if (seen.has(address.address)) continue;
|
|
||||||
seen.add(address.address);
|
|
||||||
|
|
||||||
endpoints.push(
|
|
||||||
createTailscaleEndpoint({
|
|
||||||
id: `tailscale-ip:http://${address.address}:${input.port}`,
|
|
||||||
label: "Tailscale IP",
|
|
||||||
httpBaseUrl: `http://${address.address}:${input.port}`,
|
|
||||||
reachability: "private-network",
|
|
||||||
status: "available",
|
|
||||||
description: "Reachable from devices on the same Tailnet.",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return endpoints;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
|
|
||||||
readonly dnsName: string | null;
|
|
||||||
readonly serveEnabled: boolean;
|
|
||||||
readonly servePort?: number;
|
|
||||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
|
||||||
}): Promise<AdvertisedEndpoint | null> {
|
|
||||||
if (!input.dnsName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
|
|
||||||
magicDnsName: input.dnsName,
|
|
||||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
|
||||||
});
|
|
||||||
const isReachable = input.serveEnabled
|
|
||||||
? await (input.probe?.(httpBaseUrl) ??
|
|
||||||
Effect.runPromise(
|
|
||||||
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
|
|
||||||
Effect.provide(TailscaleDesktopLayer),
|
|
||||||
),
|
|
||||||
))
|
|
||||||
: false;
|
|
||||||
|
|
||||||
return createTailscaleEndpoint({
|
|
||||||
id: `tailscale-magicdns:${httpBaseUrl}`,
|
|
||||||
label: "Tailscale HTTPS",
|
|
||||||
httpBaseUrl,
|
|
||||||
reachability: "private-network",
|
|
||||||
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
|
|
||||||
status: isReachable ? "available" : "unavailable",
|
|
||||||
description: isReachable
|
|
||||||
? "HTTPS endpoint served by Tailscale Serve."
|
|
||||||
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resolveTailscaleAdvertisedEndpoints(input: {
|
|
||||||
readonly port: number;
|
|
||||||
readonly serveEnabled?: boolean;
|
|
||||||
readonly servePort?: number;
|
|
||||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
|
||||||
readonly statusJson?: string | null;
|
|
||||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
|
||||||
}): Promise<readonly AdvertisedEndpoint[]> {
|
|
||||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
|
||||||
const dnsName =
|
|
||||||
input.statusJson === undefined
|
|
||||||
? await Effect.runPromise(
|
|
||||||
readTailscaleStatus.pipe(
|
|
||||||
Effect.map((status) => status.magicDnsName),
|
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
|
||||||
Effect.provide(TailscaleDesktopLayer),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: input.statusJson
|
|
||||||
? await Effect.runPromise(
|
|
||||||
parseTailscaleMagicDnsName(input.statusJson).pipe(
|
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: null;
|
|
||||||
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
|
|
||||||
dnsName,
|
|
||||||
serveEnabled: input.serveEnabled === true,
|
|
||||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
|
||||||
...(input.probe === undefined ? {} : { probe: input.probe }),
|
|
||||||
});
|
|
||||||
|
|
||||||
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
|
|
||||||
}
|
|
||||||
@@ -3,8 +3,7 @@ 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,
|
||||||
CodexSettings,
|
ProviderKind,
|
||||||
ProviderDriverKind,
|
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -25,7 +24,10 @@ 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 { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||||
|
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||||
|
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.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";
|
||||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||||
@@ -34,16 +36,13 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
|
|||||||
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.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 { ServerSettingsService } from "../src/serverSettings.ts";
|
||||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||||
import {
|
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||||
NoOpProviderEventLoggers,
|
|
||||||
ProviderEventLoggers,
|
|
||||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
|
||||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||||
@@ -74,11 +73,6 @@ import {
|
|||||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||||
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
|
|
||||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
|
||||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
|
||||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
|
||||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -220,7 +214,7 @@ export interface OrchestrationIntegrationHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||||
readonly provider?: ProviderDriverKind;
|
readonly provider?: ProviderKind;
|
||||||
readonly realCodex?: boolean;
|
readonly realCodex?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,7 +225,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
|
||||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
const provider = options?.provider ?? "codex";
|
||||||
const useRealCodex = options?.realCodex === true;
|
const useRealCodex = options?.realCodex === true;
|
||||||
const adapterHarness = useRealCodex
|
const adapterHarness = useRealCodex
|
||||||
? null
|
? null
|
||||||
@@ -239,10 +233,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
provider,
|
provider,
|
||||||
});
|
});
|
||||||
const fakeRegistry = adapterHarness
|
const fakeRegistry = adapterHarness
|
||||||
? Layer.succeed(
|
? Layer.succeed(ProviderAdapterRegistry, {
|
||||||
ProviderAdapterRegistry,
|
getByProvider: (resolvedProvider) =>
|
||||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
resolvedProvider === adapterHarness.provider
|
||||||
)
|
? Effect.succeed(adapterHarness.adapter)
|
||||||
|
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||||
|
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||||
|
} as typeof ProviderAdapterRegistry.Service)
|
||||||
: null;
|
: null;
|
||||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||||
prefix: "t3-orchestration-integration-",
|
prefix: "t3-orchestration-integration-",
|
||||||
@@ -267,33 +264,34 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
const realCodexRegistry = Layer.effect(
|
const realCodexRegistry = Layer.effect(
|
||||||
ProviderAdapterRegistry,
|
ProviderAdapterRegistry,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const codexSettings = Schema.decodeSync(CodexSettings)({});
|
const codexAdapter = yield* CodexAdapter;
|
||||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
return {
|
||||||
return makeAdapterRegistryMock({
|
getByProvider: (resolvedProvider) =>
|
||||||
[ProviderDriverKind.make("codex")]: codexAdapter,
|
resolvedProvider === "codex"
|
||||||
});
|
? Effect.succeed(codexAdapter)
|
||||||
|
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||||
|
listProviders: () => Effect.succeed(["codex"] as const),
|
||||||
|
} as typeof ProviderAdapterRegistry.Service;
|
||||||
}),
|
}),
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Layer.provide(makeCodexAdapterLive()),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
);
|
);
|
||||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
|
||||||
const providerLayer = useRealCodex
|
const providerLayer = useRealCodex
|
||||||
? makeProviderServiceLive().pipe(
|
? makeProviderServiceLive().pipe(
|
||||||
Layer.provide(providerSessionDirectoryLayer),
|
Layer.provide(providerSessionDirectoryLayer),
|
||||||
Layer.provide(realCodexRegistry),
|
Layer.provide(realCodexRegistry),
|
||||||
Layer.provide(AnalyticsService.layerTest),
|
Layer.provide(AnalyticsService.layerTest),
|
||||||
Layer.provide(providerEventLoggersLayer),
|
|
||||||
)
|
)
|
||||||
: makeProviderServiceLive().pipe(
|
: makeProviderServiceLive().pipe(
|
||||||
Layer.provide(providerSessionDirectoryLayer),
|
Layer.provide(providerSessionDirectoryLayer),
|
||||||
Layer.provide(fakeRegistry!),
|
Layer.provide(fakeRegistry!),
|
||||||
Layer.provide(AnalyticsService.layerTest),
|
Layer.provide(AnalyticsService.layerTest),
|
||||||
Layer.provide(providerEventLoggersLayer),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
projectionSnapshotQueryLayer,
|
projectionSnapshotQueryLayer,
|
||||||
@@ -309,31 +307,31 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
Effect.succeed({ branch: input.newBranch }),
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
});
|
} as unknown as GitCoreShape);
|
||||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
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(gitWorkflowLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(textGenerationLayer),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(VcsStatusBroadcaster, {
|
Layer.succeed(GitStatusBroadcaster, {
|
||||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||||
refreshLocalStatus: () =>
|
refreshLocalStatus: () =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
isRepo: true,
|
isRepo: true,
|
||||||
hasPrimaryRemote: false,
|
hasOriginRemote: false,
|
||||||
isDefaultRef: true,
|
isDefaultBranch: true,
|
||||||
refName: "main",
|
branch: "main",
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||||
}),
|
}),
|
||||||
@@ -344,12 +342,11 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
WorkspaceEntriesLive.pipe(
|
WorkspaceEntriesLive.pipe(
|
||||||
Layer.provide(WorkspacePathsLive),
|
Layer.provide(WorkspacePathsLive),
|
||||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provide(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Layer.provideMerge(WorkspacePathsLive),
|
Layer.provideMerge(WorkspacePathsLive),
|
||||||
Layer.provideMerge(VcsProcess.layer),
|
|
||||||
);
|
);
|
||||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeIngestionLayer),
|
Layer.provideMerge(runtimeIngestionLayer),
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
ProviderTurnStartResult,
|
ProviderTurnStartResult,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
ProviderDriverKind,
|
ProviderKind,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Queue, Stream } from "effect";
|
import { Effect, Queue, Stream } from "effect";
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
|
|||||||
export type FixtureProviderRuntimeEvent = {
|
export type FixtureProviderRuntimeEvent = {
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
readonly eventId: EventId;
|
readonly eventId: EventId;
|
||||||
readonly provider: ProviderDriverKind;
|
readonly provider: ProviderKind;
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
readonly threadId: string;
|
readonly threadId: string;
|
||||||
readonly turnId?: string | undefined;
|
readonly turnId?: string | undefined;
|
||||||
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
|||||||
|
|
||||||
export interface TestProviderAdapterHarness {
|
export interface TestProviderAdapterHarness {
|
||||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||||
readonly provider: ProviderDriverKind;
|
readonly provider: ProviderKind;
|
||||||
readonly queueTurnResponse: (
|
readonly queueTurnResponse: (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
response: TestTurnResponse,
|
response: TestTurnResponse,
|
||||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeTestProviderAdapterHarnessOptions {
|
interface MakeTestProviderAdapterHarnessOptions {
|
||||||
readonly provider?: ProviderDriverKind;
|
readonly provider?: ProviderKind;
|
||||||
}
|
}
|
||||||
|
|
||||||
function nowIso(): string {
|
function nowIso(): string {
|
||||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function sessionNotFound(
|
function sessionNotFound(
|
||||||
provider: ProviderDriverKind,
|
provider: ProviderKind,
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): ProviderAdapterSessionNotFoundError {
|
): ProviderAdapterSessionNotFoundError {
|
||||||
return new ProviderAdapterSessionNotFoundError({
|
return new ProviderAdapterSessionNotFoundError({
|
||||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function missingSessionEffect(
|
function missingSessionEffect(
|
||||||
provider: ProviderDriverKind,
|
provider: ProviderKind,
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): Effect.Effect<never, ProviderAdapterError> {
|
): Effect.Effect<never, ProviderAdapterError> {
|
||||||
return Effect.fail(sessionNotFound(provider, threadId));
|
return Effect.fail(sessionNotFound(provider, threadId));
|
||||||
@@ -224,7 +224,7 @@ function missingSessionEffect(
|
|||||||
|
|
||||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
const provider = options?.provider ?? "codex";
|
||||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||||
let sessionCount = 0;
|
let sessionCount = 0;
|
||||||
const sessions = new Map<ThreadId, SessionState>();
|
const sessions = new Map<ThreadId, SessionState>();
|
||||||
@@ -257,9 +257,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
|||||||
|
|
||||||
const session: ProviderSession = {
|
const session: ProviderSession = {
|
||||||
provider,
|
provider,
|
||||||
...(input.providerInstanceId !== undefined
|
|
||||||
? { providerInstanceId: input.providerInstanceId }
|
|
||||||
: {}),
|
|
||||||
status: "ready",
|
status: "ready",
|
||||||
runtimeMode: input.runtimeMode,
|
runtimeMode: input.runtimeMode,
|
||||||
threadId,
|
threadId,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
|
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||||
|
|
||||||
const PROVIDER = ProviderDriverKind.make("codex");
|
const PROVIDER = "codex" as const;
|
||||||
const SESSION_ID = "fixture-session";
|
const SESSION_ID = "fixture-session";
|
||||||
const THREAD_ID = "fixture-thread";
|
const THREAD_ID = "fixture-thread";
|
||||||
const TURN_ID = "fixture-turn";
|
const TURN_ID = "fixture-turn";
|
||||||
|
|||||||
@@ -4,17 +4,14 @@ import path from "node:path";
|
|||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
CommandId,
|
CommandId,
|
||||||
defaultInstanceIdForDriver,
|
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
DEFAULT_MODEL,
|
|
||||||
DEFAULT_MODEL_BY_PROVIDER,
|
DEFAULT_MODEL_BY_PROVIDER,
|
||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderDriverKind,
|
ProviderKind,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
ModelSelection,
|
ModelSelection,
|
||||||
ProviderInstanceId,
|
|
||||||
} 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";
|
||||||
@@ -42,9 +39,7 @@ const PROJECT_ID = asProjectId("project-1");
|
|||||||
const THREAD_ID = ThreadId.make("thread-1");
|
const THREAD_ID = ThreadId.make("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 = ProviderDriverKind;
|
type IntegrationProvider = ProviderKind;
|
||||||
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
|
|
||||||
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
|
|
||||||
|
|
||||||
function nowIso() {
|
function nowIso() {
|
||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
@@ -79,11 +74,7 @@ function waitForSync<A>(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function runtimeBase(
|
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
|
||||||
eventId: string,
|
|
||||||
createdAt: string,
|
|
||||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
|
||||||
) {
|
|
||||||
return {
|
return {
|
||||||
eventId: asEventId(eventId),
|
eventId: asEventId(eventId),
|
||||||
provider,
|
provider,
|
||||||
@@ -93,7 +84,7 @@ function runtimeBase(
|
|||||||
|
|
||||||
function withHarness<A, E>(
|
function withHarness<A, E>(
|
||||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
provider: IntegrationProvider = "codex",
|
||||||
) {
|
) {
|
||||||
return Effect.acquireUseRelease(
|
return Effect.acquireUseRelease(
|
||||||
makeOrchestrationIntegrationHarness({ provider }),
|
makeOrchestrationIntegrationHarness({ provider }),
|
||||||
@@ -106,7 +97,7 @@ function withRealCodexHarness<A, E>(
|
|||||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||||
) {
|
) {
|
||||||
return Effect.acquireUseRelease(
|
return Effect.acquireUseRelease(
|
||||||
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
|
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
).pipe(Effect.provide(NodeServices.layer));
|
).pipe(Effect.provide(NodeServices.layer));
|
||||||
@@ -115,9 +106,8 @@ function withRealCodexHarness<A, E>(
|
|||||||
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_PROVIDER;
|
const provider = harness.adapterHarness?.provider ?? "codex";
|
||||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
|
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||||
const instanceId = defaultInstanceIdForDriver(provider);
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
@@ -126,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId,
|
provider,
|
||||||
model: defaultModel,
|
model: defaultModel,
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -139,7 +129,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId,
|
provider,
|
||||||
model: defaultModel,
|
model: defaultModel,
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -275,7 +265,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -288,7 +278,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -506,7 +496,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
|||||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||||
fallbackFromToHead: false,
|
fallbackFromToHead: false,
|
||||||
ignoreWhitespace: false,
|
|
||||||
});
|
});
|
||||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||||
|
|
||||||
@@ -515,7 +504,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
|||||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||||
fallbackFromToHead: false,
|
fallbackFromToHead: false,
|
||||||
ignoreWhitespace: false,
|
|
||||||
});
|
});
|
||||||
assert.equal(fullDiff.includes("README.md"), true);
|
assert.equal(fullDiff.includes("README.md"), true);
|
||||||
|
|
||||||
@@ -924,32 +912,20 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
||||||
"evt-claude-start-1",
|
|
||||||
"2026-02-24T10:10:00.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
||||||
"evt-claude-start-2",
|
|
||||||
"2026-02-24T10:10:00.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "Claude first turn.\n",
|
delta: "Claude first turn.\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
||||||
"evt-claude-start-3",
|
|
||||||
"2026-02-24T10:10:00.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -963,7 +939,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
|||||||
messageId: "msg-user-claude-initial",
|
messageId: "msg-user-claude-initial",
|
||||||
text: "Use Claude",
|
text: "Use Claude",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-sonnet-4-6",
|
model: "claude-sonnet-4-6",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -979,7 +955,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
|||||||
);
|
);
|
||||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
assert.equal(thread.session?.providerName, "claudeAgent");
|
||||||
}),
|
}),
|
||||||
CLAUDE_AGENT_PROVIDER,
|
"claudeAgent",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -993,32 +969,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
||||||
"evt-claude-recover-1",
|
|
||||||
"2026-02-24T10:11:00.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
||||||
"evt-claude-recover-2",
|
|
||||||
"2026-02-24T10:11:00.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "Turn before restart.\n",
|
delta: "Turn before restart.\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
||||||
"evt-claude-recover-3",
|
|
||||||
"2026-02-24T10:11:00.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1032,7 +996,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
|||||||
messageId: "msg-user-claude-recover-1",
|
messageId: "msg-user-claude-recover-1",
|
||||||
text: "Before restart",
|
text: "Before restart",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-sonnet-4-6",
|
model: "claude-sonnet-4-6",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1054,32 +1018,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
||||||
"evt-claude-recover-4",
|
|
||||||
"2026-02-24T10:11:01.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
||||||
"evt-claude-recover-5",
|
|
||||||
"2026-02-24T10:11:01.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "Turn after restart.\n",
|
delta: "Turn after restart.\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
||||||
"evt-claude-recover-6",
|
|
||||||
"2026-02-24T10:11:01.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1111,7 +1063,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
|||||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
||||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||||
}),
|
}),
|
||||||
CLAUDE_AGENT_PROVIDER,
|
"claudeAgent",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1125,21 +1077,13 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
||||||
"evt-claude-approval-1",
|
|
||||||
"2026-02-24T10:12:00.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "approval.requested",
|
type: "approval.requested",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
||||||
"evt-claude-approval-2",
|
|
||||||
"2026-02-24T10:12:00.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
requestId: APPROVAL_REQUEST_ID,
|
||||||
@@ -1148,11 +1092,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
||||||
"evt-claude-approval-3",
|
|
||||||
"2026-02-24T10:12:00.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1166,7 +1106,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
messageId: "msg-user-claude-approval",
|
messageId: "msg-user-claude-approval",
|
||||||
text: "Need approval",
|
text: "Need approval",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-sonnet-4-6",
|
model: "claude-sonnet-4-6",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1197,7 +1137,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
);
|
);
|
||||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||||
}),
|
}),
|
||||||
CLAUDE_AGENT_PROVIDER,
|
"claudeAgent",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1211,32 +1151,20 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
||||||
"evt-claude-interrupt-1",
|
|
||||||
"2026-02-24T10:13:00.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
||||||
"evt-claude-interrupt-2",
|
|
||||||
"2026-02-24T10:13:00.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "Long running output.\n",
|
delta: "Long running output.\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
||||||
"evt-claude-interrupt-3",
|
|
||||||
"2026-02-24T10:13:00.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1250,7 +1178,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|||||||
messageId: "msg-user-claude-interrupt",
|
messageId: "msg-user-claude-interrupt",
|
||||||
text: "Start long turn",
|
text: "Start long turn",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-sonnet-4-6",
|
model: "claude-sonnet-4-6",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1278,7 +1206,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|||||||
);
|
);
|
||||||
assert.equal(interruptCalls.length, 1);
|
assert.equal(interruptCalls.length, 1);
|
||||||
}),
|
}),
|
||||||
CLAUDE_AGENT_PROVIDER,
|
"claudeAgent",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1292,32 +1220,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
||||||
"evt-claude-revert-1",
|
|
||||||
"2026-02-24T10:14:00.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
||||||
"evt-claude-revert-2",
|
|
||||||
"2026-02-24T10:14:00.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "README -> v2\n",
|
delta: "README -> v2\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
||||||
"evt-claude-revert-3",
|
|
||||||
"2026-02-24T10:14:00.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1335,7 +1251,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
messageId: "msg-user-claude-revert-1",
|
messageId: "msg-user-claude-revert-1",
|
||||||
text: "First Claude edit",
|
text: "First Claude edit",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-sonnet-4-6",
|
model: "claude-sonnet-4-6",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1350,32 +1266,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
events: [
|
events: [
|
||||||
{
|
{
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
||||||
"evt-claude-revert-4",
|
|
||||||
"2026-02-24T10:14:01.000Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "message.delta",
|
type: "message.delta",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
||||||
"evt-claude-revert-5",
|
|
||||||
"2026-02-24T10:14:01.050Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
delta: "README -> v3\n",
|
delta: "README -> v3\n",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
...runtimeBase(
|
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
||||||
"evt-claude-revert-6",
|
|
||||||
"2026-02-24T10:14:01.100Z",
|
|
||||||
CLAUDE_AGENT_PROVIDER,
|
|
||||||
),
|
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnId: FIXTURE_TURN_ID,
|
turnId: FIXTURE_TURN_ID,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
@@ -1426,6 +1330,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
);
|
);
|
||||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||||
}),
|
}),
|
||||||
CLAUDE_AGENT_PROVIDER,
|
"claudeAgent",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -1,17 +1,13 @@
|
|||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
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";
|
||||||
|
|
||||||
|
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
|
||||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||||
import {
|
|
||||||
NoOpProviderEventLoggers,
|
|
||||||
ProviderEventLoggers,
|
|
||||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
|
||||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||||
import {
|
import {
|
||||||
ProviderService,
|
ProviderService,
|
||||||
@@ -33,8 +29,6 @@ import {
|
|||||||
codexTurnTextFixture,
|
codexTurnTextFixture,
|
||||||
} from "./fixtures/providerRuntime.ts";
|
} from "./fixtures/providerRuntime.ts";
|
||||||
|
|
||||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
|
||||||
|
|
||||||
const makeWorkspaceDirectory = Effect.gen(function* () {
|
const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const pathService = yield* Path.Path;
|
const pathService = yield* Path.Path;
|
||||||
@@ -53,9 +47,13 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
|||||||
const cwd = yield* makeWorkspaceDirectory;
|
const cwd = yield* makeWorkspaceDirectory;
|
||||||
const harness = yield* makeTestProviderAdapterHarness();
|
const harness = yield* makeTestProviderAdapterHarness();
|
||||||
|
|
||||||
const registry = makeAdapterRegistryMock({
|
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
getByProvider: (provider) =>
|
||||||
});
|
provider === "codex"
|
||||||
|
? Effect.succeed(harness.adapter)
|
||||||
|
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||||
|
listProviders: () => Effect.succeed(["codex"]),
|
||||||
|
};
|
||||||
|
|
||||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||||
@@ -66,7 +64,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
|||||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||||
AnalyticsService.layerTest,
|
AnalyticsService.layerTest,
|
||||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
|
||||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||||
|
|
||||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||||
@@ -127,8 +124,7 @@ it.live("replays typed runtime fixture events", () =>
|
|||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||||
threadId: ThreadId.make("thread-integration-typed"),
|
threadId: ThreadId.make("thread-integration-typed"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
providerInstanceId: codexInstanceId,
|
|
||||||
cwd: fixture.cwd,
|
cwd: fixture.cwd,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
});
|
});
|
||||||
@@ -146,10 +142,6 @@ it.live("replays typed runtime fixture events", () =>
|
|||||||
observedEvents.map((event) => event.type),
|
observedEvents.map((event) => event.type),
|
||||||
codexTurnTextFixture.map((event) => event.type),
|
codexTurnTextFixture.map((event) => event.type),
|
||||||
);
|
);
|
||||||
assert.deepEqual(
|
|
||||||
observedEvents.map((event) => event.providerInstanceId),
|
|
||||||
codexTurnTextFixture.map(() => codexInstanceId),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.provide(fixture.layer));
|
}).pipe(Effect.provide(fixture.layer));
|
||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
@@ -164,8 +156,7 @@ it.live("replays file-changing fixture turn events", () =>
|
|||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||||
threadId: ThreadId.make("thread-integration-tools"),
|
threadId: ThreadId.make("thread-integration-tools"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
providerInstanceId: codexInstanceId,
|
|
||||||
cwd: fixture.cwd,
|
cwd: fixture.cwd,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
});
|
});
|
||||||
@@ -201,8 +192,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
|||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||||
threadId: ThreadId.make("thread-integration-multi"),
|
threadId: ThreadId.make("thread-integration-multi"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
providerInstanceId: codexInstanceId,
|
|
||||||
cwd: fixture.cwd,
|
cwd: fixture.cwd,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
});
|
});
|
||||||
@@ -253,8 +243,7 @@ it.live("rolls back provider conversation state only", () =>
|
|||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||||
threadId: ThreadId.make("thread-integration-rollback"),
|
threadId: ThreadId.make("thread-integration-rollback"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
providerInstanceId: codexInstanceId,
|
|
||||||
cwd: fixture.cwd,
|
cwd: fixture.cwd,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.0.22",
|
"version": "0.0.20",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"build": "node scripts/cli.ts build",
|
"build": "node scripts/cli.ts build",
|
||||||
"build:bundle": "tsdown",
|
"build:bundle": "tsdown",
|
||||||
"start": "node dist/bin.mjs",
|
"start": "node dist/bin.mjs",
|
||||||
|
"prepare": "effect-language-service patch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||||
@@ -29,7 +30,7 @@
|
|||||||
"@effect/platform-node": "catalog:",
|
"@effect/platform-node": "catalog:",
|
||||||
"@effect/sql-sqlite-bun": "catalog:",
|
"@effect/sql-sqlite-bun": "catalog:",
|
||||||
"@opencode-ai/sdk": "^1.3.15",
|
"@opencode-ai/sdk": "^1.3.15",
|
||||||
"@pierre/diffs": "catalog:",
|
"@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"
|
||||||
@@ -39,7 +40,6 @@
|
|||||||
"@effect/vitest": "catalog:",
|
"@effect/vitest": "catalog:",
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
"@t3tools/shared": "workspace:*",
|
"@t3tools/shared": "workspace:*",
|
||||||
"@t3tools/tailscale": "workspace:*",
|
|
||||||
"@t3tools/web": "workspace:*",
|
"@t3tools/web": "workspace:*",
|
||||||
"@types/bun": "catalog:",
|
"@types/bun": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
|
|||||||
@@ -6,14 +6,9 @@ import { Command } from "effect/unstable/cli";
|
|||||||
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
import { cli } from "./cli.ts";
|
import { cli } from "./cli.ts";
|
||||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
|
||||||
import packageJson from "../package.json" with { type: "json" };
|
import packageJson from "../package.json" with { type: "json" };
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(
|
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||||
NodeServices.layer,
|
|
||||||
NetService.layer,
|
|
||||||
AnalyticsService.layerTest,
|
|
||||||
);
|
|
||||||
|
|
||||||
Command.run(cli, { version: packageJson.version }).pipe(
|
Command.run(cli, { version: packageJson.version }).pipe(
|
||||||
Effect.scoped,
|
Effect.scoped,
|
||||||
|
|||||||
@@ -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 type { VcsError } from "@t3tools/contracts";
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||||
@@ -35,6 +35,9 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
|
export type CheckpointStoreError =
|
||||||
|
| GitCommandError
|
||||||
|
| CheckpointInvariantError
|
||||||
|
| CheckpointUnavailableError;
|
||||||
|
|
||||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||||
@@ -48,7 +48,6 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
readonly fromCheckpointRef: CheckpointRef;
|
readonly fromCheckpointRef: CheckpointRef;
|
||||||
readonly toCheckpointRef: CheckpointRef;
|
readonly toCheckpointRef: CheckpointRef;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
readonly ignoreWhitespace: boolean;
|
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||||
@@ -69,14 +68,9 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
return true;
|
return true;
|
||||||
}),
|
}),
|
||||||
restoreCheckpoint: () => Effect.succeed(true),
|
restoreCheckpoint: () => Effect.succeed(true),
|
||||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
diffCheckpointsCalls.push({
|
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||||
fromCheckpointRef,
|
|
||||||
toCheckpointRef,
|
|
||||||
cwd,
|
|
||||||
ignoreWhitespace,
|
|
||||||
});
|
|
||||||
return "diff patch";
|
return "diff patch";
|
||||||
}),
|
}),
|
||||||
deleteCheckpointRefs: () => Effect.void,
|
deleteCheckpointRefs: () => Effect.void,
|
||||||
@@ -86,13 +80,10 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getCommandReadModel: () =>
|
|
||||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
|
||||||
getSnapshot: () =>
|
getSnapshot: () =>
|
||||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||||
getShellSnapshot: () =>
|
getShellSnapshot: () =>
|
||||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
|
||||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||||
@@ -111,7 +102,6 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
threadId,
|
threadId,
|
||||||
fromTurnCount: 0,
|
fromTurnCount: 0,
|
||||||
toTurnCount: 1,
|
toTurnCount: 1,
|
||||||
ignoreWhitespace: true,
|
|
||||||
});
|
});
|
||||||
}).pipe(Effect.provide(layer)),
|
}).pipe(Effect.provide(layer)),
|
||||||
);
|
);
|
||||||
@@ -123,7 +113,6 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
cwd: "/tmp/workspace",
|
cwd: "/tmp/workspace",
|
||||||
fromCheckpointRef: expectedFromRef,
|
fromCheckpointRef: expectedFromRef,
|
||||||
toCheckpointRef,
|
toCheckpointRef,
|
||||||
ignoreWhitespace: true,
|
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
@@ -134,70 +123,6 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("defaults to hide whitespace changes", async () => {
|
|
||||||
const projectId = ProjectId.make("project-default-whitespace");
|
|
||||||
const threadId = ThreadId.make("thread-default-whitespace");
|
|
||||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
|
||||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
|
||||||
|
|
||||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
|
||||||
projectId,
|
|
||||||
threadId,
|
|
||||||
workspaceRoot: "/tmp/workspace",
|
|
||||||
worktreePath: null,
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
checkpointRef: toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
const checkpointStore: CheckpointStoreShape = {
|
|
||||||
isGitRepository: () => Effect.succeed(true),
|
|
||||||
captureCheckpoint: () => Effect.void,
|
|
||||||
hasCheckpointRef: () => Effect.succeed(true),
|
|
||||||
restoreCheckpoint: () => Effect.succeed(true),
|
|
||||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
|
||||||
return "diff patch";
|
|
||||||
}),
|
|
||||||
deleteCheckpointRefs: () => Effect.void,
|
|
||||||
};
|
|
||||||
|
|
||||||
const layer = CheckpointDiffQueryLive.pipe(
|
|
||||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
|
||||||
Layer.provideMerge(
|
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
|
||||||
getCommandReadModel: () =>
|
|
||||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
|
||||||
getSnapshot: () =>
|
|
||||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
|
||||||
getShellSnapshot: () =>
|
|
||||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
|
||||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
|
||||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
|
||||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
|
||||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
|
||||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
|
||||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
|
||||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const query = yield* CheckpointDiffQuery;
|
|
||||||
return yield* query.getTurnDiff({
|
|
||||||
threadId,
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
}).pipe(Effect.provide(layer)),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fails when the thread is missing from the snapshot", async () => {
|
it("fails when the thread is missing from the snapshot", async () => {
|
||||||
const threadId = ThreadId.make("thread-missing");
|
const threadId = ThreadId.make("thread-missing");
|
||||||
|
|
||||||
@@ -214,13 +139,10 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getCommandReadModel: () =>
|
|
||||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
|
||||||
getSnapshot: () =>
|
getSnapshot: () =>
|
||||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||||
getShellSnapshot: () =>
|
getShellSnapshot: () =>
|
||||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
|
||||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ const make = Effect.gen(function* () {
|
|||||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||||
function* (input) {
|
function* (input) {
|
||||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
|
||||||
|
|
||||||
if (input.fromTurnCount === input.toTurnCount) {
|
if (input.fromTurnCount === input.toTurnCount) {
|
||||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||||
@@ -132,7 +131,6 @@ const make = Effect.gen(function* () {
|
|||||||
fromCheckpointRef,
|
fromCheckpointRef,
|
||||||
toCheckpointRef,
|
toCheckpointRef,
|
||||||
fallbackFromToHead: false,
|
fallbackFromToHead: false,
|
||||||
ignoreWhitespace,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||||
@@ -159,7 +157,6 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: input.threadId,
|
threadId: input.threadId,
|
||||||
fromTurnCount: 0,
|
fromTurnCount: 0,
|
||||||
toTurnCount: input.toTurnCount,
|
toTurnCount: input.toTurnCount,
|
||||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
|
||||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -8,27 +8,24 @@ import { describe, expect } from "vitest";
|
|||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
import type { VcsError } from "@t3tools/contracts";
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||||
prefix: "t3-checkpoint-store-test-",
|
prefix: "t3-checkpoint-store-test-",
|
||||||
});
|
});
|
||||||
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||||
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
|
Layer.provide(ServerConfigLayer),
|
||||||
|
Layer.provide(NodeServices.layer),
|
||||||
|
);
|
||||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||||
Layer.provideMerge(VcsDriverTestLayer),
|
Layer.provide(GitCoreTestLayer),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provide(NodeServices.layer),
|
||||||
);
|
|
||||||
const TestLayer = CheckpointStoreTestLayer.pipe(
|
|
||||||
Layer.provideMerge(VcsProcessTestLayer),
|
|
||||||
Layer.provideMerge(VcsDriverTestLayer),
|
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
);
|
||||||
|
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||||
|
|
||||||
function makeTmpDir(
|
function makeTmpDir(
|
||||||
prefix = "checkpoint-store-test-",
|
prefix = "checkpoint-store-test-",
|
||||||
@@ -52,12 +49,11 @@ function writeTextFile(
|
|||||||
function git(
|
function git(
|
||||||
cwd: string,
|
cwd: string,
|
||||||
args: ReadonlyArray<string>,
|
args: ReadonlyArray<string>,
|
||||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const process = yield* VcsProcess.VcsProcess;
|
const gitCore = yield* GitCore;
|
||||||
const result = yield* process.run({
|
const result = yield* gitCore.execute({
|
||||||
operation: "CheckpointStore.test.git",
|
operation: "CheckpointStore.test.git",
|
||||||
command: "git",
|
|
||||||
cwd,
|
cwd,
|
||||||
args,
|
args,
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
@@ -70,11 +66,12 @@ function initRepoWithCommit(
|
|||||||
cwd: string,
|
cwd: string,
|
||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
void,
|
void,
|
||||||
VcsError | PlatformError.PlatformError,
|
GitCommandError | PlatformError.PlatformError,
|
||||||
VcsProcess.VcsProcess | FileSystem.FileSystem
|
GitCore | FileSystem.FileSystem
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
yield* git(cwd, ["init"]);
|
const core = yield* GitCore;
|
||||||
|
yield* core.initRepo({ cwd });
|
||||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
||||||
@@ -114,7 +111,6 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
|||||||
cwd: tmp,
|
cwd: tmp,
|
||||||
fromCheckpointRef,
|
fromCheckpointRef,
|
||||||
toCheckpointRef,
|
toCheckpointRef,
|
||||||
ignoreWhitespace: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(diff).toContain("diff --git");
|
expect(diff).toContain("diff --git");
|
||||||
@@ -122,80 +118,5 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
|||||||
expect(diff).toContain("+line 04999");
|
expect(diff).toContain("+line 04999");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("can hide indentation churn when changes wrap existing lines", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const tmp = yield* makeTmpDir();
|
|
||||||
yield* initRepoWithCommit(tmp);
|
|
||||||
const checkpointStore = yield* CheckpointStore;
|
|
||||||
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
|
|
||||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
|
||||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
|
||||||
|
|
||||||
const componentPath = path.join(tmp, "Component.tsx");
|
|
||||||
yield* writeTextFile(
|
|
||||||
componentPath,
|
|
||||||
[
|
|
||||||
"export function View() {",
|
|
||||||
" return (",
|
|
||||||
" <section>",
|
|
||||||
" <h1>Title</h1>",
|
|
||||||
" <p>Body</p>",
|
|
||||||
" </section>",
|
|
||||||
" );",
|
|
||||||
"}",
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: fromCheckpointRef,
|
|
||||||
});
|
|
||||||
yield* writeTextFile(
|
|
||||||
componentPath,
|
|
||||||
[
|
|
||||||
"export function View() {",
|
|
||||||
" return (",
|
|
||||||
" <section>",
|
|
||||||
" {isReady ? (",
|
|
||||||
" <div>",
|
|
||||||
" <h1>Title</h1>",
|
|
||||||
" <p>Body</p>",
|
|
||||||
" </div>",
|
|
||||||
" ) : null}",
|
|
||||||
" </section>",
|
|
||||||
" );",
|
|
||||||
"}",
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
const normalDiff = yield* checkpointStore.diffCheckpoints({
|
|
||||||
cwd: tmp,
|
|
||||||
fromCheckpointRef,
|
|
||||||
toCheckpointRef,
|
|
||||||
ignoreWhitespace: false,
|
|
||||||
});
|
|
||||||
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
|
|
||||||
cwd: tmp,
|
|
||||||
fromCheckpointRef,
|
|
||||||
toCheckpointRef,
|
|
||||||
ignoreWhitespace: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(normalDiff).toContain("diff --git");
|
|
||||||
expect(normalDiff).toContain("- <h1>Title</h1>");
|
|
||||||
expect(normalDiff).toContain("+ <h1>Title</h1>");
|
|
||||||
expect(whitespaceIgnoredDiff).toContain("diff --git");
|
|
||||||
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
|
|
||||||
expect(whitespaceIgnoredDiff).toContain("+ <div>");
|
|
||||||
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
|
|
||||||
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -14,8 +14,8 @@ 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 { VcsProcessExitError } from "@t3tools/contracts";
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
import { GitCore } from "../../git/Services/GitCore.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";
|
||||||
|
|
||||||
@@ -24,26 +24,10 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
|||||||
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 vcsRegistry = yield* VcsDriverRegistry;
|
const git = yield* GitCore;
|
||||||
const vcs = {
|
|
||||||
execute: (input: {
|
|
||||||
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;
|
|
||||||
}) =>
|
|
||||||
vcsRegistry
|
|
||||||
.resolve({ cwd: input.cwd, requestedKind: "git" })
|
|
||||||
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
|
|
||||||
};
|
|
||||||
|
|
||||||
const resolveHeadCommit = (cwd: string) =>
|
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||||
vcs
|
git
|
||||||
.execute({
|
.execute({
|
||||||
operation: "CheckpointStore.resolveHeadCommit",
|
operation: "CheckpointStore.resolveHeadCommit",
|
||||||
cwd,
|
cwd,
|
||||||
@@ -52,7 +36,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.map((result) => {
|
Effect.map((result) => {
|
||||||
if (result.exitCode !== 0) {
|
if (result.code !== 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const commit = result.stdout.trim();
|
const commit = result.stdout.trim();
|
||||||
@@ -60,18 +44,21 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const hasHeadCommit = (cwd: string) =>
|
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||||
vcs
|
git
|
||||||
.execute({
|
.execute({
|
||||||
operation: "CheckpointStore.hasHeadCommit",
|
operation: "CheckpointStore.hasHeadCommit",
|
||||||
cwd,
|
cwd,
|
||||||
args: ["rev-parse", "--verify", "HEAD"],
|
args: ["rev-parse", "--verify", "HEAD"],
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
})
|
})
|
||||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
.pipe(Effect.map((result) => result.code === 0));
|
||||||
|
|
||||||
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
|
const resolveCheckpointCommit = (
|
||||||
vcs
|
cwd: string,
|
||||||
|
checkpointRef: CheckpointRef,
|
||||||
|
): Effect.Effect<string | null, GitCommandError> =>
|
||||||
|
git
|
||||||
.execute({
|
.execute({
|
||||||
operation: "CheckpointStore.resolveCheckpointCommit",
|
operation: "CheckpointStore.resolveCheckpointCommit",
|
||||||
cwd,
|
cwd,
|
||||||
@@ -80,7 +67,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.map((result) => {
|
Effect.map((result) => {
|
||||||
if (result.exitCode !== 0) {
|
if (result.code !== 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const commit = result.stdout.trim();
|
const commit = result.stdout.trim();
|
||||||
@@ -89,7 +76,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||||
vcs
|
git
|
||||||
.execute({
|
.execute({
|
||||||
operation: "CheckpointStore.isGitRepository",
|
operation: "CheckpointStore.isGitRepository",
|
||||||
cwd,
|
cwd,
|
||||||
@@ -97,7 +84,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
|
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
|
||||||
Effect.catch(() => Effect.succeed(false)),
|
Effect.catch(() => Effect.succeed(false)),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -121,7 +108,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
if (headExists) {
|
if (headExists) {
|
||||||
yield* vcs.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["read-tree", "HEAD"],
|
args: ["read-tree", "HEAD"],
|
||||||
@@ -129,14 +116,14 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* vcs.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* vcs.execute({
|
const writeTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["write-tree"],
|
args: ["write-tree"],
|
||||||
@@ -144,17 +131,16 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
const treeOid = writeTreeResult.stdout.trim();
|
const treeOid = writeTreeResult.stdout.trim();
|
||||||
if (treeOid.length === 0) {
|
if (treeOid.length === 0) {
|
||||||
return yield* new VcsProcessExitError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git write-tree",
|
command: "git write-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
exitCode: 0,
|
|
||||||
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* vcs.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],
|
||||||
@@ -162,16 +148,15 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
const commitOid = commitTreeResult.stdout.trim();
|
const commitOid = commitTreeResult.stdout.trim();
|
||||||
if (commitOid.length === 0) {
|
if (commitOid.length === 0) {
|
||||||
return yield* new VcsProcessExitError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git commit-tree",
|
command: "git commit-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
exitCode: 0,
|
|
||||||
detail: "git commit-tree returned an empty commit oid.",
|
detail: "git commit-tree returned an empty commit oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* vcs.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", input.checkpointRef, commitOid],
|
args: ["update-ref", input.checkpointRef, commitOid],
|
||||||
@@ -212,12 +197,12 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* vcs.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||||
});
|
});
|
||||||
yield* vcs.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["clean", "-fd", "--", "."],
|
args: ["clean", "-fd", "--", "."],
|
||||||
@@ -225,7 +210,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
if (headExists) {
|
if (headExists) {
|
||||||
yield* vcs.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["reset", "--quiet", "--", "."],
|
args: ["reset", "--quiet", "--", "."],
|
||||||
@@ -250,29 +235,18 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!fromCommitOid || !toCommitOid) {
|
if (!fromCommitOid || !toCommitOid) {
|
||||||
return yield* new VcsProcessExitError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git diff",
|
command: "git diff",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
exitCode: 1,
|
|
||||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const diffArgs = [
|
const result = yield* git.execute({
|
||||||
"diff",
|
|
||||||
"--patch",
|
|
||||||
"--minimal",
|
|
||||||
"--no-color",
|
|
||||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
|
||||||
fromCommitOid,
|
|
||||||
toCommitOid,
|
|
||||||
];
|
|
||||||
|
|
||||||
const result = yield* vcs.execute({
|
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: diffArgs,
|
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -288,7 +262,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.checkpointRefs,
|
input.checkpointRefs,
|
||||||
(checkpointRef) =>
|
(checkpointRef) =>
|
||||||
vcs.execute({
|
git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", "-d", checkpointRef],
|
args: ["update-ref", "-d", checkpointRef],
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ export interface DiffCheckpointsInput {
|
|||||||
readonly fromCheckpointRef: CheckpointRef;
|
readonly fromCheckpointRef: CheckpointRef;
|
||||||
readonly toCheckpointRef: CheckpointRef;
|
readonly toCheckpointRef: CheckpointRef;
|
||||||
readonly fallbackFromToHead?: boolean;
|
readonly fallbackFromToHead?: boolean;
|
||||||
readonly ignoreWhitespace: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DeleteCheckpointRefsInput {
|
export interface DeleteCheckpointRefsInput {
|
||||||
|
|||||||
@@ -46,8 +46,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -89,8 +87,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -112,8 +108,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.some(true),
|
autoBootstrapProjectFromCwd: Option.some(true),
|
||||||
logWebSocketEvents: Option.some(true),
|
logWebSocketEvents: Option.some(true),
|
||||||
tailscaleServeEnabled: Option.some(true),
|
|
||||||
tailscaleServePort: Option.some(8443),
|
|
||||||
},
|
},
|
||||||
Option.some("Debug"),
|
Option.some("Debug"),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -155,8 +149,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: true,
|
autoBootstrapProjectFromCwd: true,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: true,
|
|
||||||
tailscaleServePort: 8443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -169,8 +161,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
noBrowser: true,
|
noBrowser: true,
|
||||||
autoBootstrapProjectFromCwd: true,
|
autoBootstrapProjectFromCwd: true,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||||
|
|
||||||
@@ -186,8 +176,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.some(false),
|
autoBootstrapProjectFromCwd: Option.some(false),
|
||||||
logWebSocketEvents: Option.some(false),
|
logWebSocketEvents: Option.some(false),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -224,8 +212,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -243,8 +229,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
noBrowser: true,
|
noBrowser: true,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||||
});
|
});
|
||||||
@@ -262,8 +246,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -299,8 +281,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||||
}),
|
}),
|
||||||
@@ -325,8 +305,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -368,8 +346,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||||
|
|
||||||
@@ -385,8 +361,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.some("Debug"),
|
Option.some("Debug"),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -425,8 +399,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: true,
|
autoBootstrapProjectFromCwd: true,
|
||||||
logWebSocketEvents: true,
|
logWebSocketEvents: true,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -460,8 +432,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -493,8 +463,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -517,8 +485,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
Option.none(),
|
Option.none(),
|
||||||
{
|
{
|
||||||
@@ -556,8 +522,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { Command } from "effect/unstable/cli";
|
|||||||
|
|
||||||
import { cli } from "./cli.ts";
|
import { cli } from "./cli.ts";
|
||||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||||
|
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||||
import {
|
import {
|
||||||
@@ -32,13 +33,8 @@ import {
|
|||||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(
|
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||||
NodeServices.layer,
|
|
||||||
NetService.layer,
|
|
||||||
AnalyticsService.layerTest,
|
|
||||||
);
|
|
||||||
|
|
||||||
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
||||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
||||||
@@ -80,8 +76,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
|||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
} satisfies ServerConfigShape;
|
} satisfies ServerConfigShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -320,8 +314,8 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
|||||||
"--base-dir",
|
"--base-dir",
|
||||||
baseDir,
|
baseDir,
|
||||||
]);
|
]);
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
const addedProject = readModel.projects.find(
|
const addedProject = readModel.projects.find(
|
||||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -78,8 +78,6 @@ const BootstrapEnvelopeSchema = Schema.Struct({
|
|||||||
desktopBootstrapToken: Schema.optional(Schema.String),
|
desktopBootstrapToken: Schema.optional(Schema.String),
|
||||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||||
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
|
|
||||||
tailscaleServePort: Schema.optional(PortSchema),
|
|
||||||
otlpTracesUrl: Schema.optional(Schema.String),
|
otlpTracesUrl: Schema.optional(Schema.String),
|
||||||
otlpMetricsUrl: Schema.optional(Schema.String),
|
otlpMetricsUrl: Schema.optional(Schema.String),
|
||||||
});
|
});
|
||||||
@@ -128,17 +126,6 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
|||||||
Flag.withAlias("log-ws-events"),
|
Flag.withAlias("log-ws-events"),
|
||||||
Flag.optional,
|
Flag.optional,
|
||||||
);
|
);
|
||||||
const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
|
|
||||||
Flag.withDescription(
|
|
||||||
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
|
|
||||||
),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
|
|
||||||
Flag.withSchema(PortSchema),
|
|
||||||
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
|
|
||||||
Flag.optional,
|
|
||||||
);
|
|
||||||
|
|
||||||
const EnvServerConfig = Config.all({
|
const EnvServerConfig = Config.all({
|
||||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||||
@@ -187,14 +174,6 @@ const EnvServerConfig = Config.all({
|
|||||||
Config.option,
|
Config.option,
|
||||||
Config.map(Option.getOrUndefined),
|
Config.map(Option.getOrUndefined),
|
||||||
),
|
),
|
||||||
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
|
|
||||||
Config.option,
|
|
||||||
Config.map(Option.getOrUndefined),
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
interface CliServerFlags {
|
interface CliServerFlags {
|
||||||
@@ -208,8 +187,6 @@ interface CliServerFlags {
|
|||||||
readonly bootstrapFd: Option.Option<number>;
|
readonly bootstrapFd: Option.Option<number>;
|
||||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||||
readonly tailscaleServeEnabled: Option.Option<boolean>;
|
|
||||||
readonly tailscaleServePort: Option.Option<number>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CliAuthLocationFlags {
|
interface CliAuthLocationFlags {
|
||||||
@@ -256,8 +233,6 @@ export const resolveServerConfig = (
|
|||||||
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
||||||
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
||||||
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
||||||
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
|
|
||||||
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
|
|
||||||
} satisfies CliServerFlags;
|
} satisfies CliServerFlags;
|
||||||
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
||||||
const bootstrapEnvelope =
|
const bootstrapEnvelope =
|
||||||
@@ -348,22 +323,6 @@ export const resolveServerConfig = (
|
|||||||
),
|
),
|
||||||
() => Boolean(devUrl),
|
() => Boolean(devUrl),
|
||||||
);
|
);
|
||||||
const tailscaleServeEnabled = Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
normalizedFlags.tailscaleServeEnabled,
|
|
||||||
Option.fromUndefinedOr(env.tailscaleServeEnabled),
|
|
||||||
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
|
|
||||||
),
|
|
||||||
() => false,
|
|
||||||
);
|
|
||||||
const tailscaleServePort = Option.getOrElse(
|
|
||||||
resolveOptionPrecedence(
|
|
||||||
normalizedFlags.tailscaleServePort,
|
|
||||||
Option.fromUndefinedOr(env.tailscaleServePort),
|
|
||||||
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
|
|
||||||
),
|
|
||||||
() => 443,
|
|
||||||
);
|
|
||||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||||
const host = Option.getOrElse(
|
const host = Option.getOrElse(
|
||||||
resolveOptionPrecedence(
|
resolveOptionPrecedence(
|
||||||
@@ -406,8 +365,6 @@ export const resolveServerConfig = (
|
|||||||
desktopBootstrapToken,
|
desktopBootstrapToken,
|
||||||
autoBootstrapProjectFromCwd,
|
autoBootstrapProjectFromCwd,
|
||||||
logWebSocketEvents,
|
logWebSocketEvents,
|
||||||
tailscaleServeEnabled,
|
|
||||||
tailscaleServePort,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
@@ -429,8 +386,6 @@ const resolveCliAuthConfig = (
|
|||||||
bootstrapFd: Option.none(),
|
bootstrapFd: Option.none(),
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
logWebSocketEvents: Option.none(),
|
logWebSocketEvents: Option.none(),
|
||||||
tailscaleServeEnabled: Option.none(),
|
|
||||||
tailscaleServePort: Option.none(),
|
|
||||||
},
|
},
|
||||||
cliLogLevel,
|
cliLogLevel,
|
||||||
);
|
);
|
||||||
@@ -811,8 +766,6 @@ const sharedServerCommandFlags = {
|
|||||||
bootstrapFd: bootstrapFdFlag,
|
bootstrapFd: bootstrapFdFlag,
|
||||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||||
logWebSocketEvents: logWebSocketEventsFlag,
|
logWebSocketEvents: logWebSocketEventsFlag,
|
||||||
tailscaleServeEnabled: tailscaleServeFlag,
|
|
||||||
tailscaleServePort: tailscaleServePortFlag,
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const authLocationFlags = sharedServerLocationFlags;
|
const authLocationFlags = sharedServerLocationFlags;
|
||||||
|
|||||||
@@ -65,8 +65,6 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
|||||||
readonly desktopBootstrapToken: string | undefined;
|
readonly desktopBootstrapToken: string | undefined;
|
||||||
readonly autoBootstrapProjectFromCwd: boolean;
|
readonly autoBootstrapProjectFromCwd: boolean;
|
||||||
readonly logWebSocketEvents: boolean;
|
readonly logWebSocketEvents: boolean;
|
||||||
readonly tailscaleServeEnabled: boolean;
|
|
||||||
readonly tailscaleServePort: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const deriveServerPaths = Effect.fn(function* (
|
export const deriveServerPaths = Effect.fn(function* (
|
||||||
@@ -160,8 +158,6 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
|
|||||||
mode: "web",
|
mode: "web",
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
port: 0,
|
port: 0,
|
||||||
host: undefined,
|
host: undefined,
|
||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
|
|||||||
@@ -30,8 +30,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
|||||||
mode: "web",
|
mode: "web",
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
tailscaleServeEnabled: false,
|
|
||||||
tailscaleServePort: 443,
|
|
||||||
port: 0,
|
port: 0,
|
||||||
host: undefined,
|
host: undefined,
|
||||||
desktopBootstrapToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
import { assert, describe, it, vi } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import * as GitManager from "./GitManager.ts";
|
|
||||||
import * as GitWorkflowService from "./GitWorkflowService.ts";
|
|
||||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
|
||||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
|
||||||
|
|
||||||
function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistryShape["detect"] }) {
|
|
||||||
return GitWorkflowService.layer.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
|
||||||
detect: input.detect,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
|
||||||
Layer.provide(Layer.mock(GitManager.GitManager)({})),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("GitWorkflowService", () => {
|
|
||||||
it.effect("returns an empty local status when no VCS repository is detected", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
|
||||||
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
|
||||||
|
|
||||||
assert.deepStrictEqual(status, {
|
|
||||||
isRepo: false,
|
|
||||||
hasPrimaryRemote: false,
|
|
||||||
isDefaultRef: false,
|
|
||||||
refName: null,
|
|
||||||
hasWorkingTreeChanges: false,
|
|
||||||
workingTree: {
|
|
||||||
files: [],
|
|
||||||
insertions: 0,
|
|
||||||
deletions: 0,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeLayer({
|
|
||||||
detect: () => Effect.succeed(null),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns an empty full status when no VCS repository is detected", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
|
||||||
const status = yield* workflow.status({ cwd: "/not-a-repo" });
|
|
||||||
|
|
||||||
assert.deepStrictEqual(status, {
|
|
||||||
isRepo: false,
|
|
||||||
hasPrimaryRemote: false,
|
|
||||||
isDefaultRef: false,
|
|
||||||
refName: null,
|
|
||||||
hasWorkingTreeChanges: false,
|
|
||||||
workingTree: {
|
|
||||||
files: [],
|
|
||||||
insertions: 0,
|
|
||||||
deletions: 0,
|
|
||||||
},
|
|
||||||
hasUpstream: false,
|
|
||||||
aheadCount: 0,
|
|
||||||
behindCount: 0,
|
|
||||||
aheadOfDefaultCount: 0,
|
|
||||||
pr: null,
|
|
||||||
});
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeLayer({
|
|
||||||
detect: () => Effect.succeed(null),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("does not call GitManager status methods when no VCS repository is detected", () => {
|
|
||||||
const localStatus = vi.fn();
|
|
||||||
const remoteStatus = vi.fn();
|
|
||||||
const status = vi.fn();
|
|
||||||
|
|
||||||
const testLayer = GitWorkflowService.layer.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
|
||||||
detect: () => Effect.succeed(null),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
|
||||||
Layer.provide(
|
|
||||||
Layer.mock(GitManager.GitManager)({
|
|
||||||
localStatus,
|
|
||||||
remoteStatus,
|
|
||||||
status,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
|
||||||
yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
|
||||||
yield* workflow.remoteStatus({ cwd: "/not-a-repo" });
|
|
||||||
yield* workflow.status({ cwd: "/not-a-repo" });
|
|
||||||
|
|
||||||
assert.equal(localStatus.mock.calls.length, 0);
|
|
||||||
assert.equal(remoteStatus.mock.calls.length, 0);
|
|
||||||
assert.equal(status.mock.calls.length, 0);
|
|
||||||
}).pipe(Effect.provide(testLayer));
|
|
||||||
});
|
|
||||||
|
|
||||||
it.effect("returns an empty ref list when no VCS repository is detected", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
|
||||||
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
|
|
||||||
|
|
||||||
assert.deepStrictEqual(refs, {
|
|
||||||
refs: [],
|
|
||||||
isRepo: false,
|
|
||||||
hasPrimaryRemote: false,
|
|
||||||
nextCursor: null,
|
|
||||||
totalCount: 0,
|
|
||||||
});
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeLayer({
|
|
||||||
detect: () => Effect.succeed(null),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,314 +0,0 @@
|
|||||||
import { Context, Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import {
|
|
||||||
GitManagerError,
|
|
||||||
GitCommandError,
|
|
||||||
type VcsSwitchRefInput,
|
|
||||||
type VcsSwitchRefResult,
|
|
||||||
type VcsCreateRefInput,
|
|
||||||
type VcsCreateRefResult,
|
|
||||||
type VcsCreateWorktreeInput,
|
|
||||||
type VcsCreateWorktreeResult,
|
|
||||||
type VcsListRefsInput,
|
|
||||||
type VcsListRefsResult,
|
|
||||||
type GitManagerServiceError,
|
|
||||||
type GitPreparePullRequestThreadInput,
|
|
||||||
type GitPreparePullRequestThreadResult,
|
|
||||||
type GitPullRequestRefInput,
|
|
||||||
type VcsPullResult,
|
|
||||||
type VcsRemoveWorktreeInput,
|
|
||||||
type GitResolvePullRequestResult,
|
|
||||||
type GitRunStackedActionInput,
|
|
||||||
type GitRunStackedActionResult,
|
|
||||||
type VcsStatusInput,
|
|
||||||
type VcsStatusLocalResult,
|
|
||||||
type VcsStatusRemoteResult,
|
|
||||||
type VcsStatusResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
|
||||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
|
||||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
|
||||||
|
|
||||||
export interface GitWorkflowServiceShape {
|
|
||||||
readonly status: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
|
||||||
readonly localStatus: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
|
||||||
readonly remoteStatus: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
|
||||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
|
||||||
readonly runStackedAction: (
|
|
||||||
input: GitRunStackedActionInput,
|
|
||||||
options?: GitRunStackedActionOptions,
|
|
||||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
|
||||||
readonly resolvePullRequest: (
|
|
||||||
input: GitPullRequestRefInput,
|
|
||||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
|
||||||
readonly preparePullRequestThread: (
|
|
||||||
input: GitPreparePullRequestThreadInput,
|
|
||||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
|
||||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
|
||||||
readonly createWorktree: (
|
|
||||||
input: VcsCreateWorktreeInput,
|
|
||||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
|
||||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
|
||||||
readonly createRef: (
|
|
||||||
input: VcsCreateRefInput,
|
|
||||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
|
||||||
readonly switchRef: (
|
|
||||||
input: VcsSwitchRefInput,
|
|
||||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
|
||||||
readonly renameBranch: (input: {
|
|
||||||
readonly cwd: string;
|
|
||||||
readonly oldBranch: string;
|
|
||||||
readonly newBranch: string;
|
|
||||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GitWorkflowService extends Context.Service<
|
|
||||||
GitWorkflowService,
|
|
||||||
GitWorkflowServiceShape
|
|
||||||
>()("t3/git/GitWorkflowService") {}
|
|
||||||
|
|
||||||
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
|
|
||||||
new GitManagerError({
|
|
||||||
operation,
|
|
||||||
detail: `${detail} (${cwd})`,
|
|
||||||
});
|
|
||||||
|
|
||||||
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
|
|
||||||
new GitCommandError({
|
|
||||||
operation,
|
|
||||||
command: "vcs-route",
|
|
||||||
cwd,
|
|
||||||
detail,
|
|
||||||
});
|
|
||||||
|
|
||||||
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
|
||||||
return {
|
|
||||||
isRepo: false,
|
|
||||||
hasPrimaryRemote: false,
|
|
||||||
isDefaultRef: false,
|
|
||||||
refName: null,
|
|
||||||
hasWorkingTreeChanges: false,
|
|
||||||
workingTree: {
|
|
||||||
files: [],
|
|
||||||
insertions: 0,
|
|
||||||
deletions: 0,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function nonRepositoryStatus(): VcsStatusResult {
|
|
||||||
return {
|
|
||||||
...nonRepositoryLocalStatus(),
|
|
||||||
hasUpstream: false,
|
|
||||||
aheadCount: 0,
|
|
||||||
behindCount: 0,
|
|
||||||
aheadOfDefaultCount: 0,
|
|
||||||
pr: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function nonRepositoryListRefs(): VcsListRefsResult {
|
|
||||||
return {
|
|
||||||
refs: [],
|
|
||||||
isRepo: false,
|
|
||||||
hasPrimaryRemote: false,
|
|
||||||
nextCursor: null,
|
|
||||||
totalCount: 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
|
||||||
const registry = yield* VcsDriverRegistry;
|
|
||||||
const git = yield* GitVcsDriver;
|
|
||||||
const gitManager = yield* GitManager;
|
|
||||||
|
|
||||||
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
|
|
||||||
operation: string,
|
|
||||||
cwd: string,
|
|
||||||
) {
|
|
||||||
const handle = yield* registry
|
|
||||||
.resolve({ cwd })
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((error) =>
|
|
||||||
unsupportedGitWorkflow(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (handle.kind !== "git") {
|
|
||||||
return yield* unsupportedGitWorkflow(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
|
|
||||||
operation: string,
|
|
||||||
cwd: string,
|
|
||||||
) {
|
|
||||||
const handle = yield* registry
|
|
||||||
.resolve({ cwd })
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((error) =>
|
|
||||||
unsupportedGitCommand(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (handle.kind !== "git") {
|
|
||||||
return yield* unsupportedGitCommand(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
|
|
||||||
function* (operation: string, cwd: string) {
|
|
||||||
const handle = yield* registry
|
|
||||||
.detect({ cwd })
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((error) =>
|
|
||||||
unsupportedGitWorkflow(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (!handle) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (handle.kind !== "git") {
|
|
||||||
return yield* unsupportedGitWorkflow(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const detectGitRepositoryForCommand = Effect.fn(
|
|
||||||
"GitWorkflowService.detectGitRepositoryForCommand",
|
|
||||||
)(function* (operation: string, cwd: string) {
|
|
||||||
const handle = yield* registry
|
|
||||||
.detect({ cwd })
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((error) =>
|
|
||||||
unsupportedGitCommand(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (!handle) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (handle.kind !== "git") {
|
|
||||||
return yield* unsupportedGitCommand(
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
const routeGitManager =
|
|
||||||
<Input extends { readonly cwd: string }, Output>(
|
|
||||||
operation: string,
|
|
||||||
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
|
|
||||||
) =>
|
|
||||||
(input: Input) =>
|
|
||||||
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
|
|
||||||
|
|
||||||
return GitWorkflowService.of({
|
|
||||||
status: (input) =>
|
|
||||||
detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
|
|
||||||
Effect.flatMap((isGitRepository) =>
|
|
||||||
isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
localStatus: (input) =>
|
|
||||||
detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
|
|
||||||
Effect.flatMap((isGitRepository) =>
|
|
||||||
isGitRepository
|
|
||||||
? gitManager.localStatus(input)
|
|
||||||
: Effect.succeed(nonRepositoryLocalStatus()),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
remoteStatus: (input) =>
|
|
||||||
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
|
|
||||||
Effect.flatMap((isGitRepository) =>
|
|
||||||
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
|
||||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
|
||||||
invalidateStatus: gitManager.invalidateStatus,
|
|
||||||
pullCurrentBranch: (cwd) =>
|
|
||||||
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
|
|
||||||
Effect.andThen(git.pullCurrentBranch(cwd)),
|
|
||||||
),
|
|
||||||
runStackedAction: (input, options) =>
|
|
||||||
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
|
|
||||||
Effect.andThen(gitManager.runStackedAction(input, options)),
|
|
||||||
),
|
|
||||||
resolvePullRequest: routeGitManager(
|
|
||||||
"GitWorkflowService.resolvePullRequest",
|
|
||||||
gitManager.resolvePullRequest,
|
|
||||||
),
|
|
||||||
preparePullRequestThread: routeGitManager(
|
|
||||||
"GitWorkflowService.preparePullRequestThread",
|
|
||||||
gitManager.preparePullRequestThread,
|
|
||||||
),
|
|
||||||
listRefs: (input) =>
|
|
||||||
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
|
||||||
Effect.flatMap((isGitRepository) =>
|
|
||||||
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
createWorktree: (input) =>
|
|
||||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
|
||||||
Effect.andThen(git.createWorktree(input)),
|
|
||||||
),
|
|
||||||
removeWorktree: (input) =>
|
|
||||||
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
|
|
||||||
Effect.andThen(git.removeWorktree(input)),
|
|
||||||
),
|
|
||||||
createRef: (input) =>
|
|
||||||
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
|
|
||||||
Effect.andThen(git.createRef(input)),
|
|
||||||
),
|
|
||||||
switchRef: (input) =>
|
|
||||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
|
||||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
|
||||||
),
|
|
||||||
renameBranch: (input) =>
|
|
||||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
|
||||||
Effect.andThen(git.renameBranch(input)),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
export const layer = Layer.effect(GitWorkflowService, make());
|
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
|
import { createModelSelection } from "@t3tools/shared/model";
|
||||||
|
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: {
|
||||||
|
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
|
||||||
|
{ id: "thinking", value: false },
|
||||||
|
{ id: "effort", value: "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: {
|
||||||
|
...createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||||
|
{ id: "effort", value: "max" },
|
||||||
|
{ id: "fastMode", value: 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");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
+46
-15
@@ -7,27 +7,27 @@
|
|||||||
*
|
*
|
||||||
* @module ClaudeTextGeneration
|
* @module ClaudeTextGeneration
|
||||||
*/
|
*/
|
||||||
import { Effect, Option, Schema, Stream } from "effect";
|
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
|
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import {
|
import {
|
||||||
buildBranchNamePrompt,
|
buildBranchNamePrompt,
|
||||||
buildCommitMessagePrompt,
|
buildCommitMessagePrompt,
|
||||||
buildPrContentPrompt,
|
buildPrContentPrompt,
|
||||||
buildThreadTitlePrompt,
|
buildThreadTitlePrompt,
|
||||||
} from "./TextGenerationPrompts.ts";
|
} from "../Prompts.ts";
|
||||||
import {
|
import {
|
||||||
normalizeCliError,
|
normalizeCliError,
|
||||||
sanitizeCommitSubject,
|
sanitizeCommitSubject,
|
||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
sanitizeThreadTitle,
|
sanitizeThreadTitle,
|
||||||
toJsonSchemaObject,
|
toJsonSchemaObject,
|
||||||
} from "./TextGenerationUtils.ts";
|
} from "../Utils.ts";
|
||||||
import {
|
import {
|
||||||
getModelSelectionStringOptionValue,
|
getModelSelectionStringOptionValue,
|
||||||
getProviderOptionDescriptors,
|
getProviderOptionDescriptors,
|
||||||
@@ -37,8 +37,8 @@ import {
|
|||||||
normalizeClaudeCliEffort,
|
normalizeClaudeCliEffort,
|
||||||
resolveClaudeApiModelId,
|
resolveClaudeApiModelId,
|
||||||
resolveClaudeEffort,
|
resolveClaudeEffort,
|
||||||
} from "../provider/Layers/ClaudeProvider.ts";
|
} from "../../provider/Layers/ClaudeProvider.ts";
|
||||||
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
@@ -50,12 +50,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
|
|||||||
structured_output: Schema.Unknown,
|
structured_output: Schema.Unknown,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
|
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||||
claudeSettings: ClaudeSettings,
|
|
||||||
environment: NodeJS.ProcessEnv = process.env,
|
|
||||||
) {
|
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
|
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
const readStreamAsString = <E>(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -91,7 +88,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: S;
|
outputSchemaJson: S;
|
||||||
modelSelection: ModelSelection;
|
modelSelection: ClaudeModelSelection;
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||||
const caps = getClaudeModelCapabilities(modelSelection.model);
|
const caps = getClaudeModelCapabilities(modelSelection.model);
|
||||||
@@ -114,9 +111,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
...(fastMode ? { fastMode: true } : {}),
|
...(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 runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
||||||
const command = ChildProcess.make(
|
const command = ChildProcess.make(
|
||||||
claudeSettings.binaryPath || "claude",
|
claudeSettings?.binaryPath || "claude",
|
||||||
[
|
[
|
||||||
"-p",
|
"-p",
|
||||||
"--output-format",
|
"--output-format",
|
||||||
@@ -130,7 +132,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
"--dangerously-skip-permissions",
|
"--dangerously-skip-permissions",
|
||||||
],
|
],
|
||||||
{
|
{
|
||||||
env: claudeEnvironment,
|
|
||||||
cwd,
|
cwd,
|
||||||
shell: process.platform === "win32",
|
shell: process.platform === "win32",
|
||||||
stdin: {
|
stdin: {
|
||||||
@@ -231,6 +232,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
includeBranch: input.includeBranch === true,
|
includeBranch: input.includeBranch === true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
const generated = yield* runClaudeJson({
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -259,6 +267,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
diffPatch: input.diffPatch,
|
diffPatch: input.diffPatch,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
const generated = yield* runClaudeJson({
|
||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -281,6 +296,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
const generated = yield* runClaudeJson({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -302,6 +324,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
const generated = yield* runClaudeJson({
|
||||||
operation: "generateThreadTitle",
|
operation: "generateThreadTitle",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -322,3 +351,5 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
|||||||
generateThreadTitle,
|
generateThreadTitle,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
||||||
+283
-241
@@ -1,24 +1,30 @@
|
|||||||
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, Schema } from "effect";
|
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||||
import { createModelSelection } from "@t3tools/shared/model";
|
import { createModelSelection } from "@t3tools/shared/model";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
import { ServerConfig } from "../config.ts";
|
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
provider: "codex" as const,
|
||||||
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
|
model: "gpt-5.4-mini",
|
||||||
|
};
|
||||||
|
|
||||||
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
|
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||||
ProviderInstanceId.make("codex"),
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
"gpt-5.4-mini",
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-codex-text-generation-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3code-codex-text-generation-test-",
|
|
||||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
|
||||||
|
|
||||||
function makeFakeCodexBinary(
|
function makeFakeCodexBinary(
|
||||||
dir: string,
|
dir: string,
|
||||||
input: {
|
input: {
|
||||||
@@ -156,19 +162,39 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
stdinMustContain?: string;
|
stdinMustContain?: string;
|
||||||
stdinMustNotContain?: string;
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
|
effect: Effect.Effect<A, E, R>,
|
||||||
) {
|
) {
|
||||||
return Effect.gen(function* () {
|
return Effect.acquireUseRelease(
|
||||||
const fs = yield* FileSystem.FileSystem;
|
Effect.gen(function* () {
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||||
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
|
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||||
const textGeneration = yield* makeCodexTextGeneration(config);
|
const serverSettings = yield* ServerSettingsService;
|
||||||
return yield* effectFn(textGeneration);
|
const previousSettings = yield* serverSettings.getSettings;
|
||||||
}).pipe(Effect.scoped);
|
yield* serverSettings.updateSettings({
|
||||||
|
providers: {
|
||||||
|
codex: {
|
||||||
|
binaryPath: codexPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||||
|
}),
|
||||||
|
() => effect,
|
||||||
|
({ serverSettings, previousBinaryPath }) =>
|
||||||
|
serverSettings
|
||||||
|
.updateSettings({
|
||||||
|
providers: {
|
||||||
|
codex: {
|
||||||
|
binaryPath: previousBinaryPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.pipe(Effect.asVoid),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (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(
|
||||||
{
|
{
|
||||||
@@ -179,21 +205,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = 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,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
expect(generated.subject.endsWith(".")).toBe(false);
|
cwd: process.cwd(),
|
||||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
branch: "feature/codex-effect",
|
||||||
expect(generated.branch).toBeUndefined();
|
stagedSummary: "M 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.endsWith(".")).toBe(false);
|
||||||
|
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||||
|
expect(generated.branch).toBeUndefined();
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -210,17 +237,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
requireReasoningEffort: "xhigh",
|
requireReasoningEffort: "xhigh",
|
||||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
textGeneration.generateCommitMessage({
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
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: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
modelSelection: createModelSelection("codex", "gpt-5.4", [
|
||||||
{ id: "reasoningEffort", value: "xhigh" },
|
{ id: "reasoningEffort", value: "xhigh" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
}),
|
});
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -233,14 +263,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
requireReasoningEffort: "low",
|
requireReasoningEffort: "low",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
textGeneration.generateCommitMessage({
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
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,
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
}),
|
});
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -254,20 +287,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
includeBranch: true,
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
cwd: process.cwd(),
|
||||||
}),
|
branch: "feature/codex-effect",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
includeBranch: true,
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Add important change");
|
||||||
|
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -279,22 +313,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
|
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generatePrContent({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/codex-effect",
|
|
||||||
commitSummary: "feat: improve orchestration flow",
|
|
||||||
diffSummary: "2 files changed",
|
|
||||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
const generated = yield* textGeneration.generatePrContent({
|
||||||
expect(generated.body.startsWith("## Summary")).toBe(true);
|
cwd: process.cwd(),
|
||||||
expect(generated.body.endsWith("\n\n")).toBe(false);
|
baseBranch: "main",
|
||||||
}),
|
headBranch: "feature/codex-effect",
|
||||||
|
commitSummary: "feat: improve orchestration flow",
|
||||||
|
diffSummary: "2 files changed",
|
||||||
|
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("Improve orchestration flow");
|
||||||
|
expect(generated.body.startsWith("## Summary")).toBe(true);
|
||||||
|
expect(generated.body.endsWith("\n\n")).toBe(false);
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -306,16 +341,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
stdinMustNotContain: "Image attachments supplied to the model",
|
stdinMustNotContain: "Image attachments supplied to the model",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Please update session handling.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.branch).toBe("feat/session");
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
}),
|
cwd: process.cwd(),
|
||||||
|
message: "Please update session handling.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("feat/session");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -327,16 +363,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
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...");
|
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...");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -347,16 +384,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
title: ' """ """ ',
|
title: ' """ """ ',
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
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");
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
}),
|
cwd: process.cwd(),
|
||||||
|
message: "Name this thread.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("New thread");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -367,16 +405,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
title: ` "' hello world '" `,
|
title: ` "' hello world '" `,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
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");
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
}),
|
cwd: process.cwd(),
|
||||||
|
message: "Name this thread.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("hello world");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -388,16 +427,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
stdinMustNotContain: "Attachment metadata:",
|
stdinMustNotContain: "Attachment metadata:",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Fix timeout behavior.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/session-timeout");
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
}),
|
cwd: process.cwd(),
|
||||||
|
message: "Fix timeout behavior.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -410,17 +450,56 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
requireImage: true,
|
requireImage: true,
|
||||||
stdinMustContain: "Attachment metadata:",
|
stdinMustContain: "Attachment metadata:",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
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 { 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(attachmentsDir, `${attachmentId}.png`);
|
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: attachmentId,
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const { attachmentsDir } = yield* ServerConfig;
|
||||||
|
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
|
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||||
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
@@ -433,59 +512,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
})
|
||||||
|
.pipe(
|
||||||
expect(generated.branch).toBe("fix/ui-regression");
|
Effect.tap(() =>
|
||||||
}),
|
fs.stat(imagePath).pipe(
|
||||||
),
|
Effect.map((fileInfo) => {
|
||||||
);
|
expect(fileInfo.type).toBe("File");
|
||||||
|
}),
|
||||||
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
branch: "fix/ui-regression",
|
|
||||||
}),
|
|
||||||
requireImage: true,
|
|
||||||
},
|
|
||||||
(textGeneration) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
||||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
|
||||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
|
||||||
|
|
||||||
const generated = yield* textGeneration
|
|
||||||
.generateBranchName({
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Fix layout bug from screenshot.",
|
|
||||||
attachments: [
|
|
||||||
{
|
|
||||||
type: "image",
|
|
||||||
id: attachmentId,
|
|
||||||
name: "bug.png",
|
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 5,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.tap(() =>
|
|
||||||
fs.stat(imagePath).pipe(
|
|
||||||
Effect.map((fileInfo) => {
|
|
||||||
expect(fileInfo.type).toBe("File");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
|
),
|
||||||
);
|
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
|
||||||
|
);
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/ui-regression");
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -497,38 +537,38 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
}),
|
}),
|
||||||
requireImage: true,
|
requireImage: true,
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
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 { 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(attachmentsDir, `${missingAttachmentId}.png`);
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
|
||||||
|
|
||||||
const result = yield* textGeneration
|
const textGeneration = yield* TextGeneration;
|
||||||
.generateBranchName({
|
const result = yield* textGeneration
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
message: "Fix layout bug from screenshot.",
|
cwd: process.cwd(),
|
||||||
attachments: [
|
message: "Fix layout bug from screenshot.",
|
||||||
{
|
attachments: [
|
||||||
type: "image",
|
{
|
||||||
id: missingAttachmentId,
|
type: "image",
|
||||||
name: "outside.png",
|
id: missingAttachmentId,
|
||||||
mimeType: "image/png",
|
name: "outside.png",
|
||||||
sizeBytes: 5,
|
mimeType: "image/png",
|
||||||
},
|
sizeBytes: 5,
|
||||||
],
|
},
|
||||||
})
|
],
|
||||||
.pipe(Effect.result);
|
})
|
||||||
|
.pipe(Effect.result);
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
if (Result.isFailure(result)) {
|
if (Result.isFailure(result)) {
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.failure.message).toContain("missing --image input");
|
expect(result.failure.message).toContain("missing --image input");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -541,22 +581,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
title: "This is not a branch payload",
|
title: "This is not a branch payload",
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const result = yield* textGeneration
|
|
||||||
.generateBranchName({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Fix websocket reconnect flake",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
|
||||||
.pipe(Effect.result);
|
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
const result = yield* textGeneration
|
||||||
if (Result.isFailure(result)) {
|
.generateBranchName({
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
cwd: process.cwd(),
|
||||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
message: "Fix websocket reconnect flake",
|
||||||
}
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
}),
|
})
|
||||||
|
.pipe(Effect.result);
|
||||||
|
|
||||||
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
|
if (Result.isFailure(result)) {
|
||||||
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
||||||
|
}
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -567,26 +608,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
|||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
stderr: "codex execution failed",
|
stderr: "codex execution failed",
|
||||||
},
|
},
|
||||||
(textGeneration) =>
|
Effect.gen(function* () {
|
||||||
Effect.gen(function* () {
|
const textGeneration = yield* TextGeneration;
|
||||||
const result = yield* textGeneration
|
|
||||||
.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-error",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
|
||||||
.pipe(Effect.result);
|
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
const result = yield* textGeneration
|
||||||
if (Result.isFailure(result)) {
|
.generateCommitMessage({
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
cwd: process.cwd(),
|
||||||
expect(result.failure.message).toContain(
|
branch: "feature/codex-error",
|
||||||
"Codex CLI command failed: codex execution failed",
|
stagedSummary: "M README.md",
|
||||||
);
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
}
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
}),
|
})
|
||||||
|
.pipe(Effect.result);
|
||||||
|
|
||||||
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
|
if (Result.isFailure(result)) {
|
||||||
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.failure.message).toContain(
|
||||||
|
"Codex CLI command failed: codex execution failed",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
+70
-37
@@ -1,31 +1,35 @@
|
|||||||
import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
|
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
|
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 { expandHomePath } from "../pathExpansion.ts";
|
import { expandHomePath } from "../../pathExpansion.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
type BranchNameGenerationInput,
|
type BranchNameGenerationInput,
|
||||||
type ThreadTitleGenerationResult,
|
type ThreadTitleGenerationResult,
|
||||||
type TextGenerationShape,
|
type TextGenerationShape,
|
||||||
} from "./TextGeneration.ts";
|
TextGeneration,
|
||||||
|
} from "../Services/TextGeneration.ts";
|
||||||
import {
|
import {
|
||||||
buildBranchNamePrompt,
|
buildBranchNamePrompt,
|
||||||
buildCommitMessagePrompt,
|
buildCommitMessagePrompt,
|
||||||
buildPrContentPrompt,
|
buildPrContentPrompt,
|
||||||
buildThreadTitlePrompt,
|
buildThreadTitlePrompt,
|
||||||
} from "./TextGenerationPrompts.ts";
|
} from "../Prompts.ts";
|
||||||
import {
|
import {
|
||||||
normalizeCliError,
|
normalizeCliError,
|
||||||
sanitizeCommitSubject,
|
sanitizeCommitSubject,
|
||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
sanitizeThreadTitle,
|
sanitizeThreadTitle,
|
||||||
toJsonSchemaObject,
|
toJsonSchemaObject,
|
||||||
} from "./TextGenerationUtils.ts";
|
} from "../Utils.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import {
|
import {
|
||||||
getModelSelectionBooleanOptionValue,
|
getModelSelectionBooleanOptionValue,
|
||||||
getModelSelectionStringOptionValue,
|
getModelSelectionStringOptionValue,
|
||||||
@@ -33,18 +37,12 @@ import {
|
|||||||
|
|
||||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
/**
|
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||||
* Build a Codex text-generation closure bound to a specific `CodexSettings`
|
|
||||||
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
|
|
||||||
*/
|
|
||||||
export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
|
|
||||||
codexConfig: CodexSettings,
|
|
||||||
environment: NodeJS.ProcessEnv = process.env,
|
|
||||||
) {
|
|
||||||
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>;
|
||||||
@@ -70,23 +68,21 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
prefix: string,
|
prefix: string,
|
||||||
content: string,
|
content: string,
|
||||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
||||||
return Effect.gen(function* () {
|
return fileSystem
|
||||||
const tempFileId = yield* Random.nextUUIDv4;
|
.makeTempFileScoped({
|
||||||
return yield* fileSystem
|
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
|
||||||
.makeTempFileScoped({
|
})
|
||||||
prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`,
|
.pipe(
|
||||||
})
|
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
|
||||||
.pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));
|
Effect.mapError(
|
||||||
}).pipe(
|
(cause) =>
|
||||||
Effect.mapError(
|
new TextGenerationError({
|
||||||
(cause) =>
|
operation,
|
||||||
new TextGenerationError({
|
detail: `Failed to write temp file`,
|
||||||
operation,
|
cause,
|
||||||
detail: `Failed to write temp file`,
|
}),
|
||||||
cause,
|
),
|
||||||
}),
|
);
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||||
@@ -147,7 +143,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
outputSchemaJson: S;
|
outputSchemaJson: S;
|
||||||
imagePaths?: ReadonlyArray<string>;
|
imagePaths?: ReadonlyArray<string>;
|
||||||
cleanupPaths?: ReadonlyArray<string>;
|
cleanupPaths?: ReadonlyArray<string>;
|
||||||
modelSelection: ModelSelection;
|
modelSelection: CodexModelSelection;
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||||
const schemaPath = yield* writeTempFile(
|
const schemaPath = yield* writeTempFile(
|
||||||
operation,
|
operation,
|
||||||
@@ -156,12 +152,17 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
);
|
);
|
||||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
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 runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
||||||
const reasoningEffort =
|
const reasoningEffort =
|
||||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||||
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||||
const command = ChildProcess.make(
|
const command = ChildProcess.make(
|
||||||
codexConfig.binaryPath || "codex",
|
codexSettings?.binaryPath || "codex",
|
||||||
[
|
[
|
||||||
"exec",
|
"exec",
|
||||||
"--ephemeral",
|
"--ephemeral",
|
||||||
@@ -184,8 +185,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
],
|
],
|
||||||
{
|
{
|
||||||
env: {
|
env: {
|
||||||
...environment,
|
...process.env,
|
||||||
...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
|
...(codexSettings?.homePath
|
||||||
|
? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
cwd,
|
cwd,
|
||||||
shell: process.platform === "win32",
|
shell: process.platform === "win32",
|
||||||
@@ -285,6 +288,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
includeBranch: input.includeBranch === true,
|
includeBranch: input.includeBranch === true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "codex") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
const generated = yield* runCodexJson({
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -313,6 +323,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
diffPatch: input.diffPatch,
|
diffPatch: input.diffPatch,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "codex") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
const generated = yield* runCodexJson({
|
||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -339,6 +356,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "codex") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
const generated = yield* runCodexJson({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -365,6 +389,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "codex") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
const generated = yield* runCodexJson({
|
||||||
operation: "generateThreadTitle",
|
operation: "generateThreadTitle",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -386,3 +417,5 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
|||||||
generateThreadTitle,
|
generateThreadTitle,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
import * as path from "node:path";
|
||||||
|
import * as os from "node:os";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Effect, Layer } from "effect";
|
||||||
|
import { createModelSelection } from "@t3tools/shared/model";
|
||||||
|
import { expect } from "vitest";
|
||||||
|
|
||||||
|
import { ServerSettingsError } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||||
|
|
||||||
|
function shellSingleQuote(value: string): string {
|
||||||
|
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-cursor-text-generation-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
|
||||||
|
const binDir = path.join(dir, "bin");
|
||||||
|
const agentPath = path.join(binDir, "agent");
|
||||||
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
writeFileSync(
|
||||||
|
agentPath,
|
||||||
|
[
|
||||||
|
"#!/bin/sh",
|
||||||
|
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||||
|
'if [ "$1" != "acp" ]; then',
|
||||||
|
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||||
|
" exit 11",
|
||||||
|
"fi",
|
||||||
|
`exec bun ${JSON.stringify(mockAgentPath)}`,
|
||||||
|
"",
|
||||||
|
].join("\n"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
chmodSync(agentPath, 0o755);
|
||||||
|
return agentPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withFakeAcpAgent<A, E, R>(
|
||||||
|
env: Record<string, string>,
|
||||||
|
effect: Effect.Effect<A, E, R>,
|
||||||
|
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
|
||||||
|
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||||
|
const serverSettings = yield* ServerSettingsService;
|
||||||
|
const previousSettings = yield* serverSettings.getSettings;
|
||||||
|
|
||||||
|
yield* serverSettings.updateSettings({
|
||||||
|
providers: {
|
||||||
|
cursor: {
|
||||||
|
binaryPath: agentPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return yield* effect.pipe(
|
||||||
|
Effect.ensuring(
|
||||||
|
serverSettings
|
||||||
|
.updateSettings({
|
||||||
|
providers: {
|
||||||
|
cursor: {
|
||||||
|
binaryPath: previousSettings.providers.cursor.binaryPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.catch(() => Effect.void),
|
||||||
|
Effect.ensuring(
|
||||||
|
Effect.sync(() => {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.asVoid,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||||
|
return Effect.promise(async () => {
|
||||||
|
const deadline = Date.now() + 5_000;
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
return readFileSync(path, "utf8");
|
||||||
|
} catch (error) {
|
||||||
|
if (Date.now() >= deadline) {
|
||||||
|
throw error instanceof Error ? error : new Error(String(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||||
|
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
|
||||||
|
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
|
||||||
|
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
|
||||||
|
|
||||||
|
return withFakeAcpAgent(
|
||||||
|
{
|
||||||
|
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||||
|
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||||
|
subject: "Add generated commit message",
|
||||||
|
body: "- verify cursor acp model config path",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/cursor-text-generation",
|
||||||
|
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||||
|
stagedPatch:
|
||||||
|
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||||
|
modelSelection: {
|
||||||
|
...createModelSelection("cursor", "gpt-5.4", [
|
||||||
|
{ id: "reasoning", value: "xhigh" },
|
||||||
|
{ id: "fastMode", value: true },
|
||||||
|
{ id: "contextWindow", value: "1m" },
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Add generated commit message");
|
||||||
|
expect(generated.body).toBe("- verify cursor acp model config path");
|
||||||
|
|
||||||
|
const requests = readFileSync(requestLogPath, "utf8")
|
||||||
|
.trim()
|
||||||
|
.split("\n")
|
||||||
|
.filter((line) => line.length > 0)
|
||||||
|
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
|
||||||
|
|
||||||
|
expect(
|
||||||
|
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||||
|
).toMatchObject({
|
||||||
|
_meta: {
|
||||||
|
parameterizedModelPicker: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
requests.some(
|
||||||
|
(request) =>
|
||||||
|
request.method === "session/set_config_option" &&
|
||||||
|
request.params?.configId === "model" &&
|
||||||
|
request.params?.value === "gpt-5.4",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
requests.some(
|
||||||
|
(request) =>
|
||||||
|
request.method === "session/set_config_option" &&
|
||||||
|
request.params?.configId === "reasoning" &&
|
||||||
|
request.params?.value === "extra-high",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
requests.some(
|
||||||
|
(request) =>
|
||||||
|
request.method === "session/set_config_option" &&
|
||||||
|
request.params?.configId === "context" &&
|
||||||
|
request.params?.value === "1m",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
requests.some(
|
||||||
|
(request) =>
|
||||||
|
request.method === "session/set_config_option" &&
|
||||||
|
request.params?.configId === "fast" &&
|
||||||
|
request.params?.value === "true",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
|
||||||
|
).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
type: "text",
|
||||||
|
text: expect.stringContaining("Staged patch:"),
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
rmSync(requestLogDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.effect("accepts json objects with extra assistant text around them", () =>
|
||||||
|
withFakeAcpAgent(
|
||||||
|
{
|
||||||
|
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||||
|
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/cursor-noisy-json",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "cursor",
|
||||||
|
model: "composer-2",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
|
||||||
|
expect(generated.body).toBe("");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("generates thread titles through Cursor ACP text generation", () =>
|
||||||
|
withFakeAcpAgent(
|
||||||
|
{
|
||||||
|
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||||
|
title: '"Trim reconnect spinner status after resume."',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix the reconnect spinner after a resumed session.",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "cursor",
|
||||||
|
model: "composer-2",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("closes the ACP child process after text generation completes", () => {
|
||||||
|
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
|
||||||
|
const exitLogPath = path.join(exitLogDir, "exit.log");
|
||||||
|
|
||||||
|
return withFakeAcpAgent(
|
||||||
|
{
|
||||||
|
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||||
|
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||||
|
subject: "Close runtime after generation",
|
||||||
|
body: "",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/cursor-runtime-close",
|
||||||
|
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||||
|
stagedPatch:
|
||||||
|
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "cursor",
|
||||||
|
model: "composer-2",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Close runtime after generation");
|
||||||
|
|
||||||
|
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||||
|
expect(exitLog).toContain("exit:0");
|
||||||
|
|
||||||
|
rmSync(exitLogDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
+49
-16
@@ -1,27 +1,32 @@
|
|||||||
import { Effect, Option, Ref, Schema } from "effect";
|
import { Effect, Layer, Option, Ref, Schema } from "effect";
|
||||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
|
import { CursorModelSelection } from "@t3tools/contracts";
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
|
import {
|
||||||
|
type ThreadTitleGenerationResult,
|
||||||
|
type TextGenerationShape,
|
||||||
|
TextGeneration,
|
||||||
|
} from "../Services/TextGeneration.ts";
|
||||||
import {
|
import {
|
||||||
buildBranchNamePrompt,
|
buildBranchNamePrompt,
|
||||||
buildCommitMessagePrompt,
|
buildCommitMessagePrompt,
|
||||||
buildPrContentPrompt,
|
buildPrContentPrompt,
|
||||||
buildThreadTitlePrompt,
|
buildThreadTitlePrompt,
|
||||||
} from "./TextGenerationPrompts.ts";
|
} from "../Prompts.ts";
|
||||||
import {
|
import {
|
||||||
extractJsonObject,
|
extractJsonObject,
|
||||||
sanitizeCommitSubject,
|
sanitizeCommitSubject,
|
||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
sanitizeThreadTitle,
|
sanitizeThreadTitle,
|
||||||
} from "./TextGenerationUtils.ts";
|
} from "../Utils.ts";
|
||||||
import {
|
import {
|
||||||
applyCursorAcpModelSelection,
|
applyCursorAcpModelSelection,
|
||||||
makeCursorAcpRuntime,
|
makeCursorAcpRuntime,
|
||||||
} from "../provider/acp/CursorAcpSupport.ts";
|
} from "../../provider/acp/CursorAcpSupport.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const CURSOR_TIMEOUT_MS = 180_000;
|
const CURSOR_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
@@ -50,15 +55,9 @@ function isTextGenerationError(error: unknown): error is TextGenerationError {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
const makeCursorTextGeneration = Effect.gen(function* () {
|
||||||
* Build a Cursor text-generation closure bound to a specific `CursorSettings`
|
|
||||||
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
|
|
||||||
*/
|
|
||||||
export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
|
|
||||||
cursorSettings: CursorSettings,
|
|
||||||
environment: NodeJS.ProcessEnv = process.env,
|
|
||||||
) {
|
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||||
|
|
||||||
const runCursorJson = <S extends Schema.Top>({
|
const runCursorJson = <S extends Schema.Top>({
|
||||||
operation,
|
operation,
|
||||||
@@ -75,13 +74,17 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: S;
|
outputSchemaJson: S;
|
||||||
modelSelection: ModelSelection;
|
modelSelection: CursorModelSelection;
|
||||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
|
const cursorSettings = yield* Effect.map(
|
||||||
|
serverSettingsService.getSettings,
|
||||||
|
(settings) => settings.providers.cursor,
|
||||||
|
).pipe(Effect.catch(() => Effect.undefined));
|
||||||
|
|
||||||
const outputRef = yield* Ref.make("");
|
const outputRef = yield* Ref.make("");
|
||||||
const runtime = yield* makeCursorAcpRuntime({
|
const runtime = yield* makeCursorAcpRuntime({
|
||||||
cursorSettings,
|
cursorSettings,
|
||||||
environment,
|
|
||||||
childProcessSpawner: commandSpawner,
|
childProcessSpawner: commandSpawner,
|
||||||
cwd,
|
cwd,
|
||||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||||
@@ -183,6 +186,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
includeBranch: input.includeBranch === true,
|
includeBranch: input.includeBranch === true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "cursor") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCursorJson({
|
const generated = yield* runCursorJson({
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -211,6 +221,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
diffPatch: input.diffPatch,
|
diffPatch: input.diffPatch,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "cursor") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCursorJson({
|
const generated = yield* runCursorJson({
|
||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -233,6 +250,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "cursor") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCursorJson({
|
const generated = yield* runCursorJson({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -254,6 +278,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "cursor") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const generated = yield* runCursorJson({
|
const generated = yield* runCursorJson({
|
||||||
operation: "generateThreadTitle",
|
operation: "generateThreadTitle",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -274,3 +305,5 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
|||||||
generateThreadTitle,
|
generateThreadTitle,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,271 @@
|
|||||||
|
import { assert, it } from "@effect/vitest";
|
||||||
|
import { Effect } from "effect";
|
||||||
|
import { afterEach, expect, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("../../processRunner", () => ({
|
||||||
|
runProcess: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { runProcess } from "../../processRunner.ts";
|
||||||
|
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||||
|
import { GitHubCliLive } from "./GitHubCli.ts";
|
||||||
|
|
||||||
|
const mockedRunProcess = vi.mocked(runProcess);
|
||||||
|
const layer = it.layer(GitHubCliLive);
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
mockedRunProcess.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
layer("GitHubCliLive", (it) => {
|
||||||
|
it.effect("parses pull request view output", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: JSON.stringify({
|
||||||
|
number: 42,
|
||||||
|
title: "Add PR thread creation",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/pr-threads",
|
||||||
|
state: "OPEN",
|
||||||
|
mergedAt: null,
|
||||||
|
isCrossRepository: true,
|
||||||
|
headRepository: {
|
||||||
|
nameWithOwner: "octocat/codething-mvp",
|
||||||
|
},
|
||||||
|
headRepositoryOwner: {
|
||||||
|
login: "octocat",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
return yield* gh.getPullRequest({
|
||||||
|
cwd: "/repo",
|
||||||
|
reference: "#42",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepStrictEqual(result, {
|
||||||
|
number: 42,
|
||||||
|
title: "Add PR thread creation",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/pr-threads",
|
||||||
|
state: "open",
|
||||||
|
isCrossRepository: true,
|
||||||
|
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||||
|
headRepositoryOwnerLogin: "octocat",
|
||||||
|
});
|
||||||
|
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||||
|
"gh",
|
||||||
|
[
|
||||||
|
"pr",
|
||||||
|
"view",
|
||||||
|
"#42",
|
||||||
|
"--json",
|
||||||
|
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||||
|
],
|
||||||
|
expect.objectContaining({ cwd: "/repo" }),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("trims pull request fields decoded from gh json", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: JSON.stringify({
|
||||||
|
number: 42,
|
||||||
|
title: " Add PR thread creation \n",
|
||||||
|
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||||
|
baseRefName: " main ",
|
||||||
|
headRefName: "\tfeature/pr-threads\t",
|
||||||
|
state: "OPEN",
|
||||||
|
mergedAt: null,
|
||||||
|
isCrossRepository: true,
|
||||||
|
headRepository: {
|
||||||
|
nameWithOwner: " octocat/codething-mvp ",
|
||||||
|
},
|
||||||
|
headRepositoryOwner: {
|
||||||
|
login: " octocat ",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
return yield* gh.getPullRequest({
|
||||||
|
cwd: "/repo",
|
||||||
|
reference: "#42",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepStrictEqual(result, {
|
||||||
|
number: 42,
|
||||||
|
title: "Add PR thread creation",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/pr-threads",
|
||||||
|
state: "open",
|
||||||
|
isCrossRepository: true,
|
||||||
|
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||||
|
headRepositoryOwnerLogin: "octocat",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: JSON.stringify([
|
||||||
|
{
|
||||||
|
number: 0,
|
||||||
|
title: "invalid",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/invalid",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
number: 43,
|
||||||
|
title: " Valid PR ",
|
||||||
|
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||||
|
baseRefName: " main ",
|
||||||
|
headRefName: " feature/pr-list ",
|
||||||
|
headRepository: {
|
||||||
|
nameWithOwner: " ",
|
||||||
|
},
|
||||||
|
headRepositoryOwner: {
|
||||||
|
login: " ",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
return yield* gh.listOpenPullRequests({
|
||||||
|
cwd: "/repo",
|
||||||
|
headSelector: "feature/pr-list",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepStrictEqual(result, [
|
||||||
|
{
|
||||||
|
number: 43,
|
||||||
|
title: "Valid PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/pr-list",
|
||||||
|
state: "open",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("reads repository clone URLs", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: JSON.stringify({
|
||||||
|
nameWithOwner: "octocat/codething-mvp",
|
||||||
|
url: "https://github.com/octocat/codething-mvp",
|
||||||
|
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||||
|
}),
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
return yield* gh.getRepositoryCloneUrls({
|
||||||
|
cwd: "/repo",
|
||||||
|
repository: "octocat/codething-mvp",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepStrictEqual(result, {
|
||||||
|
nameWithOwner: "octocat/codething-mvp",
|
||||||
|
url: "https://github.com/octocat/codething-mvp",
|
||||||
|
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("creates pull requests with the title passed as a single argv value", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: "https://github.com/pingdotgg/codething-mvp/pull/42\n",
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
yield* gh.createPullRequest({
|
||||||
|
cwd: "/repo",
|
||||||
|
baseBranch: "main",
|
||||||
|
headSelector: "dev",
|
||||||
|
title: "Stabilize map selection, pricing badges, and camera handling",
|
||||||
|
bodyFile:
|
||||||
|
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||||
|
"gh",
|
||||||
|
[
|
||||||
|
"pr",
|
||||||
|
"create",
|
||||||
|
"--base",
|
||||||
|
"main",
|
||||||
|
"--head",
|
||||||
|
"dev",
|
||||||
|
"--title",
|
||||||
|
"Stabilize map selection, pricing badges, and camera handling",
|
||||||
|
"--body-file",
|
||||||
|
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
|
||||||
|
],
|
||||||
|
expect.objectContaining({
|
||||||
|
cwd: "/repo",
|
||||||
|
shell: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockRejectedValueOnce(
|
||||||
|
new Error(
|
||||||
|
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const error = yield* Effect.gen(function* () {
|
||||||
|
const gh = yield* GitHubCli;
|
||||||
|
return yield* gh.getPullRequest({
|
||||||
|
cwd: "/repo",
|
||||||
|
reference: "4888",
|
||||||
|
});
|
||||||
|
}).pipe(Effect.flip);
|
||||||
|
|
||||||
|
assert.equal(error.message.includes("Pull request not found"), true);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||||
|
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import { runProcess } from "../../processRunner.ts";
|
||||||
|
import { GitHubCliError } from "@t3tools/contracts";
|
||||||
|
import {
|
||||||
|
GitHubCli,
|
||||||
|
type GitHubRepositoryCloneUrls,
|
||||||
|
type GitHubCliShape,
|
||||||
|
} from "../Services/GitHubCli.ts";
|
||||||
|
import {
|
||||||
|
decodeGitHubPullRequestJson,
|
||||||
|
decodeGitHubPullRequestListJson,
|
||||||
|
formatGitHubJsonDecodeError,
|
||||||
|
} from "../githubPullRequests.ts";
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||||
|
|
||||||
|
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
if (error.message.includes("Command not found: gh")) {
|
||||||
|
return new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lower = error.message.toLowerCase();
|
||||||
|
if (
|
||||||
|
lower.includes("authentication failed") ||
|
||||||
|
lower.includes("not logged in") ||
|
||||||
|
lower.includes("gh auth login") ||
|
||||||
|
lower.includes("no oauth token")
|
||||||
|
) {
|
||||||
|
return new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
lower.includes("could not resolve to a pullrequest") ||
|
||||||
|
lower.includes("repository.pullrequest") ||
|
||||||
|
lower.includes("no pull requests found for branch") ||
|
||||||
|
lower.includes("pull request not found")
|
||||||
|
) {
|
||||||
|
return new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: `GitHub CLI command failed: ${error.message}`,
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: "GitHub CLI command failed.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||||
|
nameWithOwner: TrimmedNonEmptyString,
|
||||||
|
url: TrimmedNonEmptyString,
|
||||||
|
sshUrl: TrimmedNonEmptyString,
|
||||||
|
});
|
||||||
|
|
||||||
|
function normalizeRepositoryCloneUrls(
|
||||||
|
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||||
|
): GitHubRepositoryCloneUrls {
|
||||||
|
return {
|
||||||
|
nameWithOwner: raw.nameWithOwner,
|
||||||
|
url: raw.url,
|
||||||
|
sshUrl: raw.sshUrl,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeGitHubJson<S extends Schema.Top>(
|
||||||
|
raw: string,
|
||||||
|
schema: S,
|
||||||
|
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
|
||||||
|
invalidDetail: string,
|
||||||
|
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
|
||||||
|
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(error) =>
|
||||||
|
new GitHubCliError({
|
||||||
|
operation,
|
||||||
|
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||||
|
cause: error,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeGitHubCli = Effect.sync(() => {
|
||||||
|
const execute: GitHubCliShape["execute"] = (input) =>
|
||||||
|
Effect.tryPromise({
|
||||||
|
try: () =>
|
||||||
|
runProcess("gh", input.args, {
|
||||||
|
cwd: input.cwd,
|
||||||
|
shell: false,
|
||||||
|
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||||
|
}),
|
||||||
|
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = {
|
||||||
|
execute,
|
||||||
|
listOpenPullRequests: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: [
|
||||||
|
"pr",
|
||||||
|
"list",
|
||||||
|
"--head",
|
||||||
|
input.headSelector,
|
||||||
|
"--state",
|
||||||
|
"open",
|
||||||
|
"--limit",
|
||||||
|
String(input.limit ?? 1),
|
||||||
|
"--json",
|
||||||
|
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||||
|
],
|
||||||
|
}).pipe(
|
||||||
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
Effect.flatMap((raw) =>
|
||||||
|
raw.length === 0
|
||||||
|
? Effect.succeed([])
|
||||||
|
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||||
|
Effect.flatMap((decoded) => {
|
||||||
|
if (!Result.isSuccess(decoded)) {
|
||||||
|
return Effect.fail(
|
||||||
|
new GitHubCliError({
|
||||||
|
operation: "listOpenPullRequests",
|
||||||
|
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||||
|
cause: decoded.failure,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Effect.succeed(
|
||||||
|
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
getPullRequest: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: [
|
||||||
|
"pr",
|
||||||
|
"view",
|
||||||
|
input.reference,
|
||||||
|
"--json",
|
||||||
|
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||||
|
],
|
||||||
|
}).pipe(
|
||||||
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
Effect.flatMap((raw) =>
|
||||||
|
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||||
|
Effect.flatMap((decoded) => {
|
||||||
|
if (!Result.isSuccess(decoded)) {
|
||||||
|
return Effect.fail(
|
||||||
|
new GitHubCliError({
|
||||||
|
operation: "getPullRequest",
|
||||||
|
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||||
|
cause: decoded.failure,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Effect.succeed(
|
||||||
|
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
getRepositoryCloneUrls: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
||||||
|
}).pipe(
|
||||||
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
Effect.flatMap((raw) =>
|
||||||
|
decodeGitHubJson(
|
||||||
|
raw,
|
||||||
|
RawGitHubRepositoryCloneUrlsSchema,
|
||||||
|
"getRepositoryCloneUrls",
|
||||||
|
"GitHub CLI returned invalid repository JSON.",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.map(normalizeRepositoryCloneUrls),
|
||||||
|
),
|
||||||
|
createPullRequest: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: [
|
||||||
|
"pr",
|
||||||
|
"create",
|
||||||
|
"--base",
|
||||||
|
input.baseBranch,
|
||||||
|
"--head",
|
||||||
|
input.headSelector,
|
||||||
|
"--title",
|
||||||
|
input.title,
|
||||||
|
"--body-file",
|
||||||
|
input.bodyFile,
|
||||||
|
],
|
||||||
|
}).pipe(Effect.asVoid),
|
||||||
|
getDefaultBranch: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
|
||||||
|
}).pipe(
|
||||||
|
Effect.map((value) => {
|
||||||
|
const trimmed = value.stdout.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : null;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
checkoutPullRequest: (input) =>
|
||||||
|
execute({
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
|
||||||
|
}).pipe(Effect.asVoid),
|
||||||
|
} satisfies GitHubCliShape;
|
||||||
|
|
||||||
|
return service;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
|
||||||
+95
-330
@@ -5,7 +5,6 @@ import { spawnSync } from "node:child_process";
|
|||||||
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, PlatformError, Scope } from "effect";
|
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
import type {
|
import type {
|
||||||
GitActionProgressEvent,
|
GitActionProgressEvent,
|
||||||
@@ -14,27 +13,24 @@ import type {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
|
||||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||||
import { type GitManagerShape } from "./GitManager.ts";
|
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||||
import {
|
import {
|
||||||
GitHubCliError,
|
|
||||||
type GitHubCliShape,
|
type GitHubCliShape,
|
||||||
type GitHubPullRequestSummary,
|
type GitHubPullRequestSummary,
|
||||||
GitHubCli,
|
GitHubCli,
|
||||||
} from "../sourceControl/GitHubCli.ts";
|
} from "../Services/GitHubCli.ts";
|
||||||
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
|
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
import { GitCoreLive } from "./GitCore.ts";
|
||||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
import { GitCore } from "../Services/GitCore.ts";
|
||||||
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
|
|
||||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
|
||||||
import { makeGitManager } from "./GitManager.ts";
|
import { makeGitManager } from "./GitManager.ts";
|
||||||
import { ServerConfig } from "../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { ServerSettingsService } from "../serverSettings.ts";
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import {
|
import {
|
||||||
ProjectSetupScriptRunner,
|
ProjectSetupScriptRunner,
|
||||||
type ProjectSetupScriptRunnerInput,
|
type ProjectSetupScriptRunnerInput,
|
||||||
type ProjectSetupScriptRunnerShape,
|
type ProjectSetupScriptRunnerShape,
|
||||||
} from "../project/Services/ProjectSetupScriptRunner.ts";
|
} from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||||
|
|
||||||
interface FakeGhScenario {
|
interface FakeGhScenario {
|
||||||
prListSequence?: string[];
|
prListSequence?: string[];
|
||||||
@@ -57,16 +53,6 @@ interface FakeGhScenario {
|
|||||||
failWith?: GitHubCliError;
|
failWith?: GitHubCliError;
|
||||||
}
|
}
|
||||||
|
|
||||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
|
||||||
return {
|
|
||||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
|
||||||
stdout,
|
|
||||||
stderr: "",
|
|
||||||
stdoutTruncated: false,
|
|
||||||
stderrTruncated: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FakeGitTextGeneration {
|
interface FakeGitTextGeneration {
|
||||||
generateCommitMessage: (input: {
|
generateCommitMessage: (input: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
@@ -223,27 +209,18 @@ function runGit(
|
|||||||
args: readonly string[],
|
args: readonly string[],
|
||||||
allowNonZeroExit = false,
|
allowNonZeroExit = false,
|
||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
{
|
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||||
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
|
|
||||||
readonly stdout: string;
|
|
||||||
readonly stderr: string;
|
|
||||||
},
|
|
||||||
GitCommandError,
|
GitCommandError,
|
||||||
GitVcsDriver.GitVcsDriver
|
GitCore
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
const gitCore = yield* GitCore;
|
||||||
const result = yield* git.execute({
|
return yield* gitCore.execute({
|
||||||
operation: "GitManager.test.runGit",
|
operation: "GitManager.test.runGit",
|
||||||
cwd,
|
cwd,
|
||||||
args,
|
args,
|
||||||
allowNonZeroExit,
|
allowNonZeroExit,
|
||||||
});
|
});
|
||||||
return {
|
|
||||||
exitCode: result.exitCode,
|
|
||||||
stdout: result.stdout,
|
|
||||||
stderr: result.stderr,
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,7 +229,7 @@ function initRepo(
|
|||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
void,
|
void,
|
||||||
PlatformError.PlatformError | GitCommandError,
|
PlatformError.PlatformError | GitCommandError,
|
||||||
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
|
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
@@ -268,7 +245,7 @@ function initRepo(
|
|||||||
function createBareRemote(): Effect.Effect<
|
function createBareRemote(): Effect.Effect<
|
||||||
string,
|
string,
|
||||||
PlatformError.PlatformError | GitCommandError,
|
PlatformError.PlatformError | GitCommandError,
|
||||||
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
|
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||||
@@ -282,7 +259,7 @@ function configureRemote(
|
|||||||
remoteName: string,
|
remoteName: string,
|
||||||
remotePath: string,
|
remotePath: string,
|
||||||
fetchNamespace: string,
|
fetchNamespace: string,
|
||||||
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
|
): Effect.Effect<void, GitCommandError, GitCore> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
|
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
|
||||||
yield* runGit(cwd, [
|
yield* runGit(cwd, [
|
||||||
@@ -402,15 +379,24 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
? scenario.prListByHeadSelector?.[headSelector]
|
? scenario.prListByHeadSelector?.[headSelector]
|
||||||
: undefined;
|
: undefined;
|
||||||
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
|
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
|
||||||
return Effect.succeed(fakeGhOutput(stdout));
|
return Effect.succeed({
|
||||||
|
stdout,
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args[0] === "pr" && args[1] === "create") {
|
if (args[0] === "pr" && args[1] === "create") {
|
||||||
return Effect.succeed(
|
return Effect.succeed({
|
||||||
fakeGhOutput(
|
stdout:
|
||||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||||
),
|
stderr: "",
|
||||||
);
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args[0] === "pr" && args[1] === "view") {
|
if (args[0] === "pr" && args[1] === "view") {
|
||||||
@@ -422,8 +408,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
headRefName: "feature/pull-request",
|
headRefName: "feature/pull-request",
|
||||||
state: "open",
|
state: "open",
|
||||||
};
|
};
|
||||||
return Effect.succeed(
|
return Effect.succeed({
|
||||||
fakeGhOutput(
|
stdout:
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
...pullRequest,
|
...pullRequest,
|
||||||
...(pullRequest.headRepositoryNameWithOwner
|
...(pullRequest.headRepositoryNameWithOwner
|
||||||
@@ -441,8 +427,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
}) + "\n",
|
}) + "\n",
|
||||||
),
|
stderr: "",
|
||||||
);
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args[0] === "pr" && args[1] === "checkout") {
|
if (args[0] === "pr" && args[1] === "checkout") {
|
||||||
@@ -464,7 +453,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
|
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return fakeGhOutput("");
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
catch: (error) =>
|
catch: (error) =>
|
||||||
isGitHubCliError(error)
|
isGitHubCliError(error)
|
||||||
@@ -491,17 +486,26 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Effect.succeed(
|
return Effect.succeed({
|
||||||
fakeGhOutput(
|
stdout:
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
nameWithOwner: repository,
|
nameWithOwner: repository,
|
||||||
url: cloneUrls.url,
|
url: cloneUrls.url,
|
||||||
sshUrl: cloneUrls.sshUrl,
|
sshUrl: cloneUrls.sshUrl,
|
||||||
}) + "\n",
|
}) + "\n",
|
||||||
),
|
stderr: "",
|
||||||
);
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return Effect.succeed(fakeGhOutput(`${scenario.defaultBranch ?? "main"}\n`));
|
return Effect.succeed({
|
||||||
|
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return Effect.fail(
|
return Effect.fail(
|
||||||
@@ -580,13 +584,6 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
||||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||||
createRepository: (input) =>
|
|
||||||
Effect.fail(
|
|
||||||
new GitHubCliError({
|
|
||||||
operation: "createRepository",
|
|
||||||
detail: `Unexpected repository create: ${input.repository}`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
checkoutPullRequest: (input) =>
|
checkoutPullRequest: (input) =>
|
||||||
execute({
|
execute({
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
@@ -642,27 +639,13 @@ function makeManager(input?: {
|
|||||||
|
|
||||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||||
|
|
||||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
const gitCoreLayer = GitCoreLive.pipe(
|
||||||
Layer.provideMerge(VcsProcess.layer),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
Layer.provideMerge(ServerConfigLayer),
|
||||||
);
|
);
|
||||||
const sourceControlRegistryLayer = Layer.effect(
|
|
||||||
SourceControlProviderRegistry.SourceControlProviderRegistry,
|
|
||||||
GitHubSourceControlProvider.make().pipe(
|
|
||||||
Effect.map((provider) =>
|
|
||||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
|
||||||
get: () => Effect.succeed(provider),
|
|
||||||
resolveHandle: () => Effect.succeed({ provider, context: null }),
|
|
||||||
resolve: () => Effect.succeed(provider),
|
|
||||||
discover: Effect.succeed([]),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const managerLayer = Layer.mergeAll(
|
const managerLayer = Layer.mergeAll(
|
||||||
|
Layer.succeed(GitHubCli, gitHubCli),
|
||||||
Layer.succeed(TextGeneration, textGeneration),
|
Layer.succeed(TextGeneration, textGeneration),
|
||||||
Layer.succeed(
|
Layer.succeed(
|
||||||
ProjectSetupScriptRunner,
|
ProjectSetupScriptRunner,
|
||||||
@@ -670,9 +653,9 @@ function makeManager(input?: {
|
|||||||
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
vcsDriverLayer,
|
gitCoreLayer,
|
||||||
serverSettingsLayer,
|
serverSettingsLayer,
|
||||||
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
|
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||||
|
|
||||||
return makeGitManager().pipe(
|
return makeGitManager().pipe(
|
||||||
Effect.provide(managerLayer),
|
Effect.provide(managerLayer),
|
||||||
@@ -682,9 +665,8 @@ function makeManager(input?: {
|
|||||||
|
|
||||||
const asThreadId = (threadId: string) => threadId as ThreadId;
|
const asThreadId = (threadId: string) => threadId as ThreadId;
|
||||||
|
|
||||||
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
|
const GitManagerTestLayer = GitCoreLive.pipe(
|
||||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
||||||
Layer.provideMerge(VcsProcess.layer),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -716,15 +698,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.isRepo).toBe(true);
|
expect(status.isRepo).toBe(true);
|
||||||
expect(status.hasPrimaryRemote).toBe(true);
|
expect(status.hasOriginRemote).toBe(true);
|
||||||
expect(status.isDefaultRef).toBe(false);
|
expect(status.isDefaultBranch).toBe(false);
|
||||||
expect(status.refName).toBe("feature/status-open-pr");
|
expect(status.branch).toBe("feature/status-open-pr");
|
||||||
expect(status.pr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-open-pr",
|
headBranch: "feature/status-open-pr",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -761,8 +743,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
number: 14,
|
number: 14,
|
||||||
title: "Existing PR title",
|
title: "Existing PR title",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-trimmed-pr",
|
headBranch: "feature/status-trimmed-pr",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -812,8 +794,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
number: 15,
|
number: 15,
|
||||||
title: "Valid PR title",
|
title: "Valid PR title",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-valid-pr-entry",
|
headBranch: "feature/status-valid-pr-entry",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -861,8 +843,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
number: 17,
|
number: 17,
|
||||||
title: "Merged PR",
|
title: "Merged PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-lowercase-state",
|
headBranch: "feature/status-lowercase-state",
|
||||||
state: "merged",
|
state: "merged",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -877,9 +859,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
expect(status).toEqual({
|
expect(status).toEqual({
|
||||||
isRepo: false,
|
isRepo: false,
|
||||||
hasPrimaryRemote: false,
|
hasOriginRemote: false,
|
||||||
isDefaultRef: false,
|
isDefaultBranch: false,
|
||||||
refName: null,
|
branch: null,
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: {
|
workingTree: {
|
||||||
files: [],
|
files: [],
|
||||||
@@ -889,7 +871,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
aheadOfDefaultCount: 0,
|
|
||||||
pr: null,
|
pr: null,
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -907,9 +888,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
expect(status).toEqual({
|
expect(status).toEqual({
|
||||||
isRepo: false,
|
isRepo: false,
|
||||||
hasPrimaryRemote: false,
|
hasOriginRemote: false,
|
||||||
isDefaultRef: false,
|
isDefaultBranch: false,
|
||||||
refName: null,
|
branch: null,
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: {
|
workingTree: {
|
||||||
files: [],
|
files: [],
|
||||||
@@ -919,7 +900,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
aheadOfDefaultCount: 0,
|
|
||||||
pr: null,
|
pr: null,
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -992,7 +972,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("main");
|
expect(status.branch).toBe("main");
|
||||||
expect(status.pr).toBeNull();
|
expect(status.pr).toBeNull();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -1046,13 +1026,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("t3code/pr-488/statemachine");
|
expect(status.branch).toBe("t3code/pr-488/statemachine");
|
||||||
expect(status.pr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 488,
|
number: 488,
|
||||||
title: "Rebase this PR on latest main",
|
title: "Rebase this PR on latest main",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "statemachine",
|
headBranch: "statemachine",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
expect(ghCalls).toContain(
|
expect(ghCalls).toContain(
|
||||||
@@ -1146,13 +1126,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("upstream/effect-atom");
|
expect(status.branch).toBe("upstream/effect-atom");
|
||||||
expect(status.pr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 1618,
|
number: 1618,
|
||||||
title: "Correct PR",
|
title: "Correct PR",
|
||||||
url: "https://github.com/pingdotgg/t3code/pull/1618",
|
url: "https://github.com/pingdotgg/t3code/pull/1618",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "effect-atom",
|
headBranch: "effect-atom",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
|
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
|
||||||
@@ -1196,48 +1176,18 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("feature/status-merged-pr");
|
expect(status.branch).toBe("feature/status-merged-pr");
|
||||||
expect(status.pr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 22,
|
number: 22,
|
||||||
title: "Merged PR",
|
title: "Merged PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-merged-pr",
|
headBranch: "feature/status-merged-pr",
|
||||||
state: "merged",
|
state: "merged",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("status hides merged PRs on the default branch", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager({
|
|
||||||
ghScenario: {
|
|
||||||
prListSequence: [
|
|
||||||
JSON.stringify([
|
|
||||||
{
|
|
||||||
number: 23,
|
|
||||||
title: "Merged PR",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/23",
|
|
||||||
baseRefName: "feature/status-default-branch-target",
|
|
||||||
headRefName: "main",
|
|
||||||
state: "MERGED",
|
|
||||||
mergedAt: "2026-01-30T10:00:00Z",
|
|
||||||
updatedAt: "2026-01-30T10:00:00Z",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
|
||||||
expect(status.refName).toBe("main");
|
|
||||||
expect(status.pr).toBeNull();
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -1273,13 +1223,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("feature/status-open-over-merged");
|
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||||
expect(status.pr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 46,
|
number: 46,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||||
baseRef: "main",
|
baseBranch: "main",
|
||||||
headRef: "feature/status-open-over-merged",
|
headBranch: "feature/status-open-over-merged",
|
||||||
state: "open",
|
state: "open",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -1304,7 +1254,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.refName).toBe("feature/status-no-gh");
|
expect(status.branch).toBe("feature/status-no-gh");
|
||||||
expect(status.pr).toBeNull();
|
expect(status.pr).toBeNull();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -1682,41 +1632,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("pushes existing commits without committing dirty worktree changes", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
|
|
||||||
const remoteDir = yield* createBareRemote();
|
|
||||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
|
|
||||||
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
|
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
|
|
||||||
fs.mkdirSync(path.join(repoDir, ".vercel"));
|
|
||||||
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager();
|
|
||||||
const result = yield* runStackedAction(manager, {
|
|
||||||
cwd: repoDir,
|
|
||||||
action: "push",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.commit.status).toBe("skipped_not_requested");
|
|
||||||
expect(result.push.status).toBe("pushed");
|
|
||||||
expect(result.pr.status).toBe("skipped_not_requested");
|
|
||||||
expect(
|
|
||||||
yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
|
|
||||||
Effect.map((output) => output.stdout.trim()),
|
|
||||||
),
|
|
||||||
).toContain("?? .vercel/");
|
|
||||||
expect(
|
|
||||||
yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
|
|
||||||
Effect.map((output) => output.stdout.trim()),
|
|
||||||
),
|
|
||||||
).toBe("Push dirty branch");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -1763,49 +1678,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("create_pr falls back to main when source control provider detection fails", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
|
|
||||||
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
|
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
|
|
||||||
const remoteDir = yield* createBareRemote();
|
|
||||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
|
||||||
|
|
||||||
const { manager, ghCalls } = yield* makeManager({
|
|
||||||
ghScenario: {
|
|
||||||
prListSequence: [
|
|
||||||
"[]",
|
|
||||||
JSON.stringify([
|
|
||||||
{
|
|
||||||
number: 404,
|
|
||||||
title: "Provider fallback",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/404",
|
|
||||||
baseRefName: "main",
|
|
||||||
headRefName: "feature/provider-fallback",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* runStackedAction(manager, {
|
|
||||||
cwd: repoDir,
|
|
||||||
action: "create_pr",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.pr.status).toBe("created");
|
|
||||||
expect(result.pr.number).toBe(404);
|
|
||||||
expect(
|
|
||||||
ghCalls.some((call) =>
|
|
||||||
call.includes("pr create --base main --head feature/provider-fallback"),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -2463,113 +2335,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect(
|
|
||||||
"restores same-repository upstream tracking after local PR checkout without a remote ref",
|
|
||||||
() =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
const remoteDir = yield* createBareRemote();
|
|
||||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
|
||||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
|
|
||||||
yield* runGit(repoDir, ["add", "upstream.txt"]);
|
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
|
|
||||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
|
|
||||||
yield* runGit(repoDir, ["checkout", "main"]);
|
|
||||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]);
|
|
||||||
yield* runGit(repoDir, [
|
|
||||||
"update-ref",
|
|
||||||
"-d",
|
|
||||||
"refs/remotes/origin/feature/pr-local-upstream",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager({
|
|
||||||
ghScenario: {
|
|
||||||
pullRequest: {
|
|
||||||
number: 65,
|
|
||||||
title: "Local upstream PR",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/65",
|
|
||||||
baseRefName: "main",
|
|
||||||
headRefName: "feature/pr-local-upstream",
|
|
||||||
state: "open",
|
|
||||||
isCrossRepository: false,
|
|
||||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
|
||||||
headRepositoryOwnerLogin: "pingdotgg",
|
|
||||||
},
|
|
||||||
repositoryCloneUrls: {
|
|
||||||
"pingdotgg/codething-mvp": {
|
|
||||||
url: remoteDir,
|
|
||||||
sshUrl: remoteDir,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* preparePullRequestThread(manager, {
|
|
||||||
cwd: repoDir,
|
|
||||||
reference: "65",
|
|
||||||
mode: "local",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.worktreePath).toBeNull();
|
|
||||||
expect(result.branch).toBe("feature/pr-local-upstream");
|
|
||||||
expect(
|
|
||||||
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
|
|
||||||
).toBe("origin/feature/pr-local-upstream");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect(
|
|
||||||
"restores same-repository upstream tracking when provider omits head repository metadata",
|
|
||||||
() =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
|
||||||
yield* initRepo(repoDir);
|
|
||||||
const remoteDir = yield* createBareRemote();
|
|
||||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
|
||||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
|
||||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]);
|
|
||||||
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
|
|
||||||
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
|
|
||||||
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
|
|
||||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
|
|
||||||
yield* runGit(repoDir, ["checkout", "main"]);
|
|
||||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]);
|
|
||||||
yield* runGit(repoDir, [
|
|
||||||
"update-ref",
|
|
||||||
"-d",
|
|
||||||
"refs/remotes/origin/feature/pr-local-no-head-repo",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const { manager } = yield* makeManager({
|
|
||||||
ghScenario: {
|
|
||||||
pullRequest: {
|
|
||||||
number: 66,
|
|
||||||
title: "Local upstream PR without repo metadata",
|
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/66",
|
|
||||||
baseRefName: "main",
|
|
||||||
headRefName: "feature/pr-local-no-head-repo",
|
|
||||||
state: "open",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* preparePullRequestThread(manager, {
|
|
||||||
cwd: repoDir,
|
|
||||||
reference: "66",
|
|
||||||
mode: "local",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.worktreePath).toBeNull();
|
|
||||||
expect(result.branch).toBe("feature/pr-local-no-head-repo");
|
|
||||||
expect(
|
|
||||||
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
|
|
||||||
).toBe("origin/feature/pr-local-no-head-repo");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -3324,7 +3089,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
kind: "phase_started",
|
kind: "phase_started",
|
||||||
phase: "pr",
|
phase: "pr",
|
||||||
label: "Creating pull request...",
|
label: "Creating GitHub pull request...",
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
}),
|
}),
|
||||||
@@ -1,96 +1,55 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { realpathSync } from "node:fs";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Array as Arr,
|
|
||||||
Cache,
|
Cache,
|
||||||
Context,
|
|
||||||
DateTime,
|
|
||||||
Duration,
|
Duration,
|
||||||
Effect,
|
Effect,
|
||||||
Exit,
|
Exit,
|
||||||
FileSystem,
|
FileSystem,
|
||||||
Layer,
|
Layer,
|
||||||
Option,
|
Option,
|
||||||
Order,
|
|
||||||
Path,
|
Path,
|
||||||
Ref,
|
Ref,
|
||||||
|
Result,
|
||||||
} from "effect";
|
} from "effect";
|
||||||
import {
|
import {
|
||||||
GitActionProgressEvent,
|
GitActionProgressEvent,
|
||||||
GitActionProgressPhase,
|
GitActionProgressPhase,
|
||||||
GitCommandError,
|
GitCommandError,
|
||||||
GitPreparePullRequestThreadInput,
|
|
||||||
GitPreparePullRequestThreadResult,
|
|
||||||
GitPullRequestRefInput,
|
|
||||||
GitResolvePullRequestResult,
|
|
||||||
GitRunStackedActionInput,
|
|
||||||
GitRunStackedActionResult,
|
GitRunStackedActionResult,
|
||||||
GitStackedAction,
|
GitStackedAction,
|
||||||
VcsStatusInput,
|
type GitStatusLocalResult,
|
||||||
type VcsStatusLocalResult,
|
type GitStatusRemoteResult,
|
||||||
type VcsStatusRemoteResult,
|
|
||||||
VcsStatusResult,
|
|
||||||
ModelSelection,
|
ModelSelection,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
detectSourceControlProviderFromGitRemoteUrl,
|
detectGitHostingProviderFromRemoteUrl,
|
||||||
mergeGitStatusParts,
|
mergeGitStatusParts,
|
||||||
resolveAutoFeatureBranchName,
|
resolveAutoFeatureBranchName,
|
||||||
sanitizeBranchFragment,
|
sanitizeBranchFragment,
|
||||||
sanitizeFeatureBranchName,
|
sanitizeFeatureBranchName,
|
||||||
} from "@t3tools/shared/git";
|
} from "@t3tools/shared/git";
|
||||||
import {
|
|
||||||
getChangeRequestTerminologyForKind,
|
|
||||||
type ChangeRequestTerminology,
|
|
||||||
} from "@t3tools/shared/sourceControl";
|
|
||||||
|
|
||||||
import { GitManagerError } from "@t3tools/contracts";
|
import { GitManagerError } from "@t3tools/contracts";
|
||||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
import {
|
||||||
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
|
GitManager,
|
||||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
type GitActionProgressReporter,
|
||||||
import { ServerSettingsService } from "../serverSettings.ts";
|
type GitManagerShape,
|
||||||
|
type GitRunStackedActionOptions,
|
||||||
|
} from "../Services/GitManager.ts";
|
||||||
|
import { GitCore } from "../Services/GitCore.ts";
|
||||||
|
import type { GitStatusDetails } from "../Services/GitCore.ts";
|
||||||
|
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
|
||||||
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||||
|
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||||
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
|
import {
|
||||||
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
|
decodeGitHubPullRequestListJson,
|
||||||
import type { ChangeRequest } from "@t3tools/contracts";
|
formatGitHubJsonDecodeError,
|
||||||
|
} from "../githubPullRequests.ts";
|
||||||
export interface GitActionProgressReporter {
|
|
||||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitRunStackedActionOptions {
|
|
||||||
readonly actionId?: string;
|
|
||||||
readonly progressReporter?: GitActionProgressReporter;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitManagerShape {
|
|
||||||
readonly status: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
|
||||||
readonly localStatus: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
|
||||||
readonly remoteStatus: (
|
|
||||||
input: VcsStatusInput,
|
|
||||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
|
||||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
|
||||||
readonly resolvePullRequest: (
|
|
||||||
input: GitPullRequestRefInput,
|
|
||||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
|
||||||
readonly preparePullRequestThread: (
|
|
||||||
input: GitPreparePullRequestThreadInput,
|
|
||||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
|
||||||
readonly runStackedAction: (
|
|
||||||
input: GitRunStackedActionInput,
|
|
||||||
options?: GitRunStackedActionOptions,
|
|
||||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
|
||||||
"t3/git/GitManager",
|
|
||||||
) {}
|
|
||||||
|
|
||||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||||
@@ -116,14 +75,9 @@ interface OpenPrInfo {
|
|||||||
|
|
||||||
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
|
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
|
||||||
state: "open" | "closed" | "merged";
|
state: "open" | "closed" | "merged";
|
||||||
updatedAt: Option.Option<DateTime.Utc>;
|
updatedAt: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
|
|
||||||
Order.flip(Option.makeOrder(DateTime.Order)),
|
|
||||||
(pullRequest) => pullRequest.updatedAt,
|
|
||||||
);
|
|
||||||
|
|
||||||
interface ResolvedPullRequest {
|
interface ResolvedPullRequest {
|
||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -134,9 +88,9 @@ interface ResolvedPullRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface PullRequestHeadRemoteInfo {
|
interface PullRequestHeadRemoteInfo {
|
||||||
isCrossRepository?: boolean | undefined;
|
isCrossRepository?: boolean;
|
||||||
headRepositoryNameWithOwner?: string | null | undefined;
|
headRepositoryNameWithOwner?: string | null;
|
||||||
headRepositoryOwnerLogin?: string | null | undefined;
|
headRepositoryOwnerLogin?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BranchHeadContext {
|
interface BranchHeadContext {
|
||||||
@@ -302,7 +256,7 @@ function matchesBranchHeadContext(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
|
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||||
return {
|
return {
|
||||||
number: summary.number,
|
number: summary.number,
|
||||||
title: summary.title,
|
title: summary.title,
|
||||||
@@ -310,7 +264,7 @@ function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
|
|||||||
baseRefName: summary.baseRefName,
|
baseRefName: summary.baseRefName,
|
||||||
headRefName: summary.headRefName,
|
headRefName: summary.headRefName,
|
||||||
state: summary.state ?? "open",
|
state: summary.state ?? "open",
|
||||||
updatedAt: summary.updatedAt,
|
updatedAt: null,
|
||||||
...(summary.isCrossRepository !== undefined
|
...(summary.isCrossRepository !== undefined
|
||||||
? { isCrossRepository: summary.isCrossRepository }
|
? { isCrossRepository: summary.isCrossRepository }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -357,14 +311,13 @@ function withDescription(title: string, description: string | undefined) {
|
|||||||
|
|
||||||
function summarizeGitActionResult(
|
function summarizeGitActionResult(
|
||||||
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
|
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
|
||||||
terms: ChangeRequestTerminology,
|
|
||||||
): {
|
): {
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
} {
|
} {
|
||||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
||||||
const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
|
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
||||||
return withDescription(title, truncateText(result.pr.title));
|
return withDescription(title, truncateText(result.pr.title));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,16 +422,16 @@ function toStatusPr(pr: PullRequestInfo): {
|
|||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
url: string;
|
||||||
baseRef: string;
|
baseBranch: string;
|
||||||
headRef: string;
|
headBranch: string;
|
||||||
state: "open" | "closed" | "merged";
|
state: "open" | "closed" | "merged";
|
||||||
} {
|
} {
|
||||||
return {
|
return {
|
||||||
number: pr.number,
|
number: pr.number,
|
||||||
title: pr.title,
|
title: pr.title,
|
||||||
url: pr.url,
|
url: pr.url,
|
||||||
baseRef: pr.baseRefName,
|
baseBranch: pr.baseRefName,
|
||||||
headRef: pr.headRefName,
|
headBranch: pr.headRefName,
|
||||||
state: pr.state,
|
state: pr.state,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -489,6 +442,14 @@ function normalizePullRequestReference(reference: string): string {
|
|||||||
return hashNumber?.[1] ?? trimmed;
|
return hashNumber?.[1] ?? trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function canonicalizeExistingPath(value: string): string {
|
||||||
|
try {
|
||||||
|
return realpathSync.native(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function toResolvedPullRequest(pr: {
|
function toResolvedPullRequest(pr: {
|
||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -514,9 +475,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function toPullRequestHeadRemoteInfo(pr: {
|
function toPullRequestHeadRemoteInfo(pr: {
|
||||||
isCrossRepository?: boolean | undefined;
|
isCrossRepository?: boolean;
|
||||||
headRepositoryNameWithOwner?: string | null | undefined;
|
headRepositoryNameWithOwner?: string | null;
|
||||||
headRepositoryOwnerLogin?: string | null | undefined;
|
headRepositoryOwnerLogin?: string | null;
|
||||||
}): PullRequestHeadRemoteInfo {
|
}): PullRequestHeadRemoteInfo {
|
||||||
return {
|
return {
|
||||||
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
|
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
|
||||||
@@ -530,12 +491,10 @@ function toPullRequestHeadRemoteInfo(pr: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||||
const gitCore = yield* GitVcsDriver;
|
const gitCore = yield* GitCore;
|
||||||
const sourceControlProviders = yield* SourceControlProviderRegistry;
|
const gitHubCli = yield* GitHubCli;
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
|
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
|
||||||
|
|
||||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
|
||||||
const serverSettingsService = yield* ServerSettingsService;
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
|
|
||||||
const createProgressEmitter = (
|
const createProgressEmitter = (
|
||||||
@@ -568,27 +527,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
localBranch = pullRequest.headBranch,
|
localBranch = pullRequest.headBranch,
|
||||||
) {
|
) {
|
||||||
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
|
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
|
||||||
if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
|
|
||||||
const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
|
|
||||||
yield* gitCore.fetchRemoteTrackingBranch({
|
|
||||||
cwd,
|
|
||||||
remoteName,
|
|
||||||
remoteBranch: pullRequest.headBranch,
|
|
||||||
});
|
|
||||||
yield* gitCore.setBranchUpstream({
|
|
||||||
cwd,
|
|
||||||
branch: localBranch,
|
|
||||||
remoteName,
|
|
||||||
remoteBranch: pullRequest.headBranch,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (repositoryNameWithOwner.length === 0) {
|
if (repositoryNameWithOwner.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
|
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
|
||||||
cwd,
|
cwd,
|
||||||
repository: repositoryNameWithOwner,
|
repository: repositoryNameWithOwner,
|
||||||
});
|
});
|
||||||
@@ -604,11 +547,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
url: remoteUrl,
|
url: remoteUrl,
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* gitCore.fetchRemoteTrackingBranch({
|
|
||||||
cwd,
|
|
||||||
remoteName,
|
|
||||||
remoteBranch: pullRequest.headBranch,
|
|
||||||
});
|
|
||||||
yield* gitCore.setBranchUpstream({
|
yield* gitCore.setBranchUpstream({
|
||||||
cwd,
|
cwd,
|
||||||
branch: localBranch,
|
branch: localBranch,
|
||||||
@@ -648,7 +586,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
|
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
|
||||||
cwd,
|
cwd,
|
||||||
repository: repositoryNameWithOwner,
|
repository: repositoryNameWithOwner,
|
||||||
});
|
});
|
||||||
@@ -697,9 +635,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||||
const canonicalizeExistingPath = (value: string) =>
|
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
|
||||||
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
|
|
||||||
const normalizeStatusCacheKey = canonicalizeExistingPath;
|
|
||||||
const nonRepositoryStatusDetails = {
|
const nonRepositoryStatusDetails = {
|
||||||
isRepo: false,
|
isRepo: false,
|
||||||
hasOriginRemote: false,
|
hasOriginRemote: false,
|
||||||
@@ -711,7 +647,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
aheadOfDefaultCount: 0,
|
|
||||||
} satisfies GitStatusDetails;
|
} satisfies GitStatusDetails;
|
||||||
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
|
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
|
||||||
const details = yield* gitCore
|
const details = yield* gitCore
|
||||||
@@ -725,22 +660,20 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
isRepo: details.isRepo,
|
isRepo: details.isRepo,
|
||||||
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
|
...(hostingProvider ? { hostingProvider } : {}),
|
||||||
hasPrimaryRemote: details.hasOriginRemote,
|
hasOriginRemote: details.hasOriginRemote,
|
||||||
isDefaultRef: details.isDefaultBranch,
|
isDefaultBranch: details.isDefaultBranch,
|
||||||
refName: details.branch,
|
branch: details.branch,
|
||||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||||
workingTree: details.workingTree,
|
workingTree: details.workingTree,
|
||||||
} satisfies VcsStatusLocalResult;
|
} satisfies GitStatusLocalResult;
|
||||||
});
|
});
|
||||||
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
||||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||||
});
|
});
|
||||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||||
normalizeStatusCacheKey(cwd).pipe(
|
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
|
||||||
);
|
|
||||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||||
const details = yield* gitCore
|
const details = yield* gitCore
|
||||||
.statusDetails(cwd)
|
.statusDetails(cwd)
|
||||||
@@ -755,13 +688,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
branch: details.branch,
|
branch: details.branch,
|
||||||
upstreamRef: details.upstreamRef,
|
upstreamRef: details.upstreamRef,
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map((latest) => {
|
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||||
if (!latest) return null;
|
|
||||||
// On the default branch, only surface open PRs.
|
|
||||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
|
||||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
|
||||||
return toStatusPr(latest);
|
|
||||||
}),
|
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
Effect.catch(() => Effect.succeed(null)),
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
@@ -770,18 +697,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
|
||||||
pr,
|
pr,
|
||||||
} satisfies VcsStatusRemoteResult;
|
} satisfies GitStatusRemoteResult;
|
||||||
});
|
});
|
||||||
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
||||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||||
});
|
});
|
||||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||||
normalizeStatusCacheKey(cwd).pipe(
|
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||||
Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||||
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
@@ -798,7 +722,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
|
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
|
||||||
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
|
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
|
||||||
|
|
||||||
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
|
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
|
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
|
||||||
@@ -903,10 +827,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
>,
|
>,
|
||||||
) {
|
) {
|
||||||
for (const headSelector of headContext.headSelectors) {
|
for (const headSelector of headContext.headSelectors) {
|
||||||
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
|
const pullRequests = yield* gitHubCli.listOpenPullRequests({
|
||||||
cwd,
|
cwd,
|
||||||
headSelector,
|
headSelector,
|
||||||
state: "open",
|
|
||||||
limit: 1,
|
limit: 1,
|
||||||
});
|
});
|
||||||
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
|
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
|
||||||
@@ -922,7 +845,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
baseRefName: firstPullRequest.baseRefName,
|
baseRefName: firstPullRequest.baseRefName,
|
||||||
headRefName: firstPullRequest.headRefName,
|
headRefName: firstPullRequest.headRefName,
|
||||||
state: "open",
|
state: "open",
|
||||||
updatedAt: Option.none(),
|
updatedAt: null,
|
||||||
} satisfies PullRequestInfo;
|
} satisfies PullRequestInfo;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -938,14 +861,46 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
const parsedByNumber = new Map<number, PullRequestInfo>();
|
const parsedByNumber = new Map<number, PullRequestInfo>();
|
||||||
|
|
||||||
for (const headSelector of headContext.headSelectors) {
|
for (const headSelector of headContext.headSelectors) {
|
||||||
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
|
const stdout = yield* gitHubCli
|
||||||
cwd,
|
.execute({
|
||||||
headSelector,
|
cwd,
|
||||||
state: "all",
|
args: [
|
||||||
limit: 20,
|
"pr",
|
||||||
});
|
"list",
|
||||||
|
"--head",
|
||||||
|
headSelector,
|
||||||
|
"--state",
|
||||||
|
"all",
|
||||||
|
"--limit",
|
||||||
|
"20",
|
||||||
|
"--json",
|
||||||
|
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(Effect.map((result) => result.stdout));
|
||||||
|
|
||||||
for (const pr of pullRequests.map(toPullRequestInfo)) {
|
const raw = stdout.trim();
|
||||||
|
if (raw.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||||
|
Effect.flatMap((decoded) => {
|
||||||
|
if (!Result.isSuccess(decoded)) {
|
||||||
|
return Effect.fail(
|
||||||
|
gitManagerError(
|
||||||
|
"findLatestPr",
|
||||||
|
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||||
|
decoded.failure,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Effect.succeed(decoded.success);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const pr of pullRequests) {
|
||||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -953,7 +908,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
|
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
|
||||||
|
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||||
|
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||||
|
return right - left;
|
||||||
|
});
|
||||||
|
|
||||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||||
if (latestOpenPr) {
|
if (latestOpenPr) {
|
||||||
@@ -966,11 +925,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
cwd: string,
|
cwd: string,
|
||||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||||
) {
|
) {
|
||||||
const terms = yield* sourceControlProvider(cwd).pipe(
|
const summary = summarizeGitActionResult(result);
|
||||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
|
||||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
|
||||||
);
|
|
||||||
const summary = summarizeGitActionResult(result, terms);
|
|
||||||
let latestOpenPr: PullRequestInfo | null = null;
|
let latestOpenPr: PullRequestInfo | null = null;
|
||||||
let currentBranchIsDefault = false;
|
let currentBranchIsDefault = false;
|
||||||
let finalBranchContext: {
|
let finalBranchContext: {
|
||||||
@@ -1035,7 +990,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
result.pr.status === "opened_existing")
|
result.pr.status === "opened_existing")
|
||||||
? {
|
? {
|
||||||
kind: "open_pr" as const,
|
kind: "open_pr" as const,
|
||||||
label: `View ${terms.shortLabel}`,
|
label: "View PR",
|
||||||
url: openPr.url,
|
url: openPr.url,
|
||||||
}
|
}
|
||||||
: (result.action === "push" || result.action === "commit_push") &&
|
: (result.action === "push" || result.action === "commit_push") &&
|
||||||
@@ -1043,7 +998,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
!currentBranchIsDefault
|
!currentBranchIsDefault
|
||||||
? {
|
? {
|
||||||
kind: "run_action" as const,
|
kind: "run_action" as const,
|
||||||
label: `Create ${terms.shortLabel}`,
|
label: "Create PR",
|
||||||
action: { kind: "create_pr" as const },
|
action: { kind: "create_pr" as const },
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
@@ -1074,12 +1029,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
|
const defaultFromGh = yield* gitHubCli
|
||||||
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
|
.getDefaultBranch({ cwd })
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
);
|
if (defaultFromGh) {
|
||||||
if (defaultFromProvider) {
|
return defaultFromGh;
|
||||||
return defaultFromProvider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "main";
|
return "main";
|
||||||
@@ -1251,8 +1205,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
fallbackBranch: string | null,
|
fallbackBranch: string | null,
|
||||||
emit: GitActionProgressEmitter,
|
emit: GitActionProgressEmitter,
|
||||||
) {
|
) {
|
||||||
const provider = yield* sourceControlProvider(cwd);
|
|
||||||
const terms = getChangeRequestTerminologyForKind(provider.kind);
|
|
||||||
const details = yield* gitCore.statusDetails(cwd);
|
const details = yield* gitCore.statusDetails(cwd);
|
||||||
const branch = details.branch ?? fallbackBranch;
|
const branch = details.branch ?? fallbackBranch;
|
||||||
if (!branch) {
|
if (!branch) {
|
||||||
@@ -1289,7 +1241,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
yield* emit({
|
yield* emit({
|
||||||
kind: "phase_started",
|
kind: "phase_started",
|
||||||
phase: "pr",
|
phase: "pr",
|
||||||
label: `Generating ${terms.shortLabel} content...`,
|
label: "Generating PR content...",
|
||||||
});
|
});
|
||||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||||
|
|
||||||
@@ -1314,12 +1266,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
yield* emit({
|
yield* emit({
|
||||||
kind: "phase_started",
|
kind: "phase_started",
|
||||||
phase: "pr",
|
phase: "pr",
|
||||||
label: `Creating ${terms.singular}...`,
|
label: "Creating GitHub pull request...",
|
||||||
});
|
});
|
||||||
yield* provider
|
yield* gitHubCli
|
||||||
.createChangeRequest({
|
.createPullRequest({
|
||||||
cwd,
|
cwd,
|
||||||
baseRefName: baseBranch,
|
baseBranch,
|
||||||
headSelector: headContext.preferredHeadSelector,
|
headSelector: headContext.preferredHeadSelector,
|
||||||
title: generated.title,
|
title: generated.title,
|
||||||
bodyFile,
|
bodyFile,
|
||||||
@@ -1347,13 +1299,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
||||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
|
||||||
});
|
});
|
||||||
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||||
function* (input) {
|
function* (input) {
|
||||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||||
return yield* Cache.get(remoteStatusResultCache, cacheKey);
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
||||||
@@ -1379,8 +1329,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
|
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
|
||||||
function* (input) {
|
function* (input) {
|
||||||
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
|
const pullRequest = yield* gitHubCli
|
||||||
.getChangeRequest({
|
.getPullRequest({
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
reference: normalizePullRequestReference(input.reference),
|
reference: normalizePullRequestReference(input.reference),
|
||||||
})
|
})
|
||||||
@@ -1413,15 +1363,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
};
|
};
|
||||||
return yield* Effect.gen(function* () {
|
return yield* Effect.gen(function* () {
|
||||||
const normalizedReference = normalizePullRequestReference(input.reference);
|
const normalizedReference = normalizePullRequestReference(input.reference);
|
||||||
const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
|
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
|
||||||
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
|
const pullRequestSummary = yield* gitHubCli.getPullRequest({
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
reference: normalizedReference,
|
reference: normalizedReference,
|
||||||
});
|
});
|
||||||
const pullRequest = toResolvedPullRequest(pullRequestSummary);
|
const pullRequest = toResolvedPullRequest(pullRequestSummary);
|
||||||
|
|
||||||
if (input.mode === "local") {
|
if (input.mode === "local") {
|
||||||
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
|
yield* gitHubCli.checkoutPullRequest({
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
reference: normalizedReference,
|
reference: normalizedReference,
|
||||||
force: true,
|
force: true,
|
||||||
@@ -1463,35 +1413,33 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
const localPullRequestBranch =
|
const localPullRequestBranch =
|
||||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||||
|
|
||||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
const findLocalHeadBranch = (cwd: string) =>
|
||||||
const result = yield* gitCore.listRefs({ cwd });
|
gitCore.listBranches({ cwd }).pipe(
|
||||||
const localBranch = result.refs.find(
|
Effect.map((result) => {
|
||||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
const localBranch = result.branches.find(
|
||||||
|
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||||
|
);
|
||||||
|
if (localBranch) {
|
||||||
|
return localBranch;
|
||||||
|
}
|
||||||
|
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
result.branches.find(
|
||||||
|
(branch) =>
|
||||||
|
!branch.isRemote &&
|
||||||
|
branch.name === pullRequest.headBranch &&
|
||||||
|
branch.worktreePath !== null &&
|
||||||
|
canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
|
||||||
|
) ?? null
|
||||||
|
);
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
if (localBranch) {
|
|
||||||
return localBranch;
|
|
||||||
}
|
|
||||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const branch of result.refs) {
|
|
||||||
if (branch.isRemote || branch.name !== pullRequest.headBranch || !branch.worktreePath) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);
|
|
||||||
if (worktreePath !== rootWorktreePath) {
|
|
||||||
return branch;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
|
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
|
||||||
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
|
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
|
||||||
? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||||
: null;
|
: null;
|
||||||
if (
|
if (
|
||||||
existingBranchBeforeFetch?.worktreePath &&
|
existingBranchBeforeFetch?.worktreePath &&
|
||||||
@@ -1519,7 +1467,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
|
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
|
||||||
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
|
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
|
||||||
? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||||
: null;
|
: null;
|
||||||
if (
|
if (
|
||||||
existingBranchAfterFetch?.worktreePath &&
|
existingBranchAfterFetch?.worktreePath &&
|
||||||
@@ -1541,7 +1489,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
const worktree = yield* gitCore.createWorktree({
|
const worktree = yield* gitCore.createWorktree({
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
refName: localPullRequestBranch,
|
branch: localPullRequestBranch,
|
||||||
path: null,
|
path: null,
|
||||||
});
|
});
|
||||||
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
|
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
|
||||||
@@ -1549,7 +1497,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
pullRequest,
|
pullRequest,
|
||||||
branch: worktree.worktree.refName,
|
branch: worktree.worktree.branch,
|
||||||
worktreePath: worktree.worktree.path,
|
worktreePath: worktree.worktree.path,
|
||||||
};
|
};
|
||||||
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
||||||
@@ -1581,8 +1529,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||||
|
|
||||||
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
|
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||||
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
|
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||||
@@ -1616,6 +1564,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
"Feature-branch checkout is only supported for commit actions.",
|
"Feature-branch checkout is only supported for commit actions.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (input.action === "push" && initialStatus.hasWorkingTreeChanges) {
|
||||||
|
return yield* gitManagerError(
|
||||||
|
"runStackedAction",
|
||||||
|
"Commit or stash local changes before pushing.",
|
||||||
|
);
|
||||||
|
}
|
||||||
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
|
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
|
||||||
return yield* gitManagerError(
|
return yield* gitManagerError(
|
||||||
"runStackedAction",
|
"runStackedAction",
|
||||||
@@ -1679,12 +1633,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
|
|
||||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||||
const commitAction = isCommitAction(input.action) ? input.action : null;
|
const commitAction = isCommitAction(input.action) ? input.action : null;
|
||||||
const changeRequestTerms = wantsPr
|
|
||||||
? yield* sourceControlProvider(input.cwd).pipe(
|
|
||||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
|
||||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
|
||||||
)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const commit = commitAction
|
const commit = commitAction
|
||||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||||
@@ -1722,7 +1670,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
.emit({
|
.emit({
|
||||||
kind: "phase_started",
|
kind: "phase_started",
|
||||||
phase: "pr",
|
phase: "pr",
|
||||||
label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
|
label: "Preparing PR...",
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||||
@@ -1783,4 +1731,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
|||||||
} satisfies GitManagerShape;
|
} satisfies GitManagerShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const layer = Layer.effect(GitManager, makeGitManager());
|
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
|
||||||
+74
-122
@@ -1,78 +1,83 @@
|
|||||||
import { assert, it, describe } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
|
||||||
import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
|
|
||||||
import type {
|
import type {
|
||||||
VcsStatusLocalResult,
|
GitStatusLocalResult,
|
||||||
VcsStatusRemoteResult,
|
GitStatusRemoteResult,
|
||||||
VcsStatusResult,
|
GitStatusResult,
|
||||||
VcsStatusStreamEvent,
|
GitStatusStreamEvent,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import { describe } from "vitest";
|
||||||
|
|
||||||
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
|
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
|
||||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
|
||||||
|
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
|
||||||
|
|
||||||
const baseLocalStatus: VcsStatusLocalResult = {
|
const baseLocalStatus: GitStatusLocalResult = {
|
||||||
isRepo: true,
|
isRepo: true,
|
||||||
sourceControlProvider: {
|
hostingProvider: {
|
||||||
kind: "github",
|
kind: "github",
|
||||||
name: "GitHub",
|
name: "GitHub",
|
||||||
baseUrl: "https://github.com",
|
baseUrl: "https://github.com",
|
||||||
},
|
},
|
||||||
hasPrimaryRemote: true,
|
hasOriginRemote: true,
|
||||||
isDefaultRef: false,
|
isDefaultBranch: false,
|
||||||
refName: "feature/status-broadcast",
|
branch: "feature/status-broadcast",
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||||
hasUpstream: true,
|
hasUpstream: true,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
pr: null,
|
pr: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseStatus: VcsStatusResult = {
|
const baseStatus: GitStatusResult = {
|
||||||
...baseLocalStatus,
|
...baseLocalStatus,
|
||||||
...baseRemoteStatus,
|
...baseRemoteStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
function makeTestLayer(state: {
|
function makeTestLayer(state: {
|
||||||
currentLocalStatus: VcsStatusLocalResult;
|
currentLocalStatus: GitStatusLocalResult;
|
||||||
currentRemoteStatus: VcsStatusRemoteResult | null;
|
currentRemoteStatus: GitStatusRemoteResult | null;
|
||||||
localStatusCalls: number;
|
localStatusCalls: number;
|
||||||
remoteStatusCalls: number;
|
remoteStatusCalls: number;
|
||||||
localInvalidationCalls: number;
|
localInvalidationCalls: number;
|
||||||
remoteInvalidationCalls: number;
|
remoteInvalidationCalls: number;
|
||||||
}) {
|
}) {
|
||||||
return VcsStatusBroadcaster.layer.pipe(
|
const gitManager: GitManagerShape = {
|
||||||
Layer.provide(
|
localStatus: () =>
|
||||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
Effect.sync(() => {
|
||||||
localStatus: () =>
|
state.localStatusCalls += 1;
|
||||||
Effect.sync(() => {
|
return state.currentLocalStatus;
|
||||||
state.localStatusCalls += 1;
|
|
||||||
return state.currentLocalStatus;
|
|
||||||
}),
|
|
||||||
remoteStatus: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
state.remoteStatusCalls += 1;
|
|
||||||
return state.currentRemoteStatus;
|
|
||||||
}),
|
|
||||||
invalidateLocalStatus: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
state.localInvalidationCalls += 1;
|
|
||||||
}),
|
|
||||||
invalidateRemoteStatus: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
state.remoteInvalidationCalls += 1;
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
),
|
remoteStatus: () =>
|
||||||
);
|
Effect.sync(() => {
|
||||||
|
state.remoteStatusCalls += 1;
|
||||||
|
return state.currentRemoteStatus;
|
||||||
|
}),
|
||||||
|
status: () => Effect.die("status should not be called in this test"),
|
||||||
|
invalidateLocalStatus: () =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
state.localInvalidationCalls += 1;
|
||||||
|
}),
|
||||||
|
invalidateRemoteStatus: () =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
state.remoteInvalidationCalls += 1;
|
||||||
|
}),
|
||||||
|
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||||
|
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
|
||||||
|
preparePullRequestThread: () =>
|
||||||
|
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||||
|
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||||
|
};
|
||||||
|
|
||||||
|
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("VcsStatusBroadcaster", () => {
|
describe("GitStatusBroadcasterLive", () => {
|
||||||
it.effect("reuses the cached VCS status across repeated reads", () => {
|
it.effect("reuses the cached git status across repeated reads", () => {
|
||||||
const state = {
|
const state = {
|
||||||
currentLocalStatus: baseLocalStatus,
|
currentLocalStatus: baseLocalStatus,
|
||||||
currentRemoteStatus: baseRemoteStatus,
|
currentRemoteStatus: baseRemoteStatus,
|
||||||
@@ -83,7 +88,7 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
const broadcaster = yield* GitStatusBroadcaster;
|
||||||
|
|
||||||
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
|
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||||
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
|
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||||
@@ -108,12 +113,12 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
const broadcaster = yield* GitStatusBroadcaster;
|
||||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||||
|
|
||||||
state.currentLocalStatus = {
|
state.currentLocalStatus = {
|
||||||
...baseLocalStatus,
|
...baseLocalStatus,
|
||||||
refName: "feature/updated-status",
|
branch: "feature/updated-status",
|
||||||
};
|
};
|
||||||
state.currentRemoteStatus = {
|
state.currentRemoteStatus = {
|
||||||
...baseRemoteStatus,
|
...baseRemoteStatus,
|
||||||
@@ -149,12 +154,12 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
const broadcaster = yield* GitStatusBroadcaster;
|
||||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||||
|
|
||||||
state.currentLocalStatus = {
|
state.currentLocalStatus = {
|
||||||
...baseLocalStatus,
|
...baseLocalStatus,
|
||||||
refName: "feature/local-only-refresh",
|
branch: "feature/local-only-refresh",
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -174,66 +179,6 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||||
});
|
});
|
||||||
|
|
||||||
it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
|
|
||||||
const seenCwds: string[] = [];
|
|
||||||
const state = {
|
|
||||||
currentLocalStatus: baseLocalStatus,
|
|
||||||
currentRemoteStatus: baseRemoteStatus,
|
|
||||||
localStatusCalls: 0,
|
|
||||||
remoteStatusCalls: 0,
|
|
||||||
localInvalidationCalls: 0,
|
|
||||||
remoteInvalidationCalls: 0,
|
|
||||||
};
|
|
||||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
|
||||||
localStatus: (input) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
seenCwds.push(input.cwd);
|
|
||||||
state.localStatusCalls += 1;
|
|
||||||
return state.currentLocalStatus;
|
|
||||||
}),
|
|
||||||
remoteStatus: (input) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
seenCwds.push(input.cwd);
|
|
||||||
state.remoteStatusCalls += 1;
|
|
||||||
return state.currentRemoteStatus;
|
|
||||||
}),
|
|
||||||
invalidateLocalStatus: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
state.localInvalidationCalls += 1;
|
|
||||||
}),
|
|
||||||
invalidateRemoteStatus: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
state.remoteInvalidationCalls += 1;
|
|
||||||
}),
|
|
||||||
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const realDir = yield* fileSystem.makeTempDirectoryScoped({
|
|
||||||
prefix: "t3-vcs-status-real-",
|
|
||||||
});
|
|
||||||
const linkParent = yield* fileSystem.makeTempDirectoryScoped({
|
|
||||||
prefix: "t3-vcs-status-link-",
|
|
||||||
});
|
|
||||||
const linkDir = path.join(linkParent, "repo-link");
|
|
||||||
yield* fileSystem.symlink(realDir, linkDir);
|
|
||||||
const realPath = yield* fileSystem.realPath(realDir);
|
|
||||||
|
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
|
||||||
yield* broadcaster.getStatus({ cwd: linkDir });
|
|
||||||
yield* broadcaster.getStatus({ cwd: realDir });
|
|
||||||
|
|
||||||
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
|
|
||||||
assert.equal(state.localStatusCalls, 1);
|
|
||||||
assert.equal(state.remoteStatusCalls, 1);
|
|
||||||
}).pipe(Effect.provide(Layer.mergeAll(testLayer, NodeServices.layer)));
|
|
||||||
});
|
|
||||||
|
|
||||||
it.effect("streams a local snapshot first and remote updates later", () => {
|
it.effect("streams a local snapshot first and remote updates later", () => {
|
||||||
const state = {
|
const state = {
|
||||||
currentLocalStatus: baseLocalStatus,
|
currentLocalStatus: baseLocalStatus,
|
||||||
@@ -245,9 +190,9 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
const broadcaster = yield* GitStatusBroadcaster;
|
||||||
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||||
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
|
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
|
||||||
if (event._tag === "snapshot") {
|
if (event._tag === "snapshot") {
|
||||||
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
|
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
|
||||||
@@ -266,11 +211,11 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
_tag: "snapshot",
|
_tag: "snapshot",
|
||||||
local: baseLocalStatus,
|
local: baseLocalStatus,
|
||||||
remote: null,
|
remote: null,
|
||||||
} satisfies VcsStatusStreamEvent);
|
} satisfies GitStatusStreamEvent);
|
||||||
assert.deepStrictEqual(remoteUpdated, {
|
assert.deepStrictEqual(remoteUpdated, {
|
||||||
_tag: "remoteUpdated",
|
_tag: "remoteUpdated",
|
||||||
remote: baseRemoteStatus,
|
remote: baseRemoteStatus,
|
||||||
} satisfies VcsStatusStreamEvent);
|
} satisfies GitStatusStreamEvent);
|
||||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -285,9 +230,9 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
};
|
};
|
||||||
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
|
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
const testLayer = GitStatusBroadcasterLive.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
Layer.succeed(GitManager, {
|
||||||
localStatus: () =>
|
localStatus: () =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
state.localStatusCalls += 1;
|
state.localStatusCalls += 1;
|
||||||
@@ -302,13 +247,14 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||||
: Effect.void,
|
: Effect.void,
|
||||||
),
|
),
|
||||||
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
|
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
|
||||||
Effect.onInterrupt(() =>
|
Effect.onInterrupt(() =>
|
||||||
remoteInterruptedDeferred
|
remoteInterruptedDeferred
|
||||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||||
: Effect.void,
|
: Effect.void,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
status: () => Effect.die("status should not be called in this test"),
|
||||||
invalidateLocalStatus: () =>
|
invalidateLocalStatus: () =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
state.localInvalidationCalls += 1;
|
state.localInvalidationCalls += 1;
|
||||||
@@ -317,7 +263,13 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
state.remoteInvalidationCalls += 1;
|
state.remoteInvalidationCalls += 1;
|
||||||
}),
|
}),
|
||||||
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
|
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||||
|
resolvePullRequest: () =>
|
||||||
|
Effect.die("resolvePullRequest should not be called in this test"),
|
||||||
|
preparePullRequestThread: () =>
|
||||||
|
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||||
|
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||||
|
} satisfies GitManagerShape),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -327,9 +279,9 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
remoteInterruptedDeferred = remoteInterrupted;
|
remoteInterruptedDeferred = remoteInterrupted;
|
||||||
remoteStartedDeferred = remoteStarted;
|
remoteStartedDeferred = remoteStarted;
|
||||||
|
|
||||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
const broadcaster = yield* GitStatusBroadcaster;
|
||||||
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||||
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||||
const firstScope = yield* Scope.make();
|
const firstScope = yield* Scope.make();
|
||||||
const secondScope = yield* Scope.make();
|
const secondScope = yield* Scope.make();
|
||||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||||
@@ -350,11 +302,11 @@ describe("VcsStatusBroadcaster", () => {
|
|||||||
assert.equal(state.remoteStatusCalls, 1);
|
assert.equal(state.remoteStatusCalls, 1);
|
||||||
|
|
||||||
yield* Scope.close(firstScope, Exit.void);
|
yield* Scope.close(firstScope, Exit.void);
|
||||||
assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
|
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
|
||||||
|
|
||||||
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
|
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
|
||||||
yield* Deferred.await(remoteInterrupted);
|
yield* Deferred.await(remoteInterrupted);
|
||||||
assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
|
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
|
||||||
}).pipe(Effect.provide(testLayer));
|
}).pipe(Effect.provide(testLayer));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
import { realpathSync } from "node:fs";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Duration,
|
||||||
|
Effect,
|
||||||
|
Exit,
|
||||||
|
Fiber,
|
||||||
|
Layer,
|
||||||
|
PubSub,
|
||||||
|
Ref,
|
||||||
|
Scope,
|
||||||
|
Stream,
|
||||||
|
SynchronizedRef,
|
||||||
|
} from "effect";
|
||||||
|
import type {
|
||||||
|
GitStatusInput,
|
||||||
|
GitStatusLocalResult,
|
||||||
|
GitStatusRemoteResult,
|
||||||
|
GitStatusStreamEvent,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||||
|
|
||||||
|
import {
|
||||||
|
GitStatusBroadcaster,
|
||||||
|
type GitStatusBroadcasterShape,
|
||||||
|
} from "../Services/GitStatusBroadcaster.ts";
|
||||||
|
import { GitManager } from "../Services/GitManager.ts";
|
||||||
|
|
||||||
|
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||||
|
|
||||||
|
interface GitStatusChange {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly event: GitStatusStreamEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CachedValue<T> {
|
||||||
|
readonly fingerprint: string;
|
||||||
|
readonly value: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CachedGitStatus {
|
||||||
|
readonly local: CachedValue<GitStatusLocalResult> | null;
|
||||||
|
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ActiveRemotePoller {
|
||||||
|
readonly fiber: Fiber.Fiber<void, never>;
|
||||||
|
readonly subscriberCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCwd(cwd: string): string {
|
||||||
|
try {
|
||||||
|
return realpathSync.native(cwd);
|
||||||
|
} catch {
|
||||||
|
return cwd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fingerprintStatusPart(status: unknown): string {
|
||||||
|
return JSON.stringify(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GitStatusBroadcasterLive = Layer.effect(
|
||||||
|
GitStatusBroadcaster,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitManager = yield* GitManager;
|
||||||
|
const changesPubSub = yield* Effect.acquireRelease(
|
||||||
|
PubSub.unbounded<GitStatusChange>(),
|
||||||
|
(pubsub) => PubSub.shutdown(pubsub),
|
||||||
|
);
|
||||||
|
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||||
|
Scope.close(scope, Exit.void),
|
||||||
|
);
|
||||||
|
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
|
||||||
|
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||||
|
|
||||||
|
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
|
||||||
|
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
|
||||||
|
cwd: string,
|
||||||
|
local: GitStatusLocalResult,
|
||||||
|
options?: { publish?: boolean },
|
||||||
|
) {
|
||||||
|
const nextLocal = {
|
||||||
|
fingerprint: fingerprintStatusPart(local),
|
||||||
|
value: local,
|
||||||
|
} satisfies CachedValue<GitStatusLocalResult>;
|
||||||
|
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||||
|
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||||
|
const nextCache = new Map(cache);
|
||||||
|
nextCache.set(cwd, {
|
||||||
|
...previous,
|
||||||
|
local: nextLocal,
|
||||||
|
});
|
||||||
|
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (options?.publish && shouldPublish) {
|
||||||
|
yield* PubSub.publish(changesPubSub, {
|
||||||
|
cwd,
|
||||||
|
event: {
|
||||||
|
_tag: "localUpdated",
|
||||||
|
local,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return local;
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
|
||||||
|
cwd: string,
|
||||||
|
remote: GitStatusRemoteResult | null,
|
||||||
|
options?: { publish?: boolean },
|
||||||
|
) {
|
||||||
|
const nextRemote = {
|
||||||
|
fingerprint: fingerprintStatusPart(remote),
|
||||||
|
value: remote,
|
||||||
|
} satisfies CachedValue<GitStatusRemoteResult | null>;
|
||||||
|
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||||
|
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||||
|
const nextCache = new Map(cache);
|
||||||
|
nextCache.set(cwd, {
|
||||||
|
...previous,
|
||||||
|
remote: nextRemote,
|
||||||
|
});
|
||||||
|
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (options?.publish && shouldPublish) {
|
||||||
|
yield* PubSub.publish(changesPubSub, {
|
||||||
|
cwd,
|
||||||
|
event: {
|
||||||
|
_tag: "remoteUpdated",
|
||||||
|
remote,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return remote;
|
||||||
|
});
|
||||||
|
|
||||||
|
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
|
||||||
|
const local = yield* gitManager.localStatus({ cwd });
|
||||||
|
return yield* updateCachedLocalStatus(cwd, local);
|
||||||
|
});
|
||||||
|
|
||||||
|
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
|
||||||
|
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||||
|
return yield* updateCachedRemoteStatus(cwd, remote);
|
||||||
|
});
|
||||||
|
|
||||||
|
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
|
||||||
|
const cached = yield* getCachedStatus(cwd);
|
||||||
|
if (cached?.local) {
|
||||||
|
return cached.local.value;
|
||||||
|
}
|
||||||
|
return yield* loadLocalStatus(cwd);
|
||||||
|
});
|
||||||
|
|
||||||
|
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
|
||||||
|
const cached = yield* getCachedStatus(cwd);
|
||||||
|
if (cached?.remote) {
|
||||||
|
return cached.remote.value;
|
||||||
|
}
|
||||||
|
return yield* loadRemoteStatus(cwd);
|
||||||
|
});
|
||||||
|
|
||||||
|
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) {
|
||||||
|
const normalizedCwd = normalizeCwd(input.cwd);
|
||||||
|
const [local, remote] = yield* Effect.all([
|
||||||
|
getOrLoadLocalStatus(normalizedCwd),
|
||||||
|
getOrLoadRemoteStatus(normalizedCwd),
|
||||||
|
]);
|
||||||
|
return mergeGitStatusParts(local, remote);
|
||||||
|
});
|
||||||
|
|
||||||
|
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||||
|
"refreshLocalStatus",
|
||||||
|
)(function* (cwd) {
|
||||||
|
const normalizedCwd = normalizeCwd(cwd);
|
||||||
|
yield* gitManager.invalidateLocalStatus(normalizedCwd);
|
||||||
|
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
|
||||||
|
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
|
||||||
|
yield* gitManager.invalidateRemoteStatus(cwd);
|
||||||
|
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||||
|
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
|
||||||
|
function* (cwd) {
|
||||||
|
const normalizedCwd = normalizeCwd(cwd);
|
||||||
|
const [local, remote] = yield* Effect.all([
|
||||||
|
refreshLocalStatus(normalizedCwd),
|
||||||
|
refreshRemoteStatus(normalizedCwd),
|
||||||
|
]);
|
||||||
|
return mergeGitStatusParts(local, remote);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const makeRemoteRefreshLoop = (cwd: string) => {
|
||||||
|
const logRefreshFailure = (error: Error) =>
|
||||||
|
Effect.logWarning("git remote status refresh failed", {
|
||||||
|
cwd,
|
||||||
|
detail: error.message,
|
||||||
|
});
|
||||||
|
|
||||||
|
return refreshRemoteStatus(cwd).pipe(
|
||||||
|
Effect.catch(logRefreshFailure),
|
||||||
|
Effect.andThen(
|
||||||
|
Effect.forever(
|
||||||
|
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
|
||||||
|
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
|
||||||
|
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||||
|
const existing = activePollers.get(cwd);
|
||||||
|
if (existing) {
|
||||||
|
const nextPollers = new Map(activePollers);
|
||||||
|
nextPollers.set(cwd, {
|
||||||
|
...existing,
|
||||||
|
subscriberCount: existing.subscriberCount + 1,
|
||||||
|
});
|
||||||
|
return Effect.succeed([undefined, nextPollers] as const);
|
||||||
|
}
|
||||||
|
|
||||||
|
return makeRemoteRefreshLoop(cwd).pipe(
|
||||||
|
Effect.forkIn(broadcasterScope),
|
||||||
|
Effect.map((fiber) => {
|
||||||
|
const nextPollers = new Map(activePollers);
|
||||||
|
nextPollers.set(cwd, {
|
||||||
|
fiber,
|
||||||
|
subscriberCount: 1,
|
||||||
|
});
|
||||||
|
return [undefined, nextPollers] as const;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
|
||||||
|
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||||
|
const existing = activePollers.get(cwd);
|
||||||
|
if (!existing) {
|
||||||
|
return [null, activePollers] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing.subscriberCount > 1) {
|
||||||
|
const nextPollers = new Map(activePollers);
|
||||||
|
nextPollers.set(cwd, {
|
||||||
|
...existing,
|
||||||
|
subscriberCount: existing.subscriberCount - 1,
|
||||||
|
});
|
||||||
|
return [null, nextPollers] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextPollers = new Map(activePollers);
|
||||||
|
nextPollers.delete(cwd);
|
||||||
|
return [existing.fiber, nextPollers] as const;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (pollerToInterrupt) {
|
||||||
|
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||||
|
Stream.unwrap(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const normalizedCwd = normalizeCwd(input.cwd);
|
||||||
|
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||||
|
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
|
||||||
|
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
|
||||||
|
yield* retainRemotePoller(normalizedCwd);
|
||||||
|
|
||||||
|
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
|
||||||
|
|
||||||
|
return Stream.concat(
|
||||||
|
Stream.make({
|
||||||
|
_tag: "snapshot" as const,
|
||||||
|
local: initialLocal,
|
||||||
|
remote: initialRemote,
|
||||||
|
}),
|
||||||
|
Stream.fromSubscription(subscription).pipe(
|
||||||
|
Stream.filter((event) => event.cwd === normalizedCwd),
|
||||||
|
Stream.map((event) => event.event),
|
||||||
|
),
|
||||||
|
).pipe(Stream.ensuring(release));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
getStatus,
|
||||||
|
refreshLocalStatus,
|
||||||
|
refreshStatus,
|
||||||
|
streamStatus,
|
||||||
|
} satisfies GitStatusBroadcasterShape;
|
||||||
|
}),
|
||||||
|
);
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Duration, Effect, Layer } from "effect";
|
||||||
|
import { TestClock } from "effect/testing";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
import { beforeEach, expect } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
import {
|
||||||
|
OpenCodeRuntime,
|
||||||
|
OpenCodeRuntimeError,
|
||||||
|
type OpenCodeRuntimeShape,
|
||||||
|
} from "../../provider/opencodeRuntime.ts";
|
||||||
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||||
|
|
||||||
|
const runtimeMock = {
|
||||||
|
state: {
|
||||||
|
startCalls: [] as string[],
|
||||||
|
promptUrls: [] as string[],
|
||||||
|
authHeaders: [] as Array<string | null>,
|
||||||
|
closeCalls: [] as string[],
|
||||||
|
promptResult: undefined as
|
||||||
|
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
|
||||||
|
| undefined,
|
||||||
|
},
|
||||||
|
reset() {
|
||||||
|
this.state.startCalls.length = 0;
|
||||||
|
this.state.promptUrls.length = 0;
|
||||||
|
this.state.authHeaders.length = 0;
|
||||||
|
this.state.closeCalls.length = 0;
|
||||||
|
this.state.promptResult = undefined;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||||
|
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const index = runtimeMock.state.startCalls.length + 1;
|
||||||
|
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||||
|
runtimeMock.state.startCalls.push(binaryPath);
|
||||||
|
// The production runtime binds server lifetime to the caller's scope.
|
||||||
|
// Mirror that here so the closeCalls probe observes scope close.
|
||||||
|
yield* Effect.addFinalizer(() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
runtimeMock.state.closeCalls.push(url);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
exitCode: Effect.never,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||||
|
Effect.succeed({
|
||||||
|
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||||
|
exitCode: null,
|
||||||
|
external: Boolean(serverUrl),
|
||||||
|
}),
|
||||||
|
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||||
|
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||||
|
({
|
||||||
|
session: {
|
||||||
|
create: async () => ({ data: { id: `${baseUrl}/session` } }),
|
||||||
|
prompt: async () => {
|
||||||
|
runtimeMock.state.promptUrls.push(baseUrl);
|
||||||
|
runtimeMock.state.authHeaders.push(
|
||||||
|
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
runtimeMock.state.promptResult ?? {
|
||||||
|
data: {
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: JSON.stringify({
|
||||||
|
subject: "Improve OpenCode reuse",
|
||||||
|
body: "Reuse one server for the full action.",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||||
|
loadOpenCodeInventory: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new OpenCodeRuntimeError({
|
||||||
|
operation: "loadOpenCodeInventory",
|
||||||
|
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||||
|
cause: null,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||||
|
provider: "opencode" as const,
|
||||||
|
model: "openai/gpt-5",
|
||||||
|
};
|
||||||
|
|
||||||
|
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||||
|
|
||||||
|
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerSettingsService.layerTest({
|
||||||
|
providers: {
|
||||||
|
opencode: {
|
||||||
|
binaryPath: "fake-opencode",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-opencode-text-generation-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NetService.layer),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerSettingsService.layerTest({
|
||||||
|
providers: {
|
||||||
|
opencode: {
|
||||||
|
binaryPath: "fake-opencode",
|
||||||
|
serverUrl: "http://127.0.0.1:9999",
|
||||||
|
serverPassword: "secret-password",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-opencode-text-generation-existing-server-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NetService.layer),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
runtimeMock.reset();
|
||||||
|
});
|
||||||
|
|
||||||
|
const advanceIdleClock = Effect.gen(function* () {
|
||||||
|
yield* Effect.yieldNow;
|
||||||
|
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
|
||||||
|
yield* Effect.yieldNow;
|
||||||
|
});
|
||||||
|
|
||||||
|
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
|
||||||
|
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
|
||||||
|
expect(runtimeMock.state.promptUrls).toEqual([
|
||||||
|
"http://127.0.0.1:4301",
|
||||||
|
"http://127.0.0.1:4301",
|
||||||
|
]);
|
||||||
|
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||||
|
|
||||||
|
yield* advanceIdleClock;
|
||||||
|
|
||||||
|
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||||
|
}).pipe(Effect.provide(TestClock.layer())),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("starts a new server after the warm server idles out", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* advanceIdleClock;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
|
||||||
|
expect(runtimeMock.state.promptUrls).toEqual([
|
||||||
|
"http://127.0.0.1:4301",
|
||||||
|
"http://127.0.0.1:4302",
|
||||||
|
]);
|
||||||
|
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||||
|
}).pipe(Effect.provide(TestClock.layer())),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
runtimeMock.state.promptResult = { data: {} };
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const error = yield* textGeneration
|
||||||
|
.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
})
|
||||||
|
.pipe(Effect.flip);
|
||||||
|
|
||||||
|
expect(error.message).toContain("OpenCode returned empty output.");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("parses JSON returned as plain text output", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
runtimeMock.state.promptResult = {
|
||||||
|
data: {
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const result = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
subject: "Tighten OpenCode parsing",
|
||||||
|
body: "Handle JSON text output locally.",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
runtimeMock.state.promptResult = {
|
||||||
|
data: {
|
||||||
|
info: {
|
||||||
|
error: {
|
||||||
|
name: "StructuredOutputError",
|
||||||
|
data: {
|
||||||
|
message: "Model did not produce structured output",
|
||||||
|
retries: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const error = yield* textGeneration
|
||||||
|
.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
})
|
||||||
|
.pipe(Effect.flip);
|
||||||
|
|
||||||
|
expect(error.message).toContain("Model did not produce structured output");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||||
|
"OpenCodeTextGenerationLive with configured server URL",
|
||||||
|
(it) => {
|
||||||
|
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/opencode-reuse",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(runtimeMock.state.startCalls).toEqual([]);
|
||||||
|
expect(runtimeMock.state.promptUrls).toEqual([
|
||||||
|
"http://127.0.0.1:9999",
|
||||||
|
"http://127.0.0.1:9999",
|
||||||
|
]);
|
||||||
|
expect(runtimeMock.state.authHeaders).toEqual([
|
||||||
|
`Basic ${btoa("opencode:secret-password")}`,
|
||||||
|
`Basic ${btoa("opencode:secret-password")}`,
|
||||||
|
]);
|
||||||
|
|
||||||
|
yield* advanceIdleClock;
|
||||||
|
|
||||||
|
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||||
|
}).pipe(Effect.provide(TestClock.layer())),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
+67
-20
@@ -1,30 +1,30 @@
|
|||||||
import { Effect, Exit, Fiber, Schema, Scope } from "effect";
|
import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||||
import * as Semaphore from "effect/Semaphore";
|
import * as Semaphore from "effect/Semaphore";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
TextGenerationError,
|
TextGenerationError,
|
||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
type ModelSelection,
|
type OpenCodeModelSelection,
|
||||||
type OpenCodeSettings,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||||
|
|
||||||
import { ServerConfig } from "../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { resolveAttachmentPath } from "../attachmentStore.ts";
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import {
|
import {
|
||||||
buildBranchNamePrompt,
|
buildBranchNamePrompt,
|
||||||
buildCommitMessagePrompt,
|
buildCommitMessagePrompt,
|
||||||
buildPrContentPrompt,
|
buildPrContentPrompt,
|
||||||
buildThreadTitlePrompt,
|
buildThreadTitlePrompt,
|
||||||
} from "./TextGenerationPrompts.ts";
|
} from "../Prompts.ts";
|
||||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import {
|
import {
|
||||||
extractJsonObject,
|
extractJsonObject,
|
||||||
sanitizeCommitSubject,
|
sanitizeCommitSubject,
|
||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
sanitizeThreadTitle,
|
sanitizeThreadTitle,
|
||||||
} from "./TextGenerationUtils.ts";
|
} from "../Utils.ts";
|
||||||
import {
|
import {
|
||||||
OpenCodeRuntime,
|
OpenCodeRuntime,
|
||||||
type OpenCodeServerConnection,
|
type OpenCodeServerConnection,
|
||||||
@@ -32,7 +32,7 @@ import {
|
|||||||
openCodeRuntimeErrorDetail,
|
openCodeRuntimeErrorDetail,
|
||||||
parseOpenCodeModelSlug,
|
parseOpenCodeModelSlug,
|
||||||
toOpenCodeFileParts,
|
toOpenCodeFileParts,
|
||||||
} from "../provider/opencodeRuntime.ts";
|
} from "../../provider/opencodeRuntime.ts";
|
||||||
|
|
||||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||||
|
|
||||||
@@ -93,11 +93,9 @@ interface SharedOpenCodeTextGenerationServerState {
|
|||||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
|
const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||||
openCodeSettings: OpenCodeSettings,
|
|
||||||
environment: NodeJS.ProcessEnv = process.env,
|
|
||||||
) {
|
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||||
Scope.close(scope, Exit.void),
|
Scope.close(scope, Exit.void),
|
||||||
@@ -204,7 +202,6 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
openCodeRuntime
|
openCodeRuntime
|
||||||
.startOpenCodeServerProcess({
|
.startOpenCodeServerProcess({
|
||||||
binaryPath: input.binaryPath,
|
binaryPath: input.binaryPath,
|
||||||
environment,
|
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.provideService(Scope.Scope, serverScope),
|
Effect.provideService(Scope.Scope, serverScope),
|
||||||
@@ -270,7 +267,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
readonly prompt: string;
|
readonly prompt: string;
|
||||||
readonly outputSchemaJson: S;
|
readonly outputSchemaJson: S;
|
||||||
readonly modelSelection: ModelSelection;
|
readonly modelSelection: OpenCodeModelSelection;
|
||||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
}) {
|
}) {
|
||||||
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
|
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
|
||||||
@@ -281,6 +278,26 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const settings = yield* serverSettingsService.getSettings.pipe(
|
||||||
|
Effect.map(
|
||||||
|
(value) =>
|
||||||
|
value.providers?.opencode ?? {
|
||||||
|
enabled: true,
|
||||||
|
binaryPath: "opencode",
|
||||||
|
serverUrl: "",
|
||||||
|
serverPassword: "",
|
||||||
|
customModels: [],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Effect.orElseSucceed(() => ({
|
||||||
|
enabled: true,
|
||||||
|
binaryPath: "opencode",
|
||||||
|
serverUrl: "",
|
||||||
|
serverPassword: "",
|
||||||
|
customModels: [],
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
const fileParts = toOpenCodeFileParts({
|
const fileParts = toOpenCodeFileParts({
|
||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
resolveAttachmentPath: (attachment) =>
|
resolveAttachmentPath: (attachment) =>
|
||||||
@@ -293,8 +310,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||||
baseUrl: server.url,
|
baseUrl: server.url,
|
||||||
directory: input.cwd,
|
directory: input.cwd,
|
||||||
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
|
...(settings.serverUrl.length > 0 && settings.serverPassword
|
||||||
? { serverPassword: openCodeSettings.serverPassword }
|
? { serverPassword: settings.serverPassword }
|
||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
const session = await client.session.create({
|
const session = await client.session.create({
|
||||||
@@ -337,11 +354,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
});
|
});
|
||||||
|
|
||||||
const rawOutput =
|
const rawOutput =
|
||||||
openCodeSettings.serverUrl.length > 0
|
settings.serverUrl.length > 0
|
||||||
? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
|
? yield* runAgainstServer({ url: settings.serverUrl })
|
||||||
: yield* Effect.acquireUseRelease(
|
: yield* Effect.acquireUseRelease(
|
||||||
acquireSharedServer({
|
acquireSharedServer({
|
||||||
binaryPath: openCodeSettings.binaryPath,
|
binaryPath: settings.binaryPath,
|
||||||
operation: input.operation,
|
operation: input.operation,
|
||||||
}),
|
}),
|
||||||
runAgainstServer,
|
runAgainstServer,
|
||||||
@@ -366,6 +383,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||||
"OpenCodeTextGeneration.generateCommitMessage",
|
"OpenCodeTextGeneration.generateCommitMessage",
|
||||||
)(function* (input) {
|
)(function* (input) {
|
||||||
|
if (input.modelSelection.provider !== "opencode") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||||
branch: input.branch,
|
branch: input.branch,
|
||||||
stagedSummary: input.stagedSummary,
|
stagedSummary: input.stagedSummary,
|
||||||
@@ -392,6 +416,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||||
"OpenCodeTextGeneration.generatePrContent",
|
"OpenCodeTextGeneration.generatePrContent",
|
||||||
)(function* (input) {
|
)(function* (input) {
|
||||||
|
if (input.modelSelection.provider !== "opencode") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||||
baseBranch: input.baseBranch,
|
baseBranch: input.baseBranch,
|
||||||
headBranch: input.headBranch,
|
headBranch: input.headBranch,
|
||||||
@@ -416,6 +447,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||||
"OpenCodeTextGeneration.generateBranchName",
|
"OpenCodeTextGeneration.generateBranchName",
|
||||||
)(function* (input) {
|
)(function* (input) {
|
||||||
|
if (input.modelSelection.provider !== "opencode") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||||
message: input.message,
|
message: input.message,
|
||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
@@ -437,6 +475,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||||
"OpenCodeTextGeneration.generateThreadTitle",
|
"OpenCodeTextGeneration.generateThreadTitle",
|
||||||
)(function* (input) {
|
)(function* (input) {
|
||||||
|
if (input.modelSelection.provider !== "opencode") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||||
message: input.message,
|
message: input.message,
|
||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
@@ -462,3 +507,5 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
|||||||
generateThreadTitle,
|
generateThreadTitle,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/**
|
||||||
|
* 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, Context } from "effect";
|
||||||
|
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||||
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
|
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||||
|
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||||
|
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Internal service tags so both concrete layers can coexist.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
|
||||||
|
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
||||||
|
) {}
|
||||||
|
|
||||||
|
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||||
|
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||||
|
) {}
|
||||||
|
|
||||||
|
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
|
||||||
|
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
|
||||||
|
) {}
|
||||||
|
|
||||||
|
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
|
||||||
|
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Routing implementation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||||
|
const byProvider = {
|
||||||
|
codex: yield* CodexTextGen,
|
||||||
|
claudeAgent: yield* ClaudeTextGen,
|
||||||
|
cursor: yield* CursorTextGen,
|
||||||
|
opencode: yield* OpenCodeTextGen,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
generateCommitMessage: (input) =>
|
||||||
|
byProvider[input.modelSelection.provider].generateCommitMessage(input),
|
||||||
|
generatePrContent: (input) =>
|
||||||
|
byProvider[input.modelSelection.provider].generatePrContent(input),
|
||||||
|
generateBranchName: (input) =>
|
||||||
|
byProvider[input.modelSelection.provider].generateBranchName(input),
|
||||||
|
generateThreadTitle: (input) =>
|
||||||
|
byProvider[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));
|
||||||
|
|
||||||
|
const InternalCursorLayer = Layer.effect(
|
||||||
|
CursorTextGen,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const svc = yield* TextGeneration;
|
||||||
|
return svc;
|
||||||
|
}),
|
||||||
|
).pipe(Layer.provide(CursorTextGenerationLive));
|
||||||
|
|
||||||
|
const InternalOpenCodeLayer = Layer.effect(
|
||||||
|
OpenCodeTextGen,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const svc = yield* TextGeneration;
|
||||||
|
return svc;
|
||||||
|
}),
|
||||||
|
).pipe(Layer.provide(OpenCodeTextGenerationLive));
|
||||||
|
|
||||||
|
export const RoutingTextGenerationLive = Layer.effect(
|
||||||
|
TextGeneration,
|
||||||
|
makeRoutingTextGeneration,
|
||||||
|
).pipe(
|
||||||
|
Layer.provide(InternalCodexLayer),
|
||||||
|
Layer.provide(InternalClaudeLayer),
|
||||||
|
Layer.provide(InternalCursorLayer),
|
||||||
|
Layer.provide(InternalOpenCodeLayer),
|
||||||
|
);
|
||||||
+2
-2
@@ -5,8 +5,8 @@ import {
|
|||||||
buildCommitMessagePrompt,
|
buildCommitMessagePrompt,
|
||||||
buildPrContentPrompt,
|
buildPrContentPrompt,
|
||||||
buildThreadTitlePrompt,
|
buildThreadTitlePrompt,
|
||||||
} from "./TextGenerationPrompts.ts";
|
} from "./Prompts.ts";
|
||||||
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
|
|
||||||
describe("buildCommitMessagePrompt", () => {
|
describe("buildCommitMessagePrompt", () => {
|
||||||
+1
-17
@@ -9,13 +9,7 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema } from "effect";
|
||||||
import type { ChatAttachment } from "@t3tools/contracts";
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { limitSection } from "./TextGenerationUtils.ts";
|
import { limitSection } from "./Utils.ts";
|
||||||
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
|
|
||||||
|
|
||||||
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
|
|
||||||
const trimmed = instruction?.trim();
|
|
||||||
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Commit message
|
// Commit message
|
||||||
@@ -26,7 +20,6 @@ export interface CommitMessagePromptInput {
|
|||||||
stagedSummary: string;
|
stagedSummary: string;
|
||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
includeBranch: boolean;
|
includeBranch: boolean;
|
||||||
policy?: TextGenerationPolicy | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||||
@@ -44,7 +37,6 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
|||||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||||
: []),
|
: []),
|
||||||
"- capture the primary user-visible or developer-visible change",
|
"- capture the primary user-visible or developer-visible change",
|
||||||
...policyInstruction(input.policy?.commitInstructions),
|
|
||||||
"",
|
"",
|
||||||
`Branch: ${input.branch ?? "(detached)"}`,
|
`Branch: ${input.branch ?? "(detached)"}`,
|
||||||
"",
|
"",
|
||||||
@@ -85,7 +77,6 @@ export interface PrContentPromptInput {
|
|||||||
commitSummary: string;
|
commitSummary: string;
|
||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
policy?: TextGenerationPolicy | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||||
@@ -97,7 +88,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
|
|||||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||||
"- under Summary, provide short bullet points",
|
"- under Summary, provide short bullet points",
|
||||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||||
...policyInstruction(input.policy?.changeRequestInstructions),
|
|
||||||
"",
|
"",
|
||||||
`Base branch: ${input.baseBranch}`,
|
`Base branch: ${input.baseBranch}`,
|
||||||
`Head branch: ${input.headBranch}`,
|
`Head branch: ${input.headBranch}`,
|
||||||
@@ -127,7 +117,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
|
|||||||
export interface BranchNamePromptInput {
|
export interface BranchNamePromptInput {
|
||||||
message: string;
|
message: string;
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
policy?: TextGenerationPolicy | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PromptFromMessageInput {
|
interface PromptFromMessageInput {
|
||||||
@@ -136,7 +125,6 @@ interface PromptFromMessageInput {
|
|||||||
rules: ReadonlyArray<string>;
|
rules: ReadonlyArray<string>;
|
||||||
message: string;
|
message: string;
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
additionalInstructions?: string | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||||
@@ -152,7 +140,6 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
|||||||
"",
|
"",
|
||||||
"User message:",
|
"User message:",
|
||||||
limitSection(input.message, 8_000),
|
limitSection(input.message, 8_000),
|
||||||
...policyInstruction(input.additionalInstructions),
|
|
||||||
];
|
];
|
||||||
if (attachmentLines.length > 0) {
|
if (attachmentLines.length > 0) {
|
||||||
promptSections.push(
|
promptSections.push(
|
||||||
@@ -177,7 +164,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
|||||||
],
|
],
|
||||||
message: input.message,
|
message: input.message,
|
||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
additionalInstructions: input.policy?.branchInstructions,
|
|
||||||
});
|
});
|
||||||
const outputSchema = Schema.Struct({
|
const outputSchema = Schema.Struct({
|
||||||
branch: Schema.String,
|
branch: Schema.String,
|
||||||
@@ -193,7 +179,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
|||||||
export interface ThreadTitlePromptInput {
|
export interface ThreadTitlePromptInput {
|
||||||
message: string;
|
message: string;
|
||||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
policy?: TextGenerationPolicy | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||||
@@ -208,7 +193,6 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
|||||||
],
|
],
|
||||||
message: input.message,
|
message: input.message,
|
||||||
attachments: input.attachments,
|
attachments: input.attachments,
|
||||||
additionalInstructions: input.policy?.threadTitleInstructions,
|
|
||||||
});
|
});
|
||||||
const outputSchema = Schema.Struct({
|
const outputSchema = Schema.Struct({
|
||||||
title: Schema.String,
|
title: Schema.String,
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
/**
|
||||||
|
* GitCore - Effect service contract for low-level Git operations.
|
||||||
|
*
|
||||||
|
* Wraps core repository primitives used by higher-level orchestration
|
||||||
|
* services and WebSocket routes.
|
||||||
|
*
|
||||||
|
* @module GitCore
|
||||||
|
*/
|
||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
import type {
|
||||||
|
GitCheckoutInput,
|
||||||
|
GitCheckoutResult,
|
||||||
|
GitCreateBranchInput,
|
||||||
|
GitCreateBranchResult,
|
||||||
|
GitCreateWorktreeInput,
|
||||||
|
GitCreateWorktreeResult,
|
||||||
|
GitInitInput,
|
||||||
|
GitListBranchesInput,
|
||||||
|
GitListBranchesResult,
|
||||||
|
GitPullResult,
|
||||||
|
GitRemoveWorktreeInput,
|
||||||
|
GitStatusInput,
|
||||||
|
GitStatusResult,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import type { GitCommandError } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
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"> {
|
||||||
|
upstreamRef: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitPreparedCommitContext {
|
||||||
|
stagedSummary: 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 {
|
||||||
|
status: "pushed" | "skipped_up_to_date";
|
||||||
|
branch: string;
|
||||||
|
upstreamBranch?: string | undefined;
|
||||||
|
setUpstream?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitRangeContext {
|
||||||
|
commitSummary: string;
|
||||||
|
diffSummary: string;
|
||||||
|
diffPatch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitListWorkspaceFilesResult {
|
||||||
|
readonly paths: ReadonlyArray<string>;
|
||||||
|
readonly truncated: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchInput {
|
||||||
|
cwd: string;
|
||||||
|
oldBranch: string;
|
||||||
|
newBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchResult {
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitFetchPullRequestBranchInput {
|
||||||
|
cwd: string;
|
||||||
|
prNumber: number;
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitEnsureRemoteInput {
|
||||||
|
cwd: string;
|
||||||
|
preferredName: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitFetchRemoteBranchInput {
|
||||||
|
cwd: string;
|
||||||
|
remoteName: string;
|
||||||
|
remoteBranch: string;
|
||||||
|
localBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitSetBranchUpstreamInput {
|
||||||
|
cwd: string;
|
||||||
|
branch: string;
|
||||||
|
remoteName: string;
|
||||||
|
remoteBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||||
|
*/
|
||||||
|
export interface GitCoreShape {
|
||||||
|
/**
|
||||||
|
* Execute a raw Git command.
|
||||||
|
*/
|
||||||
|
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read Git status for a repository.
|
||||||
|
*/
|
||||||
|
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read detailed working tree / branch status for a repository.
|
||||||
|
*/
|
||||||
|
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read detailed working tree / branch status without refreshing remote tracking refs.
|
||||||
|
*/
|
||||||
|
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build staged change context for commit generation.
|
||||||
|
*/
|
||||||
|
readonly prepareCommitContext: (
|
||||||
|
cwd: string,
|
||||||
|
filePaths?: readonly string[],
|
||||||
|
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a commit with provided subject/body.
|
||||||
|
*/
|
||||||
|
readonly commit: (
|
||||||
|
cwd: string,
|
||||||
|
subject: string,
|
||||||
|
body: string,
|
||||||
|
options?: GitCommitOptions,
|
||||||
|
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push current branch, setting upstream if needed.
|
||||||
|
*/
|
||||||
|
readonly pushCurrentBranch: (
|
||||||
|
cwd: string,
|
||||||
|
fallbackBranch: string | null,
|
||||||
|
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collect commit/diff context between base branch and current HEAD.
|
||||||
|
*/
|
||||||
|
readonly readRangeContext: (
|
||||||
|
cwd: string,
|
||||||
|
baseBranch: string,
|
||||||
|
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a Git config value from the local repository.
|
||||||
|
*/
|
||||||
|
readonly readConfigValue: (
|
||||||
|
cwd: string,
|
||||||
|
key: string,
|
||||||
|
) => 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.
|
||||||
|
*/
|
||||||
|
readonly listBranches: (
|
||||||
|
input: GitListBranchesInput,
|
||||||
|
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pull current branch from upstream using fast-forward only.
|
||||||
|
*/
|
||||||
|
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a worktree and branch from a base branch.
|
||||||
|
*/
|
||||||
|
readonly createWorktree: (
|
||||||
|
input: GitCreateWorktreeInput,
|
||||||
|
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Materialize a GitHub pull request head as a local branch without switching checkout.
|
||||||
|
*/
|
||||||
|
readonly fetchPullRequestBranch: (
|
||||||
|
input: GitFetchPullRequestBranchInput,
|
||||||
|
) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
|
||||||
|
*/
|
||||||
|
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch a remote branch into a local branch without checkout.
|
||||||
|
*/
|
||||||
|
readonly fetchRemoteBranch: (
|
||||||
|
input: GitFetchRemoteBranchInput,
|
||||||
|
) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the upstream tracking branch for a local branch.
|
||||||
|
*/
|
||||||
|
readonly setBranchUpstream: (
|
||||||
|
input: GitSetBranchUpstreamInput,
|
||||||
|
) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove an existing worktree.
|
||||||
|
*/
|
||||||
|
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename an existing local branch.
|
||||||
|
*/
|
||||||
|
readonly renameBranch: (
|
||||||
|
input: GitRenameBranchInput,
|
||||||
|
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a local branch.
|
||||||
|
*/
|
||||||
|
readonly createBranch: (
|
||||||
|
input: GitCreateBranchInput,
|
||||||
|
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||||
|
*/
|
||||||
|
readonly checkoutBranch: (
|
||||||
|
input: GitCheckoutInput,
|
||||||
|
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize a repository in the provided directory.
|
||||||
|
*/
|
||||||
|
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List local branch names (short format).
|
||||||
|
*/
|
||||||
|
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitCore - Service tag for low-level Git repository operations.
|
||||||
|
*/
|
||||||
|
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/**
|
||||||
|
* GitHubCli - Effect service contract for `gh` process interactions.
|
||||||
|
*
|
||||||
|
* Provides thin command execution helpers used by Git workflow orchestration.
|
||||||
|
*
|
||||||
|
* @module GitHubCli
|
||||||
|
*/
|
||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
|
import type { ProcessRunResult } from "../../processRunner.ts";
|
||||||
|
import type { GitHubCliError } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
export interface GitHubPullRequestSummary {
|
||||||
|
readonly number: number;
|
||||||
|
readonly title: string;
|
||||||
|
readonly url: string;
|
||||||
|
readonly baseRefName: string;
|
||||||
|
readonly headRefName: string;
|
||||||
|
readonly state?: "open" | "closed" | "merged";
|
||||||
|
readonly isCrossRepository?: boolean;
|
||||||
|
readonly headRepositoryNameWithOwner?: string | null;
|
||||||
|
readonly headRepositoryOwnerLogin?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitHubRepositoryCloneUrls {
|
||||||
|
readonly nameWithOwner: string;
|
||||||
|
readonly url: string;
|
||||||
|
readonly sshUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHubCliShape - Service API for executing GitHub CLI commands.
|
||||||
|
*/
|
||||||
|
export interface GitHubCliShape {
|
||||||
|
/**
|
||||||
|
* Execute a GitHub CLI command and return full process output.
|
||||||
|
*/
|
||||||
|
readonly execute: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly args: ReadonlyArray<string>;
|
||||||
|
readonly timeoutMs?: number;
|
||||||
|
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List open pull requests for a head branch.
|
||||||
|
*/
|
||||||
|
readonly listOpenPullRequests: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly headSelector: string;
|
||||||
|
readonly limit?: number;
|
||||||
|
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a pull request by URL, number, or branch-ish identifier.
|
||||||
|
*/
|
||||||
|
readonly getPullRequest: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly reference: string;
|
||||||
|
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve clone URLs for a GitHub repository.
|
||||||
|
*/
|
||||||
|
readonly getRepositoryCloneUrls: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly repository: string;
|
||||||
|
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a pull request from branch context and body file.
|
||||||
|
*/
|
||||||
|
readonly createPullRequest: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly baseBranch: string;
|
||||||
|
readonly headSelector: string;
|
||||||
|
readonly title: string;
|
||||||
|
readonly bodyFile: string;
|
||||||
|
}) => Effect.Effect<void, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve repository default branch through GitHub metadata.
|
||||||
|
*/
|
||||||
|
readonly getDefaultBranch: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
}) => Effect.Effect<string | null, GitHubCliError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checkout a pull request into the current repository worktree.
|
||||||
|
*/
|
||||||
|
readonly checkoutPullRequest: (input: {
|
||||||
|
readonly cwd: string;
|
||||||
|
readonly reference: string;
|
||||||
|
readonly force?: boolean;
|
||||||
|
}) => Effect.Effect<void, GitHubCliError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||||
|
*/
|
||||||
|
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||||
|
"t3/git/Services/GitHubCli",
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/**
|
||||||
|
* GitManager - Effect service contract for stacked Git workflows.
|
||||||
|
*
|
||||||
|
* Orchestrates status inspection and commit/push/PR flows by composing
|
||||||
|
* lower-level Git and external tool services.
|
||||||
|
*
|
||||||
|
* @module GitManager
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
GitActionProgressEvent,
|
||||||
|
GitPreparePullRequestThreadInput,
|
||||||
|
GitPreparePullRequestThreadResult,
|
||||||
|
GitPullRequestRefInput,
|
||||||
|
GitResolvePullRequestResult,
|
||||||
|
GitRunStackedActionInput,
|
||||||
|
GitRunStackedActionResult,
|
||||||
|
GitStatusLocalResult,
|
||||||
|
GitStatusRemoteResult,
|
||||||
|
GitStatusInput,
|
||||||
|
GitStatusResult,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
export interface GitManagerShape {
|
||||||
|
/**
|
||||||
|
* Read current repository Git status plus open PR metadata when available.
|
||||||
|
*/
|
||||||
|
readonly status: (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read local repository status without remote hosting enrichment.
|
||||||
|
*/
|
||||||
|
readonly localStatus: (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read remote tracking / PR status for a repository.
|
||||||
|
*/
|
||||||
|
readonly remoteStatus: (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear any cached local status snapshot for a repository.
|
||||||
|
*/
|
||||||
|
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear any cached remote status snapshot for a repository.
|
||||||
|
*/
|
||||||
|
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear any cached status snapshot for a repository so the next read is fresh.
|
||||||
|
*/
|
||||||
|
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a pull request by URL/number against the current repository.
|
||||||
|
*/
|
||||||
|
readonly resolvePullRequest: (
|
||||||
|
input: GitPullRequestRefInput,
|
||||||
|
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare a new thread workspace from a pull request in local or worktree mode.
|
||||||
|
*/
|
||||||
|
readonly preparePullRequestThread: (
|
||||||
|
input: GitPreparePullRequestThreadInput,
|
||||||
|
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
|
||||||
|
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||||
|
*/
|
||||||
|
readonly runStackedAction: (
|
||||||
|
input: GitRunStackedActionInput,
|
||||||
|
options?: GitRunStackedActionOptions,
|
||||||
|
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||||
|
*/
|
||||||
|
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||||
|
"t3/git/Services/GitManager",
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect, Stream } from "effect";
|
||||||
|
import type {
|
||||||
|
GitManagerServiceError,
|
||||||
|
GitStatusInput,
|
||||||
|
GitStatusLocalResult,
|
||||||
|
GitStatusResult,
|
||||||
|
GitStatusStreamEvent,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
|
||||||
|
export interface GitStatusBroadcasterShape {
|
||||||
|
readonly getStatus: (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||||
|
readonly refreshLocalStatus: (
|
||||||
|
cwd: string,
|
||||||
|
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||||
|
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||||
|
readonly streamStatus: (
|
||||||
|
input: GitStatusInput,
|
||||||
|
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitStatusBroadcaster extends Context.Service<
|
||||||
|
GitStatusBroadcaster,
|
||||||
|
GitStatusBroadcasterShape
|
||||||
|
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||||
+14
-62
@@ -1,13 +1,18 @@
|
|||||||
import { Context, Effect, Layer } from "effect";
|
/**
|
||||||
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
|
* TextGeneration - Effect service contract for AI-generated Git content.
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
*
|
||||||
|
* Generates commit messages and pull request titles/bodies from repository
|
||||||
|
* context prepared by Git services.
|
||||||
|
*
|
||||||
|
* @module TextGeneration
|
||||||
|
*/
|
||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||||
|
|
||||||
import {
|
import type { TextGenerationError } from "@t3tools/contracts";
|
||||||
ProviderInstanceRegistry,
|
|
||||||
type ProviderInstanceRegistryShape,
|
|
||||||
} from "../provider/Services/ProviderInstanceRegistry.ts";
|
|
||||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
|
||||||
|
|
||||||
|
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||||
|
|
||||||
export interface CommitMessageGenerationInput {
|
export interface CommitMessageGenerationInput {
|
||||||
@@ -114,58 +119,5 @@ export interface TextGenerationShape {
|
|||||||
* TextGeneration - Service tag for commit and PR text generation.
|
* TextGeneration - Service tag for commit and PR text generation.
|
||||||
*/
|
*/
|
||||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||||
"t3/text-generation/TextGeneration",
|
"t3/git/Services/TextGeneration",
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
type TextGenerationOp =
|
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
|
|
||||||
const resolveInstance = (
|
|
||||||
registry: ProviderInstanceRegistryShape,
|
|
||||||
operation: TextGenerationOp,
|
|
||||||
instanceId: ProviderInstanceId,
|
|
||||||
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
|
|
||||||
registry.getInstance(instanceId).pipe(
|
|
||||||
Effect.flatMap((instance) =>
|
|
||||||
instance
|
|
||||||
? Effect.succeed(instance.textGeneration)
|
|
||||||
: Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: `No provider instance registered for id '${instanceId}'.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const makeTextGenerationFromRegistry = (
|
|
||||||
registry: ProviderInstanceRegistryShape,
|
|
||||||
): TextGenerationShape => ({
|
|
||||||
generateCommitMessage: (input) =>
|
|
||||||
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
|
|
||||||
Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
|
|
||||||
),
|
|
||||||
generatePrContent: (input) =>
|
|
||||||
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
|
|
||||||
Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
|
|
||||||
),
|
|
||||||
generateBranchName: (input) =>
|
|
||||||
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
|
|
||||||
Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
|
|
||||||
),
|
|
||||||
generateThreadTitle: (input) =>
|
|
||||||
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
|
|
||||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const layer = Layer.effect(
|
|
||||||
TextGeneration,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const registry = yield* ProviderInstanceRegistry;
|
|
||||||
return makeTextGenerationFromRegistry(registry);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,6 +1,171 @@
|
|||||||
|
/**
|
||||||
|
* 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 { existsSync } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
|
||||||
export function isGitRepository(cwd: string): boolean {
|
export function isGitRepository(cwd: string): boolean {
|
||||||
return existsSync(join(cwd, ".git"));
|
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]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractJsonObject(raw: string): string {
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (trimmed.length === 0) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = trimmed.indexOf("{");
|
||||||
|
if (start < 0) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
let depth = 0;
|
||||||
|
let inString = false;
|
||||||
|
let escaping = false;
|
||||||
|
for (let index = start; index < trimmed.length; index += 1) {
|
||||||
|
const char = trimmed[index];
|
||||||
|
if (inString) {
|
||||||
|
if (escaping) {
|
||||||
|
escaping = false;
|
||||||
|
} else if (char === "\\") {
|
||||||
|
escaping = true;
|
||||||
|
} else if (char === '"') {
|
||||||
|
inString = false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char === '"') {
|
||||||
|
inString = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char === "{") {
|
||||||
|
depth += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char === "}") {
|
||||||
|
depth -= 1;
|
||||||
|
if (depth === 0) {
|
||||||
|
return trimmed.slice(start, index + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmed.slice(start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
});
|
||||||
|
}
|
||||||
+5
-4
@@ -1,4 +1,4 @@
|
|||||||
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
|
import { Cause, Exit, Result, Schema } from "effect";
|
||||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ export interface NormalizedGitHubPullRequestRecord {
|
|||||||
readonly baseRefName: string;
|
readonly baseRefName: string;
|
||||||
readonly headRefName: string;
|
readonly headRefName: string;
|
||||||
readonly state: "open" | "closed" | "merged";
|
readonly state: "open" | "closed" | "merged";
|
||||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
readonly updatedAt: string | null;
|
||||||
readonly isCrossRepository?: boolean;
|
readonly isCrossRepository?: boolean;
|
||||||
readonly headRepositoryNameWithOwner?: string | null;
|
readonly headRepositoryNameWithOwner?: string | null;
|
||||||
readonly headRepositoryOwnerLogin?: string | null;
|
readonly headRepositoryOwnerLogin?: string | null;
|
||||||
@@ -23,7 +23,7 @@ const GitHubPullRequestSchema = Schema.Struct({
|
|||||||
headRefName: TrimmedNonEmptyString,
|
headRefName: TrimmedNonEmptyString,
|
||||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||||
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||||
headRepository: Schema.optional(
|
headRepository: Schema.optional(
|
||||||
Schema.NullOr(
|
Schema.NullOr(
|
||||||
@@ -80,7 +80,8 @@ function normalizeGitHubPullRequestRecord(
|
|||||||
baseRefName: raw.baseRefName,
|
baseRefName: raw.baseRefName,
|
||||||
headRefName: raw.headRefName,
|
headRefName: raw.headRefName,
|
||||||
state: normalizeGitHubPullRequestState(raw),
|
state: normalizeGitHubPullRequestState(raw),
|
||||||
updatedAt: raw.updatedAt ?? Option.none(),
|
updatedAt:
|
||||||
|
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||||
...(typeof raw.isCrossRepository === "boolean"
|
...(typeof raw.isCrossRepository === "boolean"
|
||||||
? { isCrossRepository: raw.isCrossRepository }
|
? { isCrossRepository: raw.isCrossRepository }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
|||||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("appends additional custom keybindings for the same command", () =>
|
it.effect("replaces existing custom keybinding for the same command", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||||
@@ -368,55 +368,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
|
||||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
|
||||||
assert.deepEqual(persistedView, [
|
|
||||||
{ key: "mod+r", command: "script.run-tests.run" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("replaces only the targeted custom keybinding", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
|
||||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
|
||||||
{ key: "mod+r", command: "script.run-tests.run" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
yield* Effect.gen(function* () {
|
|
||||||
const keybindings = yield* Keybindings;
|
|
||||||
return yield* keybindings.upsertKeybindingRule({
|
|
||||||
key: "mod+alt+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
replace: { key: "mod+r", command: "script.run-tests.run" },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
|
||||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
|
||||||
assert.deepEqual(persistedView, [
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
{ key: "mod+alt+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("removes only the targeted custom keybinding", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
|
||||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
|
||||||
{ key: "mod+r", command: "script.run-tests.run" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
yield* Effect.gen(function* () {
|
|
||||||
const keybindings = yield* Keybindings;
|
|
||||||
return yield* keybindings.removeKeybindingRule({
|
|
||||||
key: "mod+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||||
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||||
|
|||||||
+280
-72
@@ -13,12 +13,14 @@ import {
|
|||||||
KeybindingShortcut,
|
KeybindingShortcut,
|
||||||
KeybindingWhenNode,
|
KeybindingWhenNode,
|
||||||
MAX_KEYBINDINGS_COUNT,
|
MAX_KEYBINDINGS_COUNT,
|
||||||
|
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
|
||||||
|
MAX_WHEN_EXPRESSION_DEPTH,
|
||||||
ResolvedKeybindingRule,
|
ResolvedKeybindingRule,
|
||||||
ResolvedKeybindingsConfig,
|
ResolvedKeybindingsConfig,
|
||||||
type ServerRemoveKeybindingInput,
|
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||||
type ServerUpsertKeybindingInput,
|
|
||||||
type ServerConfigIssue,
|
type ServerConfigIssue,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import type { Mutable } from "effect/Types";
|
||||||
import {
|
import {
|
||||||
Array,
|
Array,
|
||||||
Cache,
|
Cache,
|
||||||
@@ -46,20 +48,278 @@ import * as Semaphore from "effect/Semaphore";
|
|||||||
import { ServerConfig } from "./config.ts";
|
import { ServerConfig } from "./config.ts";
|
||||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||||
import {
|
|
||||||
DEFAULT_KEYBINDINGS,
|
|
||||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
|
||||||
compileResolvedKeybindingRule,
|
|
||||||
compileResolvedKeybindingsConfig,
|
|
||||||
parseKeybindingShortcut,
|
|
||||||
} from "@t3tools/shared/keybindings";
|
|
||||||
|
|
||||||
export {
|
type WhenToken =
|
||||||
DEFAULT_KEYBINDINGS,
|
| { type: "identifier"; value: string }
|
||||||
compileResolvedKeybindingRule,
|
| { type: "not" }
|
||||||
compileResolvedKeybindingsConfig,
|
| { type: "and" }
|
||||||
parseKeybindingShortcut,
|
| { type: "or" }
|
||||||
};
|
| { type: "lparen" }
|
||||||
|
| { type: "rparen" };
|
||||||
|
|
||||||
|
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||||
|
{ key: "mod+j", command: "terminal.toggle" },
|
||||||
|
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||||
|
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||||
|
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||||
|
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||||
|
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||||
|
{ key: "mod+n", 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+m", command: "modelPicker.toggle", when: "!terminalFocus" },
|
||||||
|
{ 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,
|
||||||
|
})),
|
||||||
|
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
|
||||||
|
key: `mod+${index + 1}`,
|
||||||
|
command,
|
||||||
|
when: "modelPickerOpen",
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
function normalizeKeyToken(token: string): string {
|
||||||
|
if (token === "space") return " ";
|
||||||
|
if (token === "esc") return "escape";
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal - Exported for testing */
|
||||||
|
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
||||||
|
const rawTokens = value
|
||||||
|
.toLowerCase()
|
||||||
|
.split("+")
|
||||||
|
.map((token) => token.trim());
|
||||||
|
const tokens = [...rawTokens];
|
||||||
|
let trailingEmptyCount = 0;
|
||||||
|
while (tokens[tokens.length - 1] === "") {
|
||||||
|
trailingEmptyCount += 1;
|
||||||
|
tokens.pop();
|
||||||
|
}
|
||||||
|
if (trailingEmptyCount > 0) {
|
||||||
|
tokens.push("+");
|
||||||
|
}
|
||||||
|
if (tokens.some((token) => token.length === 0)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (tokens.length === 0) return null;
|
||||||
|
|
||||||
|
let key: string | null = null;
|
||||||
|
let metaKey = false;
|
||||||
|
let ctrlKey = false;
|
||||||
|
let shiftKey = false;
|
||||||
|
let altKey = false;
|
||||||
|
let modKey = false;
|
||||||
|
|
||||||
|
for (const token of tokens) {
|
||||||
|
switch (token) {
|
||||||
|
case "cmd":
|
||||||
|
case "meta":
|
||||||
|
metaKey = true;
|
||||||
|
break;
|
||||||
|
case "ctrl":
|
||||||
|
case "control":
|
||||||
|
ctrlKey = true;
|
||||||
|
break;
|
||||||
|
case "shift":
|
||||||
|
shiftKey = true;
|
||||||
|
break;
|
||||||
|
case "alt":
|
||||||
|
case "option":
|
||||||
|
altKey = true;
|
||||||
|
break;
|
||||||
|
case "mod":
|
||||||
|
modKey = true;
|
||||||
|
break;
|
||||||
|
default: {
|
||||||
|
if (key !== null) return null;
|
||||||
|
key = normalizeKeyToken(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key === null) return null;
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
metaKey,
|
||||||
|
ctrlKey,
|
||||||
|
shiftKey,
|
||||||
|
altKey,
|
||||||
|
modKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
||||||
|
const tokens: WhenToken[] = [];
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
while (index < expression.length) {
|
||||||
|
const current = expression[index];
|
||||||
|
if (!current) break;
|
||||||
|
|
||||||
|
if (/\s/.test(current)) {
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (expression.startsWith("&&", index)) {
|
||||||
|
tokens.push({ type: "and" });
|
||||||
|
index += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (expression.startsWith("||", index)) {
|
||||||
|
tokens.push({ type: "or" });
|
||||||
|
index += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (current === "!") {
|
||||||
|
tokens.push({ type: "not" });
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (current === "(") {
|
||||||
|
tokens.push({ type: "lparen" });
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (current === ")") {
|
||||||
|
tokens.push({ type: "rparen" });
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
|
||||||
|
if (!identifier) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
tokens.push({ type: "identifier", value: identifier[0] });
|
||||||
|
index += identifier[0].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||||
|
const tokens = tokenizeWhenExpression(expression);
|
||||||
|
if (!tokens || tokens.length === 0) return null;
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
|
||||||
|
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const token = tokens[index];
|
||||||
|
if (!token) return null;
|
||||||
|
|
||||||
|
if (token.type === "identifier") {
|
||||||
|
index += 1;
|
||||||
|
return { type: "identifier", name: token.value };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.type === "lparen") {
|
||||||
|
index += 1;
|
||||||
|
const expressionNode = parseOr(depth + 1);
|
||||||
|
const closeToken = tokens[index];
|
||||||
|
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
return expressionNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseUnary = (depth: number): KeybindingWhenNode | null => {
|
||||||
|
let notCount = 0;
|
||||||
|
while (tokens[index]?.type === "not") {
|
||||||
|
index += 1;
|
||||||
|
notCount += 1;
|
||||||
|
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let node = parsePrimary(depth);
|
||||||
|
if (!node) return null;
|
||||||
|
|
||||||
|
while (notCount > 0) {
|
||||||
|
node = { type: "not", node };
|
||||||
|
notCount -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseAnd = (depth: number): KeybindingWhenNode | null => {
|
||||||
|
let left = parseUnary(depth);
|
||||||
|
if (!left) return null;
|
||||||
|
|
||||||
|
while (tokens[index]?.type === "and") {
|
||||||
|
index += 1;
|
||||||
|
const right = parseUnary(depth);
|
||||||
|
if (!right) return null;
|
||||||
|
left = { type: "and", left, right };
|
||||||
|
}
|
||||||
|
|
||||||
|
return left;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseOr = (depth: number): KeybindingWhenNode | null => {
|
||||||
|
let left = parseAnd(depth);
|
||||||
|
if (!left) return null;
|
||||||
|
|
||||||
|
while (tokens[index]?.type === "or") {
|
||||||
|
index += 1;
|
||||||
|
const right = parseAnd(depth);
|
||||||
|
if (!right) return null;
|
||||||
|
left = { type: "or", left, right };
|
||||||
|
}
|
||||||
|
|
||||||
|
return left;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ast = parseOr(0);
|
||||||
|
if (!ast || index !== tokens.length) return null;
|
||||||
|
return ast;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal - Exported for testing */
|
||||||
|
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
||||||
|
const shortcut = parseKeybindingShortcut(rule.key);
|
||||||
|
if (!shortcut) return null;
|
||||||
|
|
||||||
|
if (rule.when !== undefined) {
|
||||||
|
const whenAst = parseKeybindingWhenExpression(rule.when);
|
||||||
|
if (!whenAst) return null;
|
||||||
|
return {
|
||||||
|
command: rule.command,
|
||||||
|
shortcut,
|
||||||
|
whenAst,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
command: rule.command,
|
||||||
|
shortcut,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compileResolvedKeybindingsConfig(
|
||||||
|
config: KeybindingsConfig,
|
||||||
|
): ResolvedKeybindingsConfig {
|
||||||
|
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
|
||||||
|
for (const rule of config) {
|
||||||
|
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
|
||||||
|
if (result._tag === "Success") {
|
||||||
|
compiled.push(result.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||||
Schema.decodeTo(
|
Schema.decodeTo(
|
||||||
@@ -126,25 +386,6 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
|
|||||||
return leftContext === rightContext;
|
return leftContext === rightContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
|
|
||||||
return input.when === undefined
|
|
||||||
? { key: input.key, command: input.command }
|
|
||||||
: { key: input.key, command: input.command, when: input.when };
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
|
|
||||||
if (!input.replace) return null;
|
|
||||||
return input.replace.when === undefined
|
|
||||||
? { key: input.replace.key, command: input.replace.command }
|
|
||||||
: { key: input.replace.key, command: input.replace.command, when: input.replace.when };
|
|
||||||
}
|
|
||||||
|
|
||||||
function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
|
|
||||||
return input.when === undefined
|
|
||||||
? { key: input.key, command: input.command }
|
|
||||||
: { key: input.key, command: input.command, when: input.when };
|
|
||||||
}
|
|
||||||
|
|
||||||
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
||||||
const modifiers: string[] = [];
|
const modifiers: string[] = [];
|
||||||
if (shortcut.modKey) modifiers.push("mod");
|
if (shortcut.modKey) modifiers.push("mod");
|
||||||
@@ -171,6 +412,8 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||||
|
|
||||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
const RawKeybindingsEntries = fromLenientJson(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(
|
||||||
@@ -280,14 +523,7 @@ export interface KeybindingsShape {
|
|||||||
* oldest entries when needed.
|
* oldest entries when needed.
|
||||||
*/
|
*/
|
||||||
readonly upsertKeybindingRule: (
|
readonly upsertKeybindingRule: (
|
||||||
input: ServerUpsertKeybindingInput,
|
rule: KeybindingRule,
|
||||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove a single persisted keybinding rule by exact key/command/when match.
|
|
||||||
*/
|
|
||||||
readonly removeKeybindingRule: (
|
|
||||||
input: ServerRemoveKeybindingInput,
|
|
||||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -644,19 +880,12 @@ const makeKeybindings = Effect.gen(function* () {
|
|||||||
get streamChanges() {
|
get streamChanges() {
|
||||||
return Stream.fromPubSub(changesPubSub);
|
return Stream.fromPubSub(changesPubSub);
|
||||||
},
|
},
|
||||||
upsertKeybindingRule: (input) =>
|
upsertKeybindingRule: (rule) =>
|
||||||
upsertSemaphore.withPermits(1)(
|
upsertSemaphore.withPermits(1)(
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||||
const rule = keybindingRuleFromUpsertInput(input);
|
|
||||||
const replaceTarget = replaceTargetFromUpsertInput(input);
|
|
||||||
const nextConfig = [
|
const nextConfig = [
|
||||||
...customConfig.filter((entry) => {
|
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||||
if (replaceTarget) {
|
|
||||||
return !isSameKeybindingRule(entry, replaceTarget);
|
|
||||||
}
|
|
||||||
return !isSameKeybindingRule(entry, rule);
|
|
||||||
}),
|
|
||||||
rule,
|
rule,
|
||||||
];
|
];
|
||||||
const cappedConfig =
|
const cappedConfig =
|
||||||
@@ -684,27 +913,6 @@ const makeKeybindings = Effect.gen(function* () {
|
|||||||
return nextResolved;
|
return nextResolved;
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
removeKeybindingRule: (input) =>
|
|
||||||
upsertSemaphore.withPermits(1)(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
|
||||||
const target = keybindingRuleFromRemoveInput(input);
|
|
||||||
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
|
|
||||||
yield* writeConfigAtomically(nextConfig);
|
|
||||||
const nextResolved = mergeWithDefaultKeybindings(
|
|
||||||
compileResolvedKeybindingsConfig(nextConfig),
|
|
||||||
);
|
|
||||||
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
|
|
||||||
keybindings: nextResolved,
|
|
||||||
issues: [],
|
|
||||||
});
|
|
||||||
yield* emitChange({
|
|
||||||
keybindings: nextResolved,
|
|
||||||
issues: [],
|
|
||||||
});
|
|
||||||
return nextResolved;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
} satisfies KeybindingsShape;
|
} satisfies KeybindingsShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { assert, describe, it } from "@effect/vitest";
|
import { assert, describe, it } from "@effect/vitest";
|
||||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
|
||||||
import { Effect, Metric } from "effect";
|
import { Effect, Metric } from "effect";
|
||||||
|
|
||||||
import { withMetrics } from "./Metrics.ts";
|
import { withMetrics } from "./Metrics.ts";
|
||||||
@@ -76,11 +75,10 @@ describe("withMetrics", () => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const counter = Metric.counter("with_metrics_lazy_total");
|
const counter = Metric.counter("with_metrics_lazy_total");
|
||||||
const timer = Metric.timer("with_metrics_lazy_duration");
|
const timer = Metric.timer("with_metrics_lazy_duration");
|
||||||
let provider = ProviderDriverKind.make("unknown");
|
let provider = "unknown";
|
||||||
const lazyInittedProvider = ProviderDriverKind.make("codex");
|
|
||||||
|
|
||||||
yield* Effect.sync(() => {
|
yield* Effect.sync(() => {
|
||||||
provider = lazyInittedProvider;
|
provider = "codex";
|
||||||
}).pipe(
|
}).pipe(
|
||||||
withMetrics({
|
withMetrics({
|
||||||
counter,
|
counter,
|
||||||
@@ -95,7 +93,7 @@ describe("withMetrics", () => {
|
|||||||
const snapshots = yield* Metric.snapshot;
|
const snapshots = yield* Metric.snapshot;
|
||||||
assert.equal(
|
assert.equal(
|
||||||
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
|
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
|
||||||
provider: lazyInittedProvider,
|
provider: "codex",
|
||||||
operation: "lazy",
|
operation: "lazy",
|
||||||
outcome: "success",
|
outcome: "success",
|
||||||
}),
|
}),
|
||||||
@@ -103,7 +101,7 @@ describe("withMetrics", () => {
|
|||||||
);
|
);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
|
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
|
||||||
provider: lazyInittedProvider,
|
provider: "codex",
|
||||||
operation: "lazy",
|
operation: "lazy",
|
||||||
}),
|
}),
|
||||||
true,
|
true,
|
||||||
|
|||||||
@@ -3,12 +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 {
|
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||||
ProviderDriverKind,
|
|
||||||
ProviderRuntimeEvent,
|
|
||||||
ProviderSession,
|
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -24,9 +19,8 @@ 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 * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
|
||||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||||
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
||||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||||
@@ -41,7 +35,6 @@ import {
|
|||||||
type OrchestrationEngineShape,
|
type OrchestrationEngineShape,
|
||||||
} from "../Services/OrchestrationEngine.ts";
|
} from "../Services/OrchestrationEngine.ts";
|
||||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import {
|
import {
|
||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
@@ -57,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
|
|||||||
type LegacyProviderRuntimeEvent = {
|
type LegacyProviderRuntimeEvent = {
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
readonly eventId: EventId;
|
readonly eventId: EventId;
|
||||||
readonly provider: ProviderDriverKind;
|
readonly provider: ProviderKind;
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly turnId?: string | undefined;
|
readonly turnId?: string | undefined;
|
||||||
@@ -71,7 +64,7 @@ function createProviderServiceHarness(
|
|||||||
cwd: string,
|
cwd: string,
|
||||||
hasSession = true,
|
hasSession = true,
|
||||||
sessionCwd = cwd,
|
sessionCwd = cwd,
|
||||||
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
|
providerName: ProviderSession["provider"] = "codex",
|
||||||
) {
|
) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
@@ -104,17 +97,6 @@ function createProviderServiceHarness(
|
|||||||
stopSession: () => unsupported(),
|
stopSession: () => unsupported(),
|
||||||
listSessions,
|
listSessions,
|
||||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||||
getInstanceInfo: (instanceId) =>
|
|
||||||
Effect.succeed({
|
|
||||||
instanceId,
|
|
||||||
driverKind: ProviderDriverKind.make(providerName),
|
|
||||||
displayName: undefined,
|
|
||||||
enabled: true,
|
|
||||||
continuationIdentity: {
|
|
||||||
driverKind: ProviderDriverKind.make(providerName),
|
|
||||||
continuationKey: `${providerName}:instance:${instanceId}`,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
rollbackConversation,
|
rollbackConversation,
|
||||||
get streamEvents() {
|
get streamEvents() {
|
||||||
return Stream.fromPubSub(runtimeEventPubSub);
|
return Stream.fromPubSub(runtimeEventPubSub);
|
||||||
@@ -133,14 +115,7 @@ function createProviderServiceHarness(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function waitForThread(
|
async function waitForThread(
|
||||||
readModel: () => Promise<{
|
engine: OrchestrationEngineShape,
|
||||||
readonly threads: ReadonlyArray<{
|
|
||||||
readonly id: ThreadId;
|
|
||||||
readonly latestTurn: { readonly turnId: string } | null;
|
|
||||||
readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
|
|
||||||
readonly activities: ReadonlyArray<{ readonly kind: string }>;
|
|
||||||
}>;
|
|
||||||
}>,
|
|
||||||
predicate: (thread: {
|
predicate: (thread: {
|
||||||
latestTurn: { turnId: string } | null;
|
latestTurn: { turnId: string } | null;
|
||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
@@ -154,8 +129,8 @@ async function waitForThread(
|
|||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}> => {
|
}> => {
|
||||||
const snapshot = await readModel();
|
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
if (thread && predicate(thread)) {
|
if (thread && predicate(thread)) {
|
||||||
return thread;
|
return thread;
|
||||||
}
|
}
|
||||||
@@ -239,7 +214,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
|
|||||||
|
|
||||||
describe("CheckpointReactor", () => {
|
describe("CheckpointReactor", () => {
|
||||||
let runtime: ManagedRuntime.ManagedRuntime<
|
let runtime: ManagedRuntime.ManagedRuntime<
|
||||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
|
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
|
||||||
unknown
|
unknown
|
||||||
> | null = null;
|
> | null = null;
|
||||||
let scope: Scope.Closeable | null = null;
|
let scope: Scope.Closeable | null = null;
|
||||||
@@ -268,7 +243,7 @@ describe("CheckpointReactor", () => {
|
|||||||
readonly projectWorkspaceRoot?: string;
|
readonly projectWorkspaceRoot?: string;
|
||||||
readonly threadWorktreePath?: string | null;
|
readonly threadWorktreePath?: string | null;
|
||||||
readonly providerSessionCwd?: string;
|
readonly providerSessionCwd?: string;
|
||||||
readonly providerName?: ProviderDriverKind;
|
readonly providerName?: ProviderKind;
|
||||||
readonly gitStatusRefreshCalls?: Array<string>;
|
readonly gitStatusRefreshCalls?: Array<string>;
|
||||||
}) {
|
}) {
|
||||||
const cwd = createGitRepository();
|
const cwd = createGitRepository();
|
||||||
@@ -277,7 +252,7 @@ describe("CheckpointReactor", () => {
|
|||||||
cwd,
|
cwd,
|
||||||
options?.hasSession ?? true,
|
options?.hasSession ?? true,
|
||||||
options?.providerSessionCwd ?? cwd,
|
options?.providerSessionCwd ?? cwd,
|
||||||
options?.providerName ?? ProviderDriverKind.make("codex"),
|
options?.providerName ?? "codex",
|
||||||
);
|
);
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||||
@@ -287,15 +262,11 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provide(RepositoryIdentityResolverLive),
|
Layer.provide(RepositoryIdentityResolverLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
|
||||||
Layer.provide(RepositoryIdentityResolverLive),
|
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
|
||||||
);
|
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||||
prefix: "t3-checkpoint-reactor-test-",
|
prefix: "t3-checkpoint-reactor-test-",
|
||||||
});
|
});
|
||||||
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
|
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
|
||||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||||
refreshLocalStatus: (cwd: string) =>
|
refreshLocalStatus: (cwd: string) =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
@@ -303,9 +274,9 @@ describe("CheckpointReactor", () => {
|
|||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.as({
|
Effect.as({
|
||||||
isRepo: true,
|
isRepo: true,
|
||||||
hasPrimaryRemote: false,
|
hasOriginRemote: false,
|
||||||
isDefaultRef: true,
|
isDefaultBranch: true,
|
||||||
refName: "main",
|
branch: "main",
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||||
}),
|
}),
|
||||||
@@ -316,26 +287,19 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
const layer = CheckpointReactorLive.pipe(
|
const layer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(projectionSnapshotLayer),
|
|
||||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
Layer.provideMerge(gitStatusBroadcasterLayer),
|
||||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||||
WorkspaceEntriesLive.pipe(
|
|
||||||
Layer.provide(WorkspacePathsLive),
|
|
||||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(WorkspacePathsLive),
|
Layer.provideMerge(WorkspacePathsLive),
|
||||||
Layer.provideMerge(VcsProcess.layer),
|
Layer.provideMerge(GitCoreLive),
|
||||||
Layer.provideMerge(ServerConfigLayer),
|
Layer.provideMerge(ServerConfigLayer),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
|
||||||
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"));
|
||||||
@@ -351,7 +315,7 @@ describe("CheckpointReactor", () => {
|
|||||||
title: "Test Project",
|
title: "Test Project",
|
||||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -365,7 +329,7 @@ describe("CheckpointReactor", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -401,7 +365,6 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
engine,
|
engine,
|
||||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
|
||||||
provider,
|
provider,
|
||||||
cwd,
|
cwd,
|
||||||
drain,
|
drain,
|
||||||
@@ -433,7 +396,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
eventId: EventId.make("evt-turn-started-1"),
|
eventId: EventId.make("evt-turn-started-1"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -448,7 +411,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-1"),
|
eventId: EventId.make("evt-turn-completed-1"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -458,7 +421,7 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.readModel,
|
harness.engine,
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||||
);
|
);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
@@ -494,7 +457,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
|
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
turnId: asTurnId("turn-refresh-local-status"),
|
turnId: asTurnId("turn-refresh-local-status"),
|
||||||
@@ -531,7 +494,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
eventId: EventId.make("evt-turn-started-main"),
|
eventId: EventId.make("evt-turn-started-main"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -547,7 +510,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-aux"),
|
eventId: EventId.make("evt-turn-completed-aux"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -556,14 +519,14 @@ describe("CheckpointReactor", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await harness.drain();
|
await harness.drain();
|
||||||
const midReadModel = await harness.readModel();
|
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(midThread?.checkpoints).toHaveLength(0);
|
expect(midThread?.checkpoints).toHaveLength(0);
|
||||||
|
|
||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-main"),
|
eventId: EventId.make("evt-turn-completed-main"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -572,7 +535,7 @@ describe("CheckpointReactor", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.readModel,
|
harness.engine,
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||||
);
|
);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
@@ -581,7 +544,7 @@ describe("CheckpointReactor", () => {
|
|||||||
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
seedFilesystemCheckpoints: false,
|
seedFilesystemCheckpoints: false,
|
||||||
providerName: ProviderDriverKind.make("claudeAgent"),
|
providerName: "claudeAgent",
|
||||||
});
|
});
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
|
|
||||||
@@ -606,7 +569,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
eventId: EventId.make("evt-turn-started-claude-1"),
|
eventId: EventId.make("evt-turn-started-claude-1"),
|
||||||
provider: ProviderDriverKind.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
turnId: asTurnId("turn-claude-1"),
|
turnId: asTurnId("turn-claude-1"),
|
||||||
@@ -620,7 +583,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-claude-1"),
|
eventId: EventId.make("evt-turn-completed-claude-1"),
|
||||||
provider: ProviderDriverKind.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
turnId: asTurnId("turn-claude-1"),
|
turnId: asTurnId("turn-claude-1"),
|
||||||
@@ -629,7 +592,7 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.readModel,
|
harness.engine,
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -664,7 +627,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-missing-baseline"),
|
eventId: EventId.make("evt-turn-completed-missing-baseline"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -674,7 +637,7 @@ describe("CheckpointReactor", () => {
|
|||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.readModel,
|
harness.engine,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
entry.checkpoints.length === 1 &&
|
entry.checkpoints.length === 1 &&
|
||||||
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||||
@@ -753,7 +716,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
|
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -799,7 +762,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "checkpoint.captured",
|
type: "checkpoint.captured",
|
||||||
eventId: EventId.make("evt-checkpoint-captured-3"),
|
eventId: EventId.make("evt-checkpoint-captured-3"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -809,7 +772,7 @@ describe("CheckpointReactor", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await harness.drain();
|
await harness.drain();
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||||
false,
|
false,
|
||||||
@@ -849,7 +812,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.make("evt-runtime-capture-failure"),
|
eventId: EventId.make("evt-runtime-capture-failure"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -860,7 +823,7 @@ describe("CheckpointReactor", () => {
|
|||||||
harness.provider.emit({
|
harness.provider.emit({
|
||||||
type: "turn.started",
|
type: "turn.started",
|
||||||
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
|
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
@@ -938,10 +901,7 @@ describe("CheckpointReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||||
harness.readModel,
|
|
||||||
(entry) => entry.checkpoints.length === 1,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||||
expect(thread.checkpoints).toHaveLength(1);
|
expect(thread.checkpoints).toHaveLength(1);
|
||||||
@@ -958,7 +918,7 @@ describe("CheckpointReactor", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
||||||
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
|
const harness = await createHarness({ providerName: "claudeAgent" });
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
|
|
||||||
await Effect.runPromise(
|
await Effect.runPromise(
|
||||||
@@ -1123,7 +1083,7 @@ describe("CheckpointReactor", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
const thread = await waitForThread(harness.engine, (entry) =>
|
||||||
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
|
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -20,12 +20,11 @@ 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";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||||
import { isGitRepository } from "../../git/Utils.ts";
|
import { isGitRepository } from "../../git/Utils.ts";
|
||||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||||
|
|
||||||
type ReactorInput =
|
type ReactorInput =
|
||||||
@@ -67,12 +66,11 @@ const serverCommandId = (tag: string): CommandId =>
|
|||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
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 workspaceEntries = yield* WorkspaceEntries;
|
||||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||||
|
|
||||||
const appendRevertFailureActivity = (input: {
|
const appendRevertFailureActivity = (input: {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
@@ -126,26 +124,29 @@ const make = Effect.gen(function* () {
|
|||||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
||||||
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
|
|
||||||
const sessions = yield* providerService.listSessions();
|
const sessions = yield* providerService.listSessions();
|
||||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
|
||||||
return session?.cwd
|
|
||||||
? Option.some({ threadId: session.threadId, cwd: session.cwd })
|
|
||||||
: Option.none();
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
const findSessionWithCwd = (
|
||||||
return yield* projectionSnapshotQuery
|
session: (typeof sessions)[number] | undefined,
|
||||||
.getThreadDetailById(threadId)
|
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
if (!session?.cwd) {
|
||||||
});
|
return Option.none();
|
||||||
|
}
|
||||||
|
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||||
|
};
|
||||||
|
|
||||||
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
|
if (thread) {
|
||||||
projectId: ProjectId,
|
const projectedSession = sessions.find((session) => session.threadId === thread.id);
|
||||||
) {
|
const fromProjected = findSessionWithCwd(projectedSession);
|
||||||
const project = yield* projectionSnapshotQuery
|
if (Option.isSome(fromProjected)) {
|
||||||
.getProjectShellById(projectId)
|
return fromProjected;
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
}
|
||||||
return project ? [project] : [];
|
}
|
||||||
|
|
||||||
|
return Option.none();
|
||||||
});
|
});
|
||||||
|
|
||||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||||
@@ -236,7 +237,6 @@ const make = Effect.gen(function* () {
|
|||||||
fromCheckpointRef,
|
fromCheckpointRef,
|
||||||
toCheckpointRef: targetCheckpointRef,
|
toCheckpointRef: targetCheckpointRef,
|
||||||
fallbackFromToHead: false,
|
fallbackFromToHead: false,
|
||||||
ignoreWhitespace: false,
|
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.map((diff) =>
|
Effect.map((diff) =>
|
||||||
@@ -330,7 +330,8 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const thread = yield* resolveThreadDetail(event.threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -351,11 +352,10 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
|
||||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
thread,
|
thread,
|
||||||
projects,
|
projects: readModel.projects,
|
||||||
preferSessionRuntime: true,
|
preferSessionRuntime: true,
|
||||||
});
|
});
|
||||||
if (!checkpointCwd) {
|
if (!checkpointCwd) {
|
||||||
@@ -406,7 +406,8 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const thread = yield* resolveThreadDetail(threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
||||||
threadId,
|
threadId,
|
||||||
@@ -427,11 +428,10 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
|
||||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||||
threadId,
|
threadId,
|
||||||
thread,
|
thread,
|
||||||
projects,
|
projects: readModel.projects,
|
||||||
preferSessionRuntime: true,
|
preferSessionRuntime: true,
|
||||||
});
|
});
|
||||||
if (!checkpointCwd) {
|
if (!checkpointCwd) {
|
||||||
@@ -457,16 +457,16 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const thread = yield* resolveThreadDetail(event.threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
|
||||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
thread,
|
thread,
|
||||||
projects,
|
projects: readModel.projects,
|
||||||
preferSessionRuntime: false,
|
preferSessionRuntime: false,
|
||||||
});
|
});
|
||||||
if (!checkpointCwd) {
|
if (!checkpointCwd) {
|
||||||
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||||
Effect.catch((error) =>
|
Effect.catch((error) =>
|
||||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||||
threadId: event.threadId,
|
threadId: event.threadId,
|
||||||
@@ -539,16 +539,16 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const threadId = event.payload.threadId;
|
const threadId = event.payload.threadId;
|
||||||
const thread = yield* resolveThreadDetail(threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
|
||||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||||
threadId,
|
threadId,
|
||||||
thread,
|
thread,
|
||||||
projects,
|
projects: readModel.projects,
|
||||||
preferSessionRuntime: false,
|
preferSessionRuntime: false,
|
||||||
});
|
});
|
||||||
if (!checkpointCwd) {
|
if (!checkpointCwd) {
|
||||||
@@ -586,7 +586,8 @@ const make = Effect.gen(function* () {
|
|||||||
) {
|
) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
const thread = yield* resolveThreadDetail(event.payload.threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
yield* appendRevertFailureActivity({
|
yield* appendRevertFailureActivity({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
ProviderInstanceId,
|
|
||||||
type OrchestrationReadModel,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
@@ -43,13 +41,9 @@ async function createOrchestrationSystem() {
|
|||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||||
prefix: "t3-orchestration-engine-test-",
|
prefix: "t3-orchestration-engine-test-",
|
||||||
});
|
});
|
||||||
const orchestrationLayer = Layer.mergeAll(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
OrchestrationEngineLive.pipe(
|
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
|
||||||
),
|
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
|
||||||
).pipe(
|
|
||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(RepositoryIdentityResolverLive),
|
Layer.provide(RepositoryIdentityResolverLive),
|
||||||
@@ -59,10 +53,8 @@ async function createOrchestrationSystem() {
|
|||||||
);
|
);
|
||||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
|
||||||
return {
|
return {
|
||||||
engine,
|
engine,
|
||||||
readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
|
|
||||||
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
||||||
dispose: () => runtime.dispose(),
|
dispose: () => runtime.dispose(),
|
||||||
};
|
};
|
||||||
@@ -84,18 +76,15 @@ const hasMetricSnapshot = (
|
|||||||
);
|
);
|
||||||
|
|
||||||
describe("OrchestrationEngine", () => {
|
describe("OrchestrationEngine", () => {
|
||||||
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
|
it("bootstraps the in-memory read model from persisted projections", async () => {
|
||||||
let nextSequence = 8;
|
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
|
||||||
const eventStore: OrchestrationEventStoreShape = {
|
append: () =>
|
||||||
append: (event) =>
|
Effect.fail(
|
||||||
Effect.sync(() => {
|
new PersistenceSqlError({
|
||||||
const savedEvent = {
|
operation: "test.append",
|
||||||
...event,
|
detail: "append should not be called during bootstrap",
|
||||||
sequence: nextSequence,
|
}),
|
||||||
} as OrchestrationEvent;
|
),
|
||||||
nextSequence += 1;
|
|
||||||
return savedEvent;
|
|
||||||
}),
|
|
||||||
readFromSequence: () => Stream.empty,
|
readFromSequence: () => Stream.empty,
|
||||||
readAll: () =>
|
readAll: () =>
|
||||||
Stream.fail(
|
Stream.fail(
|
||||||
@@ -115,7 +104,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Bootstrap Project",
|
title: "Bootstrap Project",
|
||||||
workspaceRoot: "/tmp/project-bootstrap",
|
workspaceRoot: "/tmp/project-bootstrap",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex" as const,
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
scripts: [],
|
scripts: [],
|
||||||
@@ -130,7 +119,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-bootstrap"),
|
projectId: asProjectId("project-bootstrap"),
|
||||||
title: "Bootstrap Thread",
|
title: "Bootstrap Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex" as const,
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -150,27 +139,11 @@ describe("OrchestrationEngine", () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const commandReadModel = {
|
|
||||||
...projectionSnapshot,
|
|
||||||
threads: projectionSnapshot.threads.map((thread) => ({
|
|
||||||
...thread,
|
|
||||||
messages: [],
|
|
||||||
proposedPlans: [],
|
|
||||||
activities: [],
|
|
||||||
checkpoints: [],
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
let fullSnapshotReadCount = 0;
|
|
||||||
|
|
||||||
const layer = OrchestrationEngineLive.pipe(
|
const layer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getCommandReadModel: () => Effect.succeed(commandReadModel),
|
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||||
getSnapshot: () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
fullSnapshotReadCount += 1;
|
|
||||||
return projectionSnapshot;
|
|
||||||
}),
|
|
||||||
getShellSnapshot: () =>
|
getShellSnapshot: () =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||||
@@ -178,8 +151,6 @@ describe("OrchestrationEngine", () => {
|
|||||||
threads: [],
|
threads: [],
|
||||||
updatedAt: projectionSnapshot.updatedAt,
|
updatedAt: projectionSnapshot.updatedAt,
|
||||||
}),
|
}),
|
||||||
getSnapshotSequence: () =>
|
|
||||||
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
|
|
||||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||||
@@ -195,7 +166,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectEvent: () => Effect.void,
|
projectEvent: () => Effect.void,
|
||||||
} satisfies OrchestrationProjectionPipelineShape),
|
} satisfies OrchestrationProjectionPipelineShape),
|
||||||
),
|
),
|
||||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
@@ -203,22 +174,18 @@ describe("OrchestrationEngine", () => {
|
|||||||
const runtime = ManagedRuntime.make(layer);
|
const runtime = ManagedRuntime.make(layer);
|
||||||
|
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const result = await runtime.runPromise(
|
const readModel = await runtime.runPromise(engine.getReadModel());
|
||||||
engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.make("cmd-bootstrap-thread-update"),
|
|
||||||
threadId: ThreadId.make("thread-bootstrap"),
|
|
||||||
title: "Updated Bootstrap Thread",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result.sequence).toBe(8);
|
expect(readModel.snapshotSequence).toBe(7);
|
||||||
expect(fullSnapshotReadCount).toBe(0);
|
expect(readModel.projects).toHaveLength(1);
|
||||||
|
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
|
||||||
|
expect(readModel.threads).toHaveLength(1);
|
||||||
|
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
|
||||||
|
|
||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("persists deterministic read models for repeated snapshot reads", async () => {
|
it("returns deterministic read models for repeated reads", async () => {
|
||||||
const createdAt = now();
|
const createdAt = now();
|
||||||
const system = await createOrchestrationSystem();
|
const system = await createOrchestrationSystem();
|
||||||
const { engine } = system;
|
const { engine } = system;
|
||||||
@@ -231,7 +198,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Project 1",
|
title: "Project 1",
|
||||||
workspaceRoot: "/tmp/project-1",
|
workspaceRoot: "/tmp/project-1",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -245,7 +212,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -272,8 +239,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const readModelA = await system.readModel();
|
const readModelA = await system.run(engine.getReadModel());
|
||||||
const readModelB = await system.readModel();
|
const readModelB = await system.run(engine.getReadModel());
|
||||||
expect(readModelB).toEqual(readModelA);
|
expect(readModelB).toEqual(readModelA);
|
||||||
await system.dispose();
|
await system.dispose();
|
||||||
});
|
});
|
||||||
@@ -291,7 +258,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Project Archive",
|
title: "Project Archive",
|
||||||
workspaceRoot: "/tmp/project-archive",
|
workspaceRoot: "/tmp/project-archive",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -305,7 +272,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-archive"),
|
projectId: asProjectId("project-archive"),
|
||||||
title: "Archive me",
|
title: "Archive me",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -324,8 +291,9 @@ describe("OrchestrationEngine", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
(await system.run(engine.getReadModel())).threads.find(
|
||||||
?.archivedAt,
|
(thread) => thread.id === "thread-archive",
|
||||||
|
)?.archivedAt,
|
||||||
).not.toBeNull();
|
).not.toBeNull();
|
||||||
|
|
||||||
await system.run(
|
await system.run(
|
||||||
@@ -336,8 +304,9 @@ describe("OrchestrationEngine", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
(await system.run(engine.getReadModel())).threads.find(
|
||||||
?.archivedAt,
|
(thread) => thread.id === "thread-archive",
|
||||||
|
)?.archivedAt,
|
||||||
).toBeNull();
|
).toBeNull();
|
||||||
|
|
||||||
await system.dispose();
|
await system.dispose();
|
||||||
@@ -356,7 +325,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Replay Project",
|
title: "Replay Project",
|
||||||
workspaceRoot: "/tmp/project-replay",
|
workspaceRoot: "/tmp/project-replay",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -370,7 +339,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-replay"),
|
projectId: asProjectId("project-replay"),
|
||||||
title: "replay",
|
title: "replay",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -414,7 +383,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Stream Project",
|
title: "Stream Project",
|
||||||
workspaceRoot: "/tmp/project-stream",
|
workspaceRoot: "/tmp/project-stream",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -438,7 +407,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-stream"),
|
projectId: asProjectId("project-stream"),
|
||||||
title: "domain-stream",
|
title: "domain-stream",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -475,7 +444,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Ack Project",
|
title: "Ack Project",
|
||||||
workspaceRoot: "/tmp/project-ack",
|
workspaceRoot: "/tmp/project-ack",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -490,7 +459,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-ack"),
|
projectId: asProjectId("project-ack"),
|
||||||
title: "Ack Thread",
|
title: "Ack Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -527,7 +496,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-missing"),
|
projectId: asProjectId("project-missing"),
|
||||||
title: "Missing Project Thread",
|
title: "Missing Project Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -564,7 +533,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Turn Diff Project",
|
title: "Turn Diff Project",
|
||||||
workspaceRoot: "/tmp/project-turn-diff",
|
workspaceRoot: "/tmp/project-turn-diff",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -578,7 +547,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-turn-diff"),
|
projectId: asProjectId("project-turn-diff"),
|
||||||
title: "Turn diff thread",
|
title: "Turn diff thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -603,7 +572,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const thread = (await system.readModel()).threads.find(
|
const thread = (await system.run(engine.getReadModel())).threads.find(
|
||||||
(entry) => entry.id === "thread-turn-diff",
|
(entry) => entry.id === "thread-turn-diff",
|
||||||
);
|
);
|
||||||
expect(thread?.checkpoints).toEqual([
|
expect(thread?.checkpoints).toEqual([
|
||||||
@@ -683,7 +652,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Flaky Project",
|
title: "Flaky Project",
|
||||||
workspaceRoot: "/tmp/project-flaky",
|
workspaceRoot: "/tmp/project-flaky",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -699,7 +668,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-flaky"),
|
projectId: asProjectId("project-flaky"),
|
||||||
title: "flaky-fail",
|
title: "flaky-fail",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -719,7 +688,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-flaky"),
|
projectId: asProjectId("project-flaky"),
|
||||||
title: "flaky-ok",
|
title: "flaky-ok",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -731,15 +700,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result.sequence).toBe(2);
|
expect(result.sequence).toBe(2);
|
||||||
const eventsAfterRetry = await runtime.runPromise(
|
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
|
||||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
|
|
||||||
"project.created",
|
|
||||||
"thread.created",
|
|
||||||
]);
|
|
||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -786,7 +747,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Atomic Project",
|
title: "Atomic Project",
|
||||||
workspaceRoot: "/tmp/project-atomic",
|
workspaceRoot: "/tmp/project-atomic",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -800,7 +761,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-atomic"),
|
projectId: asProjectId("project-atomic"),
|
||||||
title: "atomic",
|
title: "atomic",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -839,6 +800,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
"project.created",
|
"project.created",
|
||||||
"thread.created",
|
"thread.created",
|
||||||
]);
|
]);
|
||||||
|
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||||
|
|
||||||
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
||||||
expect(retryResult.sequence).toBe(4);
|
expect(retryResult.sequence).toBe(4);
|
||||||
@@ -861,7 +823,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reconciles command state when append persists but projection fails", async () => {
|
it("reconciles in-memory state when append persists but projection fails", async () => {
|
||||||
type StoredEvent =
|
type StoredEvent =
|
||||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||||
? A
|
? A
|
||||||
@@ -893,7 +855,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectEvent: (event) => {
|
projectEvent: (event) => {
|
||||||
if (
|
if (
|
||||||
shouldFailProjection &&
|
shouldFailProjection &&
|
||||||
event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
|
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||||
) {
|
) {
|
||||||
shouldFailProjection = false;
|
shouldFailProjection = false;
|
||||||
return Effect.fail(
|
return Effect.fail(
|
||||||
@@ -928,7 +890,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Sync Project",
|
title: "Sync Project",
|
||||||
workspaceRoot: "/tmp/project-sync",
|
workspaceRoot: "/tmp/project-sync",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -942,7 +904,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-sync"),
|
projectId: asProjectId("project-sync"),
|
||||||
title: "sync-before",
|
title: "sync-before",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -956,22 +918,20 @@ describe("OrchestrationEngine", () => {
|
|||||||
await expect(
|
await expect(
|
||||||
runtime.runPromise(
|
runtime.runPromise(
|
||||||
engine.dispatch({
|
engine.dispatch({
|
||||||
type: "thread.archive",
|
type: "thread.meta.update",
|
||||||
commandId: CommandId.make("cmd-thread-archive-sync-fail"),
|
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||||
threadId: ThreadId.make("thread-sync"),
|
threadId: ThreadId.make("thread-sync"),
|
||||||
|
title: "sync-after-failed-projection",
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
).rejects.toThrow("projection failed");
|
).rejects.toThrow("projection failed");
|
||||||
|
|
||||||
await expect(
|
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
|
||||||
runtime.runPromise(
|
const updatedThread = readModelAfterFailure.threads.find(
|
||||||
engine.dispatch({
|
(thread) => thread.id === "thread-sync",
|
||||||
type: "thread.archive",
|
);
|
||||||
commandId: CommandId.make("cmd-thread-archive-sync-retry"),
|
expect(readModelAfterFailure.snapshotSequence).toBe(3);
|
||||||
threadId: ThreadId.make("thread-sync"),
|
expect(updatedThread?.title).toBe("sync-after-failed-projection");
|
||||||
}),
|
|
||||||
),
|
|
||||||
).rejects.toThrow("already archived");
|
|
||||||
|
|
||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
});
|
});
|
||||||
@@ -1015,7 +975,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
title: "Duplicate Project",
|
title: "Duplicate Project",
|
||||||
workspaceRoot: "/tmp/project-duplicate",
|
workspaceRoot: "/tmp/project-duplicate",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -1030,7 +990,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-duplicate"),
|
projectId: asProjectId("project-duplicate"),
|
||||||
title: "duplicate",
|
title: "duplicate",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -1050,7 +1010,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
projectId: asProjectId("project-duplicate"),
|
projectId: asProjectId("project-duplicate"),
|
||||||
title: "duplicate",
|
title: "duplicate",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ import {
|
|||||||
OrchestrationCommandInvariantError,
|
OrchestrationCommandInvariantError,
|
||||||
OrchestrationCommandPreviouslyRejectedError,
|
OrchestrationCommandPreviouslyRejectedError,
|
||||||
type OrchestrationDispatchError,
|
type OrchestrationDispatchError,
|
||||||
type OrchestrationProjectorDecodeError,
|
|
||||||
} from "../Errors.ts";
|
} from "../Errors.ts";
|
||||||
import { decideOrchestrationCommand } from "../decider.ts";
|
import { decideOrchestrationCommand } from "../decider.ts";
|
||||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||||
@@ -78,25 +77,13 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
|
|
||||||
let commandReadModel = createEmptyReadModel(new Date().toISOString());
|
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||||
|
|
||||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||||
|
|
||||||
const projectEventsOntoReadModel = (
|
|
||||||
baseReadModel: OrchestrationReadModel,
|
|
||||||
events: ReadonlyArray<OrchestrationEvent>,
|
|
||||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
let nextReadModel = baseReadModel;
|
|
||||||
for (const event of events) {
|
|
||||||
nextReadModel = yield* projectEvent(nextReadModel, event);
|
|
||||||
}
|
|
||||||
return nextReadModel;
|
|
||||||
});
|
|
||||||
|
|
||||||
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
|
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
|
||||||
const dispatchStartSequence = commandReadModel.snapshotSequence;
|
const dispatchStartSequence = readModel.snapshotSequence;
|
||||||
const processingStartedAtMs = Date.now();
|
const processingStartedAtMs = Date.now();
|
||||||
const aggregateRef = commandToAggregateRef(envelope.command);
|
const aggregateRef = commandToAggregateRef(envelope.command);
|
||||||
const baseMetricAttributes = {
|
const baseMetricAttributes = {
|
||||||
@@ -111,7 +98,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
|
let nextReadModel = readModel;
|
||||||
|
for (const persistedEvent of persistedEvents) {
|
||||||
|
nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
|
||||||
|
}
|
||||||
|
readModel = nextReadModel;
|
||||||
|
|
||||||
for (const persistedEvent of persistedEvents) {
|
for (const persistedEvent of persistedEvents) {
|
||||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||||
@@ -144,18 +135,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
|
|
||||||
const eventBase = yield* decideOrchestrationCommand({
|
const eventBase = yield* decideOrchestrationCommand({
|
||||||
command: envelope.command,
|
command: envelope.command,
|
||||||
readModel: commandReadModel,
|
readModel,
|
||||||
});
|
});
|
||||||
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
||||||
const committedCommand = yield* sql
|
const committedCommand = yield* sql
|
||||||
.withTransaction(
|
.withTransaction(
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const committedEvents: OrchestrationEvent[] = [];
|
const committedEvents: OrchestrationEvent[] = [];
|
||||||
let nextCommandReadModel = commandReadModel;
|
let nextReadModel = readModel;
|
||||||
|
|
||||||
for (const nextEvent of eventBases) {
|
for (const nextEvent of eventBases) {
|
||||||
const savedEvent = yield* eventStore.append(nextEvent);
|
const savedEvent = yield* eventStore.append(nextEvent);
|
||||||
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
|
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
|
||||||
yield* projectionPipeline.projectEvent(savedEvent);
|
yield* projectionPipeline.projectEvent(savedEvent);
|
||||||
committedEvents.push(savedEvent);
|
committedEvents.push(savedEvent);
|
||||||
}
|
}
|
||||||
@@ -181,7 +172,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
return {
|
return {
|
||||||
committedEvents,
|
committedEvents,
|
||||||
lastSequence: lastSavedEvent.sequence,
|
lastSequence: lastSavedEvent.sequence,
|
||||||
nextCommandReadModel,
|
nextReadModel,
|
||||||
} as const;
|
} as const;
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -193,7 +184,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
commandReadModel = committedCommand.nextCommandReadModel;
|
readModel = committedCommand.nextReadModel;
|
||||||
for (const [index, event] of committedCommand.committedEvents.entries()) {
|
for (const [index, event] of committedCommand.committedEvents.entries()) {
|
||||||
yield* PubSub.publish(eventPubSub, event);
|
yield* PubSub.publish(eventPubSub, event);
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
@@ -251,7 +242,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
).pipe(
|
).pipe(
|
||||||
Effect.annotateLogs({
|
Effect.annotateLogs({
|
||||||
commandId: envelope.command.commandId,
|
commandId: envelope.command.commandId,
|
||||||
snapshotSequence: commandReadModel.snapshotSequence,
|
snapshotSequence: readModel.snapshotSequence,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -264,7 +255,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
aggregateKind: aggregateRef.aggregateKind,
|
aggregateKind: aggregateRef.aggregateKind,
|
||||||
aggregateId: aggregateRef.aggregateId,
|
aggregateId: aggregateRef.aggregateId,
|
||||||
acceptedAt: new Date().toISOString(),
|
acceptedAt: new Date().toISOString(),
|
||||||
resultSequence: commandReadModel.snapshotSequence,
|
resultSequence: readModel.snapshotSequence,
|
||||||
status: "rejected",
|
status: "rejected",
|
||||||
error: error.message,
|
error: error.message,
|
||||||
})
|
})
|
||||||
@@ -279,14 +270,17 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
yield* projectionPipeline.bootstrap;
|
yield* projectionPipeline.bootstrap;
|
||||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||||
|
|
||||||
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.logDebug("orchestration engine started").pipe(
|
||||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
|
||||||
|
Effect.sync((): OrchestrationReadModel => readModel);
|
||||||
|
|
||||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
||||||
eventStore.readFromSequence(fromSequenceExclusive);
|
eventStore.readFromSequence(fromSequenceExclusive);
|
||||||
|
|
||||||
@@ -298,6 +292,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
getReadModel,
|
||||||
readEvents,
|
readEvents,
|
||||||
dispatch,
|
dispatch,
|
||||||
// Each access creates a fresh PubSub subscription so that multiple
|
// Each access creates a fresh PubSub subscription so that multiple
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
@@ -93,7 +92,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-1"),
|
projectId: ProjectId.make("project-1"),
|
||||||
title: "Thread 1",
|
title: "Thread 1",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -365,7 +364,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-clear-attachments"),
|
projectId: ProjectId.make("project-clear-attachments"),
|
||||||
title: "Thread Clear Attachments",
|
title: "Thread Clear Attachments",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -493,7 +492,7 @@ it.layer(
|
|||||||
projectId: ProjectId.make("project-overwrite"),
|
projectId: ProjectId.make("project-overwrite"),
|
||||||
title: "Thread Overwrite",
|
title: "Thread Overwrite",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -641,7 +640,7 @@ it.layer(
|
|||||||
projectId: ProjectId.make("project-rollback"),
|
projectId: ProjectId.make("project-rollback"),
|
||||||
title: "Thread Rollback",
|
title: "Thread Rollback",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -770,7 +769,7 @@ it.layer(
|
|||||||
projectId: ProjectId.make("project-revert-files"),
|
projectId: ProjectId.make("project-revert-files"),
|
||||||
title: "Thread Revert Files",
|
title: "Thread Revert Files",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -978,7 +977,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
|||||||
projectId: ProjectId.make("project-delete-files"),
|
projectId: ProjectId.make("project-delete-files"),
|
||||||
title: "Thread Delete Files",
|
title: "Thread Delete Files",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -1141,7 +1140,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-a"),
|
projectId: ProjectId.make("project-a"),
|
||||||
title: "Thread A",
|
title: "Thread A",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -1268,7 +1267,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-empty"),
|
projectId: ProjectId.make("project-empty"),
|
||||||
title: "Thread Empty",
|
title: "Thread Empty",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -1408,7 +1407,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-conflict"),
|
projectId: ProjectId.make("project-conflict"),
|
||||||
title: "Thread Conflict",
|
title: "Thread Conflict",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -1552,7 +1551,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-stale-approval"),
|
projectId: ProjectId.make("project-stale-approval"),
|
||||||
title: "Thread Stale Approval",
|
title: "Thread Stale Approval",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
@@ -1695,7 +1694,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-nonstale-approval"),
|
projectId: ProjectId.make("project-nonstale-approval"),
|
||||||
title: "Thread Non-Stale Approval",
|
title: "Thread Non-Stale Approval",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
@@ -1875,7 +1874,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
|||||||
projectId: ProjectId.make("project-revert"),
|
projectId: ProjectId.make("project-revert"),
|
||||||
title: "Thread Revert",
|
title: "Thread Revert",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -2196,7 +2195,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
|||||||
title: "Live Project",
|
title: "Live Project",
|
||||||
workspaceRoot: "/tmp/project-live",
|
workspaceRoot: "/tmp/project-live",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -2234,7 +2233,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
|||||||
title: "Scripts Project",
|
title: "Scripts Project",
|
||||||
workspaceRoot: "/tmp/project-scripts",
|
workspaceRoot: "/tmp/project-scripts",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -2254,7 +2253,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5",
|
model: "gpt-5",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -2273,7 +2272,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
|||||||
{
|
{
|
||||||
scriptsJson:
|
scriptsJson:
|
||||||
'[{"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}]',
|
||||||
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
|
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -739,31 +739,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
if (Option.isNone(existingRow)) {
|
if (Option.isNone(existingRow)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const retainedTurns = yield* projectionTurnRepository.listByThreadId({
|
|
||||||
threadId: event.payload.threadId,
|
|
||||||
});
|
|
||||||
let latestTurnId: ProjectionTurn["turnId"] = null;
|
|
||||||
let latestCheckpointTurnCount = -1;
|
|
||||||
for (let index = 0; index < retainedTurns.length; index += 1) {
|
|
||||||
const turn = retainedTurns[index];
|
|
||||||
if (
|
|
||||||
!turn ||
|
|
||||||
turn.turnId === null ||
|
|
||||||
turn.checkpointTurnCount === null ||
|
|
||||||
turn.checkpointTurnCount > event.payload.turnCount
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
|
|
||||||
latestCheckpointTurnCount = turn.checkpointTurnCount;
|
|
||||||
latestTurnId = turn.turnId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* projectionThreadRepository.upsert({
|
yield* projectionThreadRepository.upsert({
|
||||||
...existingRow.value,
|
...existingRow.value,
|
||||||
latestTurnId,
|
latestTurnId: null,
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
});
|
});
|
||||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||||
@@ -967,7 +945,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
status: event.payload.session.status,
|
status: event.payload.session.status,
|
||||||
providerName: event.payload.session.providerName,
|
providerName: event.payload.session.providerName,
|
||||||
providerInstanceId: event.payload.session.providerInstanceId ?? null,
|
|
||||||
runtimeMode: event.payload.session.runtimeMode,
|
runtimeMode: event.payload.session.runtimeMode,
|
||||||
activeTurnId: event.payload.session.activeTurnId,
|
activeTurnId: event.payload.session.activeTurnId,
|
||||||
lastError: event.payload.session.lastError,
|
lastError: event.payload.session.lastError,
|
||||||
|
|||||||
@@ -1,18 +1,9 @@
|
|||||||
import {
|
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||||
CheckpointRef,
|
|
||||||
EventId,
|
|
||||||
MessageId,
|
|
||||||
ProjectId,
|
|
||||||
ThreadId,
|
|
||||||
TurnId,
|
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Layer } from "effect";
|
import { Effect, Layer } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||||
import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
|
|
||||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||||
@@ -261,7 +252,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
workspaceRoot: "/tmp/project-1",
|
workspaceRoot: "/tmp/project-1",
|
||||||
repositoryIdentity: null,
|
repositoryIdentity: null,
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
scripts: [
|
scripts: [
|
||||||
@@ -284,7 +275,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread 1",
|
title: "Thread 1",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
@@ -372,7 +363,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
workspaceRoot: "/tmp/project-1",
|
workspaceRoot: "/tmp/project-1",
|
||||||
repositoryIdentity: null,
|
repositoryIdentity: null,
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
scripts: [
|
scripts: [
|
||||||
@@ -394,7 +385,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread 1",
|
title: "Thread 1",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
@@ -1030,378 +1021,4 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`DELETE FROM projection_projects`;
|
|
||||||
yield* sql`DELETE FROM projection_threads`;
|
|
||||||
yield* sql`DELETE FROM projection_turns`;
|
|
||||||
yield* sql`DELETE FROM projection_state`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_projects (
|
|
||||||
project_id,
|
|
||||||
title,
|
|
||||||
workspace_root,
|
|
||||||
default_model_selection_json,
|
|
||||||
scripts_json,
|
|
||||||
created_at,
|
|
||||||
updated_at,
|
|
||||||
deleted_at
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'project-1',
|
|
||||||
'Project 1',
|
|
||||||
'/tmp/project-1',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'[]',
|
|
||||||
'2026-04-03T00:00:00.000Z',
|
|
||||||
'2026-04-03T00:00:01.000Z',
|
|
||||||
NULL
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_threads (
|
|
||||||
thread_id,
|
|
||||||
project_id,
|
|
||||||
title,
|
|
||||||
model_selection_json,
|
|
||||||
runtime_mode,
|
|
||||||
interaction_mode,
|
|
||||||
branch,
|
|
||||||
worktree_path,
|
|
||||||
latest_turn_id,
|
|
||||||
latest_user_message_at,
|
|
||||||
pending_approval_count,
|
|
||||||
pending_user_input_count,
|
|
||||||
has_actionable_proposed_plan,
|
|
||||||
created_at,
|
|
||||||
updated_at,
|
|
||||||
archived_at,
|
|
||||||
deleted_at
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'thread-1',
|
|
||||||
'project-1',
|
|
||||||
'Thread 1',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'full-access',
|
|
||||||
'default',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'turn-running',
|
|
||||||
'2026-04-03T00:00:04.000Z',
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
'2026-04-03T00:00:02.000Z',
|
|
||||||
'2026-04-03T00:00:03.000Z',
|
|
||||||
NULL,
|
|
||||||
NULL
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_turns (
|
|
||||||
thread_id,
|
|
||||||
turn_id,
|
|
||||||
pending_message_id,
|
|
||||||
source_proposed_plan_thread_id,
|
|
||||||
source_proposed_plan_id,
|
|
||||||
assistant_message_id,
|
|
||||||
state,
|
|
||||||
requested_at,
|
|
||||||
started_at,
|
|
||||||
completed_at,
|
|
||||||
checkpoint_turn_count,
|
|
||||||
checkpoint_ref,
|
|
||||||
checkpoint_status,
|
|
||||||
checkpoint_files_json
|
|
||||||
)
|
|
||||||
VALUES
|
|
||||||
(
|
|
||||||
'thread-1',
|
|
||||||
'turn-running',
|
|
||||||
'message-user-2',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'running',
|
|
||||||
'2026-04-03T00:00:30.000Z',
|
|
||||||
'2026-04-03T00:00:30.000Z',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'[]'
|
|
||||||
),
|
|
||||||
(
|
|
||||||
'thread-1',
|
|
||||||
'turn-completed',
|
|
||||||
'message-user-1',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'message-assistant-1',
|
|
||||||
'completed',
|
|
||||||
'2026-04-03T00:00:05.000Z',
|
|
||||||
'2026-04-03T00:00:06.000Z',
|
|
||||||
'2026-04-03T00:00:20.000Z',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'[]'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
|
|
||||||
VALUES
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'),
|
|
||||||
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z')
|
|
||||||
`;
|
|
||||||
|
|
||||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
|
||||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
|
||||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running");
|
|
||||||
|
|
||||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
|
||||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
|
||||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running");
|
|
||||||
|
|
||||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
|
||||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
|
||||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("keeps deleted project and thread tombstones in the command read model", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`DELETE FROM projection_projects`;
|
|
||||||
yield* sql`DELETE FROM projection_threads`;
|
|
||||||
yield* sql`DELETE FROM projection_turns`;
|
|
||||||
yield* sql`DELETE FROM projection_state`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_projects (
|
|
||||||
project_id,
|
|
||||||
title,
|
|
||||||
workspace_root,
|
|
||||||
default_model_selection_json,
|
|
||||||
scripts_json,
|
|
||||||
created_at,
|
|
||||||
updated_at,
|
|
||||||
deleted_at
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'project-deleted',
|
|
||||||
'Deleted Project',
|
|
||||||
'/tmp/deleted-project',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'[]',
|
|
||||||
'2026-04-05T00:00:00.000Z',
|
|
||||||
'2026-04-05T00:00:01.000Z',
|
|
||||||
'2026-04-05T00:00:02.000Z'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_threads (
|
|
||||||
thread_id,
|
|
||||||
project_id,
|
|
||||||
title,
|
|
||||||
model_selection_json,
|
|
||||||
runtime_mode,
|
|
||||||
interaction_mode,
|
|
||||||
branch,
|
|
||||||
worktree_path,
|
|
||||||
latest_turn_id,
|
|
||||||
latest_user_message_at,
|
|
||||||
pending_approval_count,
|
|
||||||
pending_user_input_count,
|
|
||||||
has_actionable_proposed_plan,
|
|
||||||
created_at,
|
|
||||||
updated_at,
|
|
||||||
archived_at,
|
|
||||||
deleted_at
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'thread-deleted',
|
|
||||||
'project-deleted',
|
|
||||||
'Deleted Thread',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'full-access',
|
|
||||||
'default',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'turn-deleted',
|
|
||||||
NULL,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
'2026-04-05T00:00:03.000Z',
|
|
||||||
'2026-04-05T00:00:04.000Z',
|
|
||||||
NULL,
|
|
||||||
'2026-04-05T00:00:05.000Z'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_turns (
|
|
||||||
thread_id,
|
|
||||||
turn_id,
|
|
||||||
pending_message_id,
|
|
||||||
source_proposed_plan_thread_id,
|
|
||||||
source_proposed_plan_id,
|
|
||||||
assistant_message_id,
|
|
||||||
state,
|
|
||||||
requested_at,
|
|
||||||
started_at,
|
|
||||||
completed_at,
|
|
||||||
checkpoint_turn_count,
|
|
||||||
checkpoint_ref,
|
|
||||||
checkpoint_status,
|
|
||||||
checkpoint_files_json
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
'thread-deleted',
|
|
||||||
'turn-deleted',
|
|
||||||
'message-deleted-user',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'message-deleted-assistant',
|
|
||||||
'completed',
|
|
||||||
'2026-04-05T00:00:04.100Z',
|
|
||||||
'2026-04-05T00:00:04.200Z',
|
|
||||||
'2026-04-05T00:00:04.300Z',
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
NULL,
|
|
||||||
'[]'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
|
||||||
assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted"));
|
|
||||||
assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z");
|
|
||||||
assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted"));
|
|
||||||
assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z");
|
|
||||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
|
||||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed");
|
|
||||||
|
|
||||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
|
||||||
assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted"));
|
|
||||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
|
||||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed");
|
|
||||||
|
|
||||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
|
||||||
assert.equal(shellSnapshot.projects.length, 0);
|
|
||||||
assert.equal(shellSnapshot.threads.length, 0);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it.effect(
|
|
||||||
"ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots",
|
|
||||||
() => {
|
|
||||||
const resolveCalls: string[] = [];
|
|
||||||
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
|
||||||
Layer.provideMerge(
|
|
||||||
Layer.succeed(RepositoryIdentityResolver, {
|
|
||||||
resolve: (cwd: string) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
resolveCalls.push(cwd);
|
|
||||||
return {
|
|
||||||
canonicalKey: `github.com/acme${cwd}`,
|
|
||||||
locator: {
|
|
||||||
source: "git-remote" as const,
|
|
||||||
remoteName: "origin",
|
|
||||||
remoteUrl: `https://github.com/acme${cwd}.git`,
|
|
||||||
},
|
|
||||||
rootPath: cwd,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(SqlitePersistenceMemory),
|
|
||||||
);
|
|
||||||
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`DELETE FROM projection_projects`;
|
|
||||||
yield* sql`DELETE FROM projection_threads`;
|
|
||||||
yield* sql`DELETE FROM projection_turns`;
|
|
||||||
yield* sql`DELETE FROM projection_state`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
INSERT INTO projection_projects (
|
|
||||||
project_id,
|
|
||||||
title,
|
|
||||||
workspace_root,
|
|
||||||
default_model_selection_json,
|
|
||||||
scripts_json,
|
|
||||||
created_at,
|
|
||||||
updated_at,
|
|
||||||
deleted_at
|
|
||||||
)
|
|
||||||
VALUES
|
|
||||||
(
|
|
||||||
'project-1',
|
|
||||||
'Shared Project 1',
|
|
||||||
'/tmp/shared-root',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'[]',
|
|
||||||
'2026-04-04T00:00:00.000Z',
|
|
||||||
'2026-04-04T00:00:01.000Z',
|
|
||||||
NULL
|
|
||||||
),
|
|
||||||
(
|
|
||||||
'project-2',
|
|
||||||
'Shared Project 2',
|
|
||||||
'/tmp/shared-root',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'[]',
|
|
||||||
'2026-04-04T00:00:02.000Z',
|
|
||||||
'2026-04-04T00:00:03.000Z',
|
|
||||||
NULL
|
|
||||||
),
|
|
||||||
(
|
|
||||||
'project-3',
|
|
||||||
'Deleted Project',
|
|
||||||
'/tmp/deleted-root',
|
|
||||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
|
||||||
'[]',
|
|
||||||
'2026-04-04T00:00:04.000Z',
|
|
||||||
'2026-04-04T00:00:05.000Z',
|
|
||||||
'2026-04-04T00:00:06.000Z'
|
|
||||||
)
|
|
||||||
`;
|
|
||||||
|
|
||||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
|
||||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]);
|
|
||||||
assert.equal(shellSnapshot.projects.length, 2);
|
|
||||||
assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
|
||||||
assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
|
||||||
|
|
||||||
resolveCalls.length = 0;
|
|
||||||
|
|
||||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
|
||||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]);
|
|
||||||
assert.equal(fullSnapshot.projects.length, 3);
|
|
||||||
assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root");
|
|
||||||
}).pipe(Effect.provide(layer));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
@@ -195,7 +195,6 @@ function mapSessionRow(
|
|||||||
threadId: row.threadId,
|
threadId: row.threadId,
|
||||||
status: row.status,
|
status: row.status,
|
||||||
providerName: row.providerName,
|
providerName: row.providerName,
|
||||||
...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),
|
|
||||||
runtimeMode: row.runtimeMode,
|
runtimeMode: row.runtimeMode,
|
||||||
activeTurnId: row.activeTurnId,
|
activeTurnId: row.activeTurnId,
|
||||||
lastError: row.lastError,
|
lastError: row.lastError,
|
||||||
@@ -219,20 +218,6 @@ function mapProjectShellRow(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapProposedPlanRow(
|
|
||||||
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
|
|
||||||
): OrchestrationProposedPlan {
|
|
||||||
return {
|
|
||||||
id: row.planId,
|
|
||||||
turnId: row.turnId,
|
|
||||||
planMarkdown: row.planMarkdown,
|
|
||||||
implementedAt: row.implementedAt,
|
|
||||||
implementationThreadId: row.implementationThreadId,
|
|
||||||
createdAt: row.createdAt,
|
|
||||||
updatedAt: row.updatedAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||||
return (cause: unknown): ProjectionRepositoryError =>
|
return (cause: unknown): ProjectionRepositoryError =>
|
||||||
Schema.isSchemaError(cause)
|
Schema.isSchemaError(cause)
|
||||||
@@ -244,37 +229,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||||
const repositoryIdentityResolutionConcurrency = 4;
|
const repositoryIdentityResolutionConcurrency = 4;
|
||||||
const resolveRepositoryIdentitiesForProjects = Effect.fn(
|
|
||||||
"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects",
|
|
||||||
)(function* (
|
|
||||||
projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,
|
|
||||||
options?: {
|
|
||||||
readonly includeDeleted?: boolean;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
const filteredProjectRows =
|
|
||||||
options?.includeDeleted === true
|
|
||||||
? projectRows
|
|
||||||
: projectRows.filter((row) => row.deletedAt === null);
|
|
||||||
const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];
|
|
||||||
const repositoryIdentityByWorkspaceRoot = new Map(
|
|
||||||
yield* Effect.forEach(
|
|
||||||
uniqueWorkspaceRoots,
|
|
||||||
(workspaceRoot) =>
|
|
||||||
repositoryIdentityResolver
|
|
||||||
.resolve(workspaceRoot)
|
|
||||||
.pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),
|
|
||||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return new Map(
|
|
||||||
filteredProjectRows.map((row) => [
|
|
||||||
row.projectId,
|
|
||||||
repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const listProjectRows = SqlSchema.findAll({
|
const listProjectRows = SqlSchema.findAll({
|
||||||
Request: Schema.Void,
|
Request: Schema.Void,
|
||||||
@@ -380,6 +334,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
FROM projection_thread_activities
|
FROM projection_thread_activities
|
||||||
ORDER BY
|
ORDER BY
|
||||||
thread_id ASC,
|
thread_id ASC,
|
||||||
|
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||||
sequence ASC,
|
sequence ASC,
|
||||||
created_at ASC,
|
created_at ASC,
|
||||||
activity_id ASC
|
activity_id ASC
|
||||||
@@ -395,7 +350,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
status,
|
status,
|
||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_instance_id AS "providerInstanceId",
|
|
||||||
provider_session_id AS "providerSessionId",
|
provider_session_id AS "providerSessionId",
|
||||||
provider_thread_id AS "providerThreadId",
|
provider_thread_id AS "providerThreadId",
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
@@ -433,46 +387,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
execute: () =>
|
execute: () =>
|
||||||
sql`
|
sql`
|
||||||
SELECT
|
SELECT
|
||||||
turns.thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
turns.turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
turns.state,
|
state,
|
||||||
turns.requested_at AS "requestedAt",
|
requested_at AS "requestedAt",
|
||||||
turns.started_at AS "startedAt",
|
started_at AS "startedAt",
|
||||||
turns.completed_at AS "completedAt",
|
completed_at AS "completedAt",
|
||||||
turns.assistant_message_id AS "assistantMessageId",
|
assistant_message_id AS "assistantMessageId",
|
||||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||||
FROM projection_threads threads
|
FROM projection_turns
|
||||||
JOIN projection_turns turns
|
WHERE turn_id IS NOT NULL
|
||||||
ON turns.thread_id = threads.thread_id
|
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||||
AND turns.turn_id = threads.latest_turn_id
|
|
||||||
WHERE threads.latest_turn_id IS NOT NULL
|
|
||||||
ORDER BY turns.thread_id ASC
|
|
||||||
`,
|
|
||||||
});
|
|
||||||
|
|
||||||
const listActiveLatestTurnRows = SqlSchema.findAll({
|
|
||||||
Request: Schema.Void,
|
|
||||||
Result: ProjectionLatestTurnDbRowSchema,
|
|
||||||
execute: () =>
|
|
||||||
sql`
|
|
||||||
SELECT
|
|
||||||
turns.thread_id AS "threadId",
|
|
||||||
turns.turn_id AS "turnId",
|
|
||||||
turns.state,
|
|
||||||
turns.requested_at AS "requestedAt",
|
|
||||||
turns.started_at AS "startedAt",
|
|
||||||
turns.completed_at AS "completedAt",
|
|
||||||
turns.assistant_message_id AS "assistantMessageId",
|
|
||||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
|
||||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
|
||||||
FROM projection_threads threads
|
|
||||||
JOIN projection_turns turns
|
|
||||||
ON turns.thread_id = threads.thread_id
|
|
||||||
AND turns.turn_id = threads.latest_turn_id
|
|
||||||
WHERE threads.deleted_at IS NULL
|
|
||||||
AND threads.latest_turn_id IS NOT NULL
|
|
||||||
ORDER BY turns.thread_id ASC
|
|
||||||
`,
|
`,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -666,6 +592,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
FROM projection_thread_activities
|
FROM projection_thread_activities
|
||||||
WHERE thread_id = ${threadId}
|
WHERE thread_id = ${threadId}
|
||||||
ORDER BY
|
ORDER BY
|
||||||
|
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||||
sequence ASC,
|
sequence ASC,
|
||||||
created_at ASC,
|
created_at ASC,
|
||||||
activity_id ASC
|
activity_id ASC
|
||||||
@@ -681,7 +608,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
status,
|
status,
|
||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_instance_id AS "providerInstanceId",
|
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
@@ -953,9 +879,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
threadId: row.threadId,
|
threadId: row.threadId,
|
||||||
status: row.status,
|
status: row.status,
|
||||||
providerName: row.providerName,
|
providerName: row.providerName,
|
||||||
...(row.providerInstanceId !== null
|
|
||||||
? { providerInstanceId: row.providerInstanceId }
|
|
||||||
: {}),
|
|
||||||
runtimeMode: row.runtimeMode,
|
runtimeMode: row.runtimeMode,
|
||||||
activeTurnId: row.activeTurnId,
|
activeTurnId: row.activeTurnId,
|
||||||
lastError: row.lastError,
|
lastError: row.lastError,
|
||||||
@@ -963,9 +886,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
|
const repositoryIdentities = new Map(
|
||||||
projectRows,
|
yield* Effect.forEach(
|
||||||
{ includeDeleted: true },
|
projectRows,
|
||||||
|
(row) =>
|
||||||
|
repositoryIdentityResolver
|
||||||
|
.resolve(row.workspaceRoot)
|
||||||
|
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||||
|
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||||
@@ -1023,199 +952,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const getCommandReadModel: ProjectionSnapshotQueryShape["getCommandReadModel"] = () =>
|
|
||||||
sql
|
|
||||||
.withTransaction(
|
|
||||||
Effect.all([
|
|
||||||
listProjectRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listThreadRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listThreadProposedPlanRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listThreadSessionRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listLatestTurnRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listProjectionStateRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query",
|
|
||||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
.pipe(
|
|
||||||
Effect.flatMap(
|
|
||||||
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
let updatedAt: string | null = null;
|
|
||||||
const projects: OrchestrationProject[] = [];
|
|
||||||
const threads: OrchestrationThread[] = [];
|
|
||||||
|
|
||||||
for (let index = 0; index < projectRows.length; index += 1) {
|
|
||||||
const row = projectRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
|
||||||
projects.push({
|
|
||||||
id: row.projectId,
|
|
||||||
title: row.title,
|
|
||||||
workspaceRoot: row.workspaceRoot,
|
|
||||||
defaultModelSelection: row.defaultModelSelection,
|
|
||||||
scripts: row.scripts,
|
|
||||||
createdAt: row.createdAt,
|
|
||||||
updatedAt: row.updatedAt,
|
|
||||||
deletedAt: row.deletedAt,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
for (let index = 0; index < threadRows.length; index += 1) {
|
|
||||||
const row = threadRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
|
||||||
}
|
|
||||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
|
||||||
const row = proposedPlanRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
|
||||||
}
|
|
||||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
|
||||||
const row = sessionRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
|
||||||
}
|
|
||||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
|
||||||
const row = latestTurnRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
|
||||||
if (row.startedAt !== null) {
|
|
||||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
|
||||||
}
|
|
||||||
if (row.completedAt !== null) {
|
|
||||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (let index = 0; index < stateRows.length; index += 1) {
|
|
||||||
const row = stateRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
|
||||||
}
|
|
||||||
|
|
||||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
|
||||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
|
||||||
const row = latestTurnRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
|
|
||||||
}
|
|
||||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
|
||||||
const sessionByThread = new Map<string, OrchestrationSession>();
|
|
||||||
|
|
||||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
|
||||||
const row = sessionRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
sessionByThread.set(row.threadId, mapSessionRow(row));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
|
||||||
const row = proposedPlanRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
|
|
||||||
threadProposedPlans.push(mapProposedPlanRow(row));
|
|
||||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let index = 0; index < threadRows.length; index += 1) {
|
|
||||||
const row = threadRows[index];
|
|
||||||
if (!row) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
threads.push({
|
|
||||||
id: row.threadId,
|
|
||||||
projectId: row.projectId,
|
|
||||||
title: row.title,
|
|
||||||
modelSelection: row.modelSelection,
|
|
||||||
runtimeMode: row.runtimeMode,
|
|
||||||
interactionMode: row.interactionMode,
|
|
||||||
branch: row.branch,
|
|
||||||
worktreePath: row.worktreePath,
|
|
||||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
|
||||||
createdAt: row.createdAt,
|
|
||||||
updatedAt: row.updatedAt,
|
|
||||||
archivedAt: row.archivedAt,
|
|
||||||
deletedAt: row.deletedAt,
|
|
||||||
messages: [],
|
|
||||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
|
||||||
activities: [],
|
|
||||||
checkpoints: [],
|
|
||||||
session: sessionByThread.get(row.threadId) ?? null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
|
||||||
projects,
|
|
||||||
threads,
|
|
||||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
|
||||||
} satisfies OrchestrationReadModel;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.mapError((error) => {
|
|
||||||
if (isPersistenceError(error)) {
|
|
||||||
return error;
|
|
||||||
}
|
|
||||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getCommandReadModel:query")(error);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||||
sql
|
sql
|
||||||
.withTransaction(
|
.withTransaction(
|
||||||
@@ -1244,7 +980,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
listActiveLatestTurnRows(undefined).pipe(
|
listLatestTurnRows(undefined).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
toPersistenceSqlOrDecodeError(
|
toPersistenceSqlOrDecodeError(
|
||||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||||
@@ -1288,7 +1024,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
|
const repositoryIdentities = new Map(
|
||||||
|
yield* Effect.forEach(
|
||||||
|
projectRows,
|
||||||
|
(row) =>
|
||||||
|
repositoryIdentityResolver
|
||||||
|
.resolve(row.workspaceRoot)
|
||||||
|
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||||
|
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||||
|
),
|
||||||
|
);
|
||||||
const latestTurnByThread = new Map(
|
const latestTurnByThread = new Map(
|
||||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||||
);
|
);
|
||||||
@@ -1346,19 +1091,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
|
|
||||||
listProjectionStateRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getSnapshotSequence:query",
|
|
||||||
"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.map((stateRows) => ({
|
|
||||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
|
|
||||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||||
readProjectionCounts(undefined).pipe(
|
readProjectionCounts(undefined).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
@@ -1638,7 +1370,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
return message;
|
return message;
|
||||||
}),
|
}),
|
||||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
proposedPlans: proposedPlanRows.map((row) => ({
|
||||||
|
id: row.planId,
|
||||||
|
turnId: row.turnId,
|
||||||
|
planMarkdown: row.planMarkdown,
|
||||||
|
implementedAt: row.implementedAt,
|
||||||
|
implementationThreadId: row.implementationThreadId,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
updatedAt: row.updatedAt,
|
||||||
|
})),
|
||||||
activities: activityRows.map((row) => {
|
activities: activityRows.map((row) => {
|
||||||
const activity = {
|
const activity = {
|
||||||
id: row.activityId,
|
id: row.activityId,
|
||||||
@@ -1676,10 +1416,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getCommandReadModel,
|
|
||||||
getSnapshot,
|
getSnapshot,
|
||||||
getShellSnapshot,
|
getShellSnapshot,
|
||||||
getSnapshotSequence,
|
|
||||||
getCounts,
|
getCounts,
|
||||||
getActiveProjectByWorkspaceRoot,
|
getActiveProjectByWorkspaceRoot,
|
||||||
getProjectShellById,
|
getProjectShellById,
|
||||||
|
|||||||
@@ -2,13 +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 {
|
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||||
ModelSelection,
|
|
||||||
ProviderRuntimeEvent,
|
|
||||||
ProviderSession,
|
|
||||||
ProviderDriverKind,
|
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { createModelSelection } from "@t3tools/shared/model";
|
import { createModelSelection } from "@t3tools/shared/model";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
@@ -33,23 +27,21 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||||
|
import {
|
||||||
|
GitStatusBroadcaster,
|
||||||
|
type GitStatusBroadcasterShape,
|
||||||
|
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||||
import {
|
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||||
providerErrorLabel,
|
|
||||||
providerErrorLabelFromInstanceHint,
|
|
||||||
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 { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
|
||||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
|
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||||
@@ -80,7 +72,7 @@ async function waitFor(
|
|||||||
|
|
||||||
describe("ProviderCommandReactor", () => {
|
describe("ProviderCommandReactor", () => {
|
||||||
let runtime: ManagedRuntime.ManagedRuntime<
|
let runtime: ManagedRuntime.ManagedRuntime<
|
||||||
OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
|
OrchestrationEngineService | ProviderCommandReactor,
|
||||||
unknown
|
unknown
|
||||||
> | null = null;
|
> | null = null;
|
||||||
let scope: Scope.Closeable | null = null;
|
let scope: Scope.Closeable | null = null;
|
||||||
@@ -106,30 +98,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
createdBaseDirs.clear();
|
createdBaseDirs.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("provider error attribution", () => {
|
|
||||||
it("uses the current provider instance slug when current instance lookup fails", () => {
|
|
||||||
expect(
|
|
||||||
providerErrorLabelFromInstanceHint({
|
|
||||||
instanceId: "codex_personal",
|
|
||||||
modelSelectionInstanceId: "codex",
|
|
||||||
sessionProvider: "codex",
|
|
||||||
}),
|
|
||||||
).toBe("codex_personal");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses the desired provider instance slug when desired instance lookup fails", () => {
|
|
||||||
expect(
|
|
||||||
providerErrorLabelFromInstanceHint({
|
|
||||||
instanceId: "claude_openrouter",
|
|
||||||
}),
|
|
||||||
).toBe("claude_openrouter");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses the unknown driver kind when the resolved driver is not registered locally", () => {
|
|
||||||
expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
async function createHarness(input?: {
|
async function createHarness(input?: {
|
||||||
readonly baseDir?: string;
|
readonly baseDir?: string;
|
||||||
readonly threadModelSelection?: ModelSelection;
|
readonly threadModelSelection?: ModelSelection;
|
||||||
@@ -144,7 +112,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
let nextSessionIndex = 1;
|
let nextSessionIndex = 1;
|
||||||
const runtimeSessions: Array<ProviderSession> = [];
|
const runtimeSessions: Array<ProviderSession> = [];
|
||||||
const modelSelection = input?.threadModelSelection ?? {
|
const modelSelection = input?.threadModelSelection ?? {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
};
|
};
|
||||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||||
@@ -160,24 +128,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
typeof input.threadId === "string"
|
typeof input.threadId === "string"
|
||||||
? ThreadId.make(input.threadId)
|
? ThreadId.make(input.threadId)
|
||||||
: ThreadId.make(`thread-${sessionIndex}`);
|
: ThreadId.make(`thread-${sessionIndex}`);
|
||||||
const inputModelSelection =
|
|
||||||
typeof input === "object" && input !== null && "modelSelection" in input
|
|
||||||
? (input.modelSelection as ModelSelection | undefined)
|
|
||||||
: undefined;
|
|
||||||
const providerInstanceId =
|
|
||||||
typeof input === "object" && input !== null && "providerInstanceId" in input
|
|
||||||
? (input.providerInstanceId as ProviderInstanceId | undefined)
|
|
||||||
: inputModelSelection?.instanceId;
|
|
||||||
const provider =
|
|
||||||
typeof input === "object" &&
|
|
||||||
input !== null &&
|
|
||||||
"provider" in input &&
|
|
||||||
typeof input.provider === "string"
|
|
||||||
? (input.provider as ProviderSession["provider"])
|
|
||||||
: ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId);
|
|
||||||
const session: ProviderSession = {
|
const session: ProviderSession = {
|
||||||
provider,
|
provider: modelSelection.provider,
|
||||||
...(providerInstanceId ? { providerInstanceId } : {}),
|
|
||||||
status: "ready" as const,
|
status: "ready" as const,
|
||||||
runtimeMode:
|
runtimeMode:
|
||||||
typeof input === "object" &&
|
typeof input === "object" &&
|
||||||
@@ -186,15 +138,7 @@ 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",
|
||||||
...(typeof input === "object" &&
|
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
|
||||||
input !== null &&
|
|
||||||
"cwd" in input &&
|
|
||||||
typeof input.cwd === "string"
|
|
||||||
? { cwd: input.cwd }
|
|
||||||
: {}),
|
|
||||||
...((inputModelSelection?.model ?? modelSelection.model)
|
|
||||||
? { model: inputModelSelection?.model ?? modelSelection.model }
|
|
||||||
: {}),
|
|
||||||
threadId,
|
threadId,
|
||||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -241,9 +185,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const refreshStatus = vi.fn((_: string) =>
|
const refreshStatus = vi.fn((_: string) =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
isRepo: true,
|
isRepo: true,
|
||||||
hasPrimaryRemote: true,
|
hasOriginRemote: true,
|
||||||
isDefaultRef: false,
|
isDefaultBranch: false,
|
||||||
refName: "renamed-branch",
|
branch: "renamed-branch",
|
||||||
hasWorkingTreeChanges: false,
|
hasWorkingTreeChanges: false,
|
||||||
workingTree: {
|
workingTree: {
|
||||||
files: [],
|
files: [],
|
||||||
@@ -286,25 +230,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||||
}),
|
}),
|
||||||
getInstanceInfo: (instanceId) => {
|
|
||||||
const raw = String(instanceId);
|
|
||||||
const driverKind = ProviderDriverKind.make(
|
|
||||||
raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw,
|
|
||||||
);
|
|
||||||
return Effect.succeed({
|
|
||||||
instanceId,
|
|
||||||
driverKind,
|
|
||||||
displayName: undefined,
|
|
||||||
enabled: true,
|
|
||||||
continuationIdentity: {
|
|
||||||
driverKind,
|
|
||||||
continuationKey:
|
|
||||||
driverKind === ProviderDriverKind.make("codex")
|
|
||||||
? "codex:home:/shared-codex"
|
|
||||||
: `${driverKind}:instance:${instanceId}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
rollbackConversation: () => unsupported(),
|
rollbackConversation: () => unsupported(),
|
||||||
get streamEvents() {
|
get streamEvents() {
|
||||||
return Stream.fromPubSub(runtimeEventPubSub);
|
return Stream.fromPubSub(runtimeEventPubSub);
|
||||||
@@ -319,27 +244,18 @@ describe("ProviderCommandReactor", () => {
|
|||||||
Layer.provide(RepositoryIdentityResolverLive),
|
Layer.provide(RepositoryIdentityResolverLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
|
||||||
Layer.provide(RepositoryIdentityResolverLive),
|
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
|
||||||
);
|
|
||||||
const layer = ProviderCommandReactorLive.pipe(
|
const layer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(projectionSnapshotLayer),
|
|
||||||
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.provideMerge(
|
||||||
Layer.mock(GitWorkflowService)({
|
Layer.succeed(GitStatusBroadcaster, {
|
||||||
renameBranch,
|
|
||||||
} satisfies Partial<GitWorkflowServiceShape>),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(
|
|
||||||
Layer.succeed(VcsStatusBroadcaster, {
|
|
||||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||||
refreshLocalStatus: () =>
|
refreshLocalStatus: () =>
|
||||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||||
refreshStatus,
|
refreshStatus,
|
||||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||||
}),
|
} satisfies GitStatusBroadcasterShape),
|
||||||
),
|
),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.mock(TextGeneration, {
|
Layer.mock(TextGeneration, {
|
||||||
@@ -354,7 +270,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
|
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
|
||||||
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)));
|
||||||
@@ -389,7 +304,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
engine,
|
engine,
|
||||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
|
||||||
startSession,
|
startSession,
|
||||||
sendTurn,
|
sendTurn,
|
||||||
interruptTurn,
|
interruptTurn,
|
||||||
@@ -400,7 +314,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
refreshStatus,
|
refreshStatus,
|
||||||
generateBranchName,
|
generateBranchName,
|
||||||
generateThreadTitle,
|
generateThreadTitle,
|
||||||
runtimeSessions,
|
|
||||||
stateDir,
|
stateDir,
|
||||||
drain,
|
drain,
|
||||||
};
|
};
|
||||||
@@ -433,13 +346,13 @@ describe("ProviderCommandReactor", () => {
|
|||||||
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: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
expect(thread?.session?.threadId).toBe("thread-1");
|
||||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||||
@@ -484,13 +397,13 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
return (
|
return (
|
||||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||||
"Generated title"
|
"Generated title"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.title).toBe("Generated title");
|
expect(thread?.title).toBe("Generated title");
|
||||||
});
|
});
|
||||||
@@ -530,7 +443,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.title).toBe("Keep this custom title");
|
expect(thread?.title).toBe("Keep this custom title");
|
||||||
});
|
});
|
||||||
@@ -574,14 +487,14 @@ describe("ProviderCommandReactor", () => {
|
|||||||
|
|
||||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
return (
|
return (
|
||||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||||
"Reconnect spinner resume bug"
|
"Reconnect spinner resume bug"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||||
});
|
});
|
||||||
@@ -655,7 +568,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello fast mode",
|
text: "hello fast mode",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||||
{ id: "reasoningEffort", value: "high" },
|
{ id: "reasoningEffort", value: "high" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
@@ -668,14 +581,14 @@ 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: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||||
{ id: "reasoningEffort", value: "high" },
|
{ id: "reasoningEffort", value: "high" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
});
|
});
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||||
{ id: "reasoningEffort", value: "high" },
|
{ id: "reasoningEffort", value: "high" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
@@ -684,10 +597,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
|
|
||||||
it("forwards claude effort options through session start and turn send", async () => {
|
it("forwards claude effort options through session start and turn send", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
threadModelSelection: {
|
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -702,11 +612,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello with effort",
|
text: "hello with effort",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "max" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "max" }],
|
|
||||||
),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -716,28 +624,21 @@ 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: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "max" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "max" }],
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "max" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "max" }],
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
threadModelSelection: {
|
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -752,11 +653,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello with fast mode",
|
text: "hello with fast mode",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "fastMode", value: true },
|
||||||
"claude-opus-4-6",
|
]),
|
||||||
[{ id: "fastMode", value: true }],
|
|
||||||
),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -766,19 +665,15 @@ 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: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "fastMode", value: true },
|
||||||
"claude-opus-4-6",
|
]),
|
||||||
[{ id: "fastMode", value: true }],
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "fastMode", value: true },
|
||||||
"claude-opus-4-6",
|
]),
|
||||||
[{ id: "fastMode", value: true }],
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -865,15 +760,15 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
|
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
|
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||||
});
|
});
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -889,7 +784,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -898,25 +793,29 @@ describe("ProviderCommandReactor", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
await waitFor(async () => {
|
||||||
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
expect(harness.startSession).toHaveBeenCalledTimes(1);
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
return (
|
||||||
provider: ProviderDriverKind.make("claudeAgent"),
|
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||||
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
|
false
|
||||||
modelSelection: {
|
);
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
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.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session?.providerName).toBe("claudeAgent");
|
expect(thread?.session).toBeNull();
|
||||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
|
|
||||||
expect(
|
expect(
|
||||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||||
).toBeUndefined();
|
).toMatchObject({
|
||||||
|
summary: "Provider turn start failed",
|
||||||
|
payload: {
|
||||||
|
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||||
|
},
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||||
@@ -965,147 +864,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("restarts an existing Codex thread on a compatible requested instance", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.make("cmd-turn-start-compatible-codex-1"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-compatible-codex-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
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.make("cmd-turn-start-compatible-codex-2"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-compatible-codex-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
instanceId: ProviderInstanceId.make("codex_work"),
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
|
||||||
|
|
||||||
expect(harness.startSession).toHaveBeenCalledTimes(2);
|
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
|
||||||
provider: ProviderDriverKind.make("codex"),
|
|
||||||
providerInstanceId: ProviderInstanceId.make("codex_work"),
|
|
||||||
resumeCursor: { opaque: "resume-1" },
|
|
||||||
});
|
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
|
||||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restarts the provider session when the thread workspace changes", async () => {
|
|
||||||
const harness = await createHarness({
|
|
||||||
threadModelSelection: {
|
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.make("cmd-turn-start-workspace-1"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-workspace-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first in project root",
|
|
||||||
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);
|
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
|
||||||
cwd: "/tmp/provider-project",
|
|
||||||
});
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: CommandId.make("cmd-thread-worktree-change"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
worktreePath: "/tmp/provider-project-worktree",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.make("cmd-turn-start-workspace-2"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-workspace-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second in worktree",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
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.stopSession.mock.calls.length).toBe(0);
|
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
cwd: "/tmp/provider-project-worktree",
|
|
||||||
resumeCursor: { opaque: "resume-1" },
|
|
||||||
modelSelection: {
|
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restarts claude sessions when claude effort changes", async () => {
|
it("restarts claude sessions when claude effort changes", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
threadModelSelection: {
|
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -1120,11 +881,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "first claude turn",
|
text: "first claude turn",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "medium" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "medium" }],
|
|
||||||
),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -1145,11 +904,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "second claude turn",
|
text: "second claude turn",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "max" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "max" }],
|
|
||||||
),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -1160,11 +917,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||||
resumeCursor: { opaque: "resume-1" },
|
resumeCursor: { opaque: "resume-1" },
|
||||||
modelSelection: createModelSelection(
|
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||||
ProviderInstanceId.make("claudeAgent"),
|
{ id: "effort", value: "max" },
|
||||||
"claude-sonnet-4-6",
|
]),
|
||||||
[{ id: "effort", value: "max" }],
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1213,7 +968,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
return thread?.runtimeMode === "approval-required";
|
return thread?.runtimeMode === "approval-required";
|
||||||
});
|
});
|
||||||
@@ -1247,7 +1002,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
expect(thread?.session?.threadId).toBe("thread-1");
|
||||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||||
@@ -1255,10 +1010,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
|
|
||||||
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
||||||
const harness = await createHarness({
|
const harness = await createHarness({
|
||||||
threadModelSelection: {
|
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -1294,7 +1046,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
|
|
||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
},
|
},
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
@@ -1350,7 +1102,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
return thread?.runtimeMode === "approval-required";
|
return thread?.runtimeMode === "approval-required";
|
||||||
});
|
});
|
||||||
@@ -1360,7 +1112,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
expect(thread?.session?.threadId).toBe("thread-1");
|
||||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||||
@@ -1402,7 +1154,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -1412,7 +1164,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
return (
|
return (
|
||||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||||
@@ -1424,7 +1176,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
expect(thread?.session?.threadId).toBe("thread-1");
|
||||||
expect(thread?.session?.providerName).toBe("codex");
|
expect(thread?.session?.providerName).toBe("codex");
|
||||||
@@ -1438,72 +1190,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.make("cmd-session-set-stopped-provider-switch"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
status: "stopped",
|
|
||||||
providerName: "codex",
|
|
||||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-stopped-provider-switch"),
|
|
||||||
role: "user",
|
|
||||||
text: "continue with claude",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
modelSelection: {
|
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await harness.readModel();
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
|
||||||
return (
|
|
||||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
|
||||||
false
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
|
||||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
|
||||||
const readModel = await harness.readModel();
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
|
||||||
expect(
|
|
||||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
).toMatchObject({
|
|
||||||
payload: {
|
|
||||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -1587,7 +1273,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
@@ -1597,77 +1283,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects active runtime sessions that are missing provider instance ids", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.make("cmd-session-set-missing-instance"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
status: "ready",
|
|
||||||
providerName: "codex",
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
activeTurnId: null,
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
harness.runtimeSessions.push({
|
|
||||||
provider: ProviderDriverKind.make("codex"),
|
|
||||||
status: "ready",
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
cwd: "/tmp/provider-project",
|
|
||||||
resumeCursor: { opaque: "resume-without-instance" },
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
});
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.make("cmd-turn-start-missing-instance"),
|
|
||||||
threadId: ThreadId.make("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-missing-instance"),
|
|
||||||
role: "user",
|
|
||||||
text: "resume codex",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "approval-required",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(async () => {
|
|
||||||
const readModel = await harness.readModel();
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
|
||||||
return (
|
|
||||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
|
||||||
false
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
|
||||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
|
||||||
const readModel = await harness.readModel();
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
|
||||||
expect(
|
|
||||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
).toMatchObject({
|
|
||||||
payload: {
|
|
||||||
detail: expect.stringContaining("without a provider instance id"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -1760,7 +1375,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
harness.respondToRequest.mockImplementation(() =>
|
harness.respondToRequest.mockImplementation(() =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new ProviderAdapterRequestError({
|
new ProviderAdapterRequestError({
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
method: "session/request_permission",
|
method: "session/request_permission",
|
||||||
detail: "Unknown pending permission request: approval-request-1",
|
detail: "Unknown pending permission request: approval-request-1",
|
||||||
}),
|
}),
|
||||||
@@ -1818,7 +1433,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
if (!thread) return false;
|
if (!thread) return false;
|
||||||
return thread.activities.some(
|
return thread.activities.some(
|
||||||
@@ -1826,7 +1441,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread).toBeDefined();
|
expect(thread).toBeDefined();
|
||||||
|
|
||||||
@@ -1855,7 +1470,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
harness.respondToUserInput.mockImplementation(() =>
|
harness.respondToUserInput.mockImplementation(() =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new ProviderAdapterRequestError({
|
new ProviderAdapterRequestError({
|
||||||
provider: ProviderDriverKind.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
method: "item/tool/respondToUserInput",
|
method: "item/tool/respondToUserInput",
|
||||||
detail: "Unknown pending user-input request: user-input-request-1",
|
detail: "Unknown pending user-input request: user-input-request-1",
|
||||||
}),
|
}),
|
||||||
@@ -1927,7 +1542,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(async () => {
|
await waitFor(async () => {
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
if (!thread) return false;
|
if (!thread) return false;
|
||||||
return thread.activities.some(
|
return thread.activities.some(
|
||||||
@@ -1935,7 +1550,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread).toBeDefined();
|
expect(thread).toBeDefined();
|
||||||
|
|
||||||
@@ -1971,7 +1586,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
status: "ready",
|
status: "ready",
|
||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerInstanceId: ProviderInstanceId.make("codex_work"),
|
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
@@ -1991,12 +1605,11 @@ describe("ProviderCommandReactor", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||||
const readModel = await harness.readModel();
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||||
expect(thread?.session).not.toBeNull();
|
expect(thread?.session).not.toBeNull();
|
||||||
expect(thread?.session?.status).toBe("stopped");
|
expect(thread?.session?.status).toBe("stopped");
|
||||||
expect(thread?.session?.threadId).toBe("thread-1");
|
expect(thread?.session?.threadId).toBe("thread-1");
|
||||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
|
|
||||||
expect(thread?.session?.activeTurnId).toBeNull();
|
expect(thread?.session?.activeTurnId).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -4,8 +4,7 @@ import {
|
|||||||
EventId,
|
EventId,
|
||||||
type ModelSelection,
|
type ModelSelection,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
ProviderDriverKind,
|
ProviderKind,
|
||||||
type ProjectId,
|
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
@@ -17,20 +16,19 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream }
|
|||||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||||
|
|
||||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||||
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
|
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import {
|
import {
|
||||||
ProviderCommandReactor,
|
ProviderCommandReactor,
|
||||||
type ProviderCommandReactorShape,
|
type ProviderCommandReactorShape,
|
||||||
} from "../Services/ProviderCommandReactor.ts";
|
} from "../Services/ProviderCommandReactor.ts";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
|
||||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
|
||||||
|
|
||||||
type ProviderIntentEvent = Extract<
|
type ProviderIntentEvent = Extract<
|
||||||
OrchestrationEvent,
|
OrchestrationEvent,
|
||||||
@@ -79,21 +77,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 DEFAULT_THREAD_TITLE = "New thread";
|
const DEFAULT_THREAD_TITLE = "New thread";
|
||||||
|
|
||||||
export function providerErrorLabel(value: string | undefined): string {
|
|
||||||
const normalized = value?.trim();
|
|
||||||
return normalized && normalized.length > 0 ? normalized : "unknown";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function providerErrorLabelFromInstanceHint(input: {
|
|
||||||
readonly instanceId?: string | undefined;
|
|
||||||
readonly modelSelectionInstanceId?: string | undefined;
|
|
||||||
readonly sessionProvider?: string | undefined;
|
|
||||||
}): string {
|
|
||||||
return providerErrorLabel(
|
|
||||||
input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
||||||
const trimmedCurrentTitle = currentTitle.trim();
|
const trimmedCurrentTitle = currentTitle.trim();
|
||||||
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
|
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
|
||||||
@@ -169,10 +152,9 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
|
|||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const gitWorkflow = yield* GitWorkflowService;
|
const git = yield* GitCore;
|
||||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const serverSettingsService = yield* ServerSettingsService;
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||||
@@ -270,16 +252,9 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
|
|
||||||
return yield* projectionSnapshotQuery
|
|
||||||
.getProjectShellById(projectId)
|
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||||
return yield* projectionSnapshotQuery
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
.getThreadDetailById(threadId)
|
return readModel.threads.find((entry) => entry.id === threadId);
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
||||||
@@ -289,115 +264,49 @@ const make = Effect.gen(function* () {
|
|||||||
readonly modelSelection?: ModelSelection;
|
readonly modelSelection?: ModelSelection;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const thread = yield* resolveThread(threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||||
}
|
}
|
||||||
|
|
||||||
const desiredRuntimeMode = thread.runtimeMode;
|
const desiredRuntimeMode = thread.runtimeMode;
|
||||||
|
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
|
||||||
|
thread.session?.providerName,
|
||||||
|
)
|
||||||
|
? thread.session.providerName
|
||||||
|
: undefined;
|
||||||
const requestedModelSelection = options?.modelSelection;
|
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 = threadProvider;
|
||||||
|
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||||
|
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||||
|
thread,
|
||||||
|
projects: readModel.projects,
|
||||||
|
});
|
||||||
|
|
||||||
const resolveActiveSession = (threadId: ThreadId) =>
|
const resolveActiveSession = (threadId: ThreadId) =>
|
||||||
providerService
|
providerService
|
||||||
.listSessions()
|
.listSessions()
|
||||||
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
|
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
|
||||||
|
|
||||||
const activeSession = yield* resolveActiveSession(threadId);
|
|
||||||
const activeThreadSession =
|
|
||||||
thread.session !== null && thread.session.status !== "stopped" && activeSession
|
|
||||||
? thread.session
|
|
||||||
: null;
|
|
||||||
if (
|
|
||||||
activeThreadSession !== null &&
|
|
||||||
activeSession !== undefined &&
|
|
||||||
(activeThreadSession.providerInstanceId === undefined ||
|
|
||||||
activeSession.providerInstanceId === undefined)
|
|
||||||
) {
|
|
||||||
return yield* new ProviderAdapterRequestError({
|
|
||||||
provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const currentInstanceId =
|
|
||||||
activeThreadSession !== null &&
|
|
||||||
activeSession !== undefined &&
|
|
||||||
activeSession.providerInstanceId !== undefined
|
|
||||||
? activeSession.providerInstanceId
|
|
||||||
: thread.modelSelection.instanceId;
|
|
||||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
|
||||||
const desiredInstanceId = desiredModelSelection.instanceId;
|
|
||||||
const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
() =>
|
|
||||||
new ProviderAdapterRequestError({
|
|
||||||
provider: providerErrorLabelFromInstanceHint({
|
|
||||||
instanceId: String(currentInstanceId),
|
|
||||||
modelSelectionInstanceId: String(thread.modelSelection.instanceId),
|
|
||||||
sessionProvider: thread.session?.providerName ?? undefined,
|
|
||||||
}),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
() =>
|
|
||||||
new ProviderAdapterRequestError({
|
|
||||||
provider: providerErrorLabelFromInstanceHint({
|
|
||||||
instanceId: String(desiredModelSelection.instanceId),
|
|
||||||
}),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const desiredDriverKind = desiredInfo.driverKind;
|
|
||||||
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
|
|
||||||
return yield* new ProviderAdapterRequestError({
|
|
||||||
provider: providerErrorLabel(String(desiredDriverKind)),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const preferredProvider: ProviderDriverKind = desiredDriverKind;
|
|
||||||
if (
|
|
||||||
thread.session !== null &&
|
|
||||||
requestedModelSelection !== undefined &&
|
|
||||||
requestedModelSelection.instanceId !== currentInstanceId
|
|
||||||
) {
|
|
||||||
if (currentInfo.driverKind !== desiredInfo.driverKind) {
|
|
||||||
return yield* new ProviderAdapterRequestError({
|
|
||||||
provider: preferredProvider,
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
currentInfo.continuationIdentity.continuationKey !==
|
|
||||||
desiredInfo.continuationIdentity.continuationKey
|
|
||||||
) {
|
|
||||||
return yield* new ProviderAdapterRequestError({
|
|
||||||
provider: preferredProvider,
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const project = yield* resolveProject(thread.projectId);
|
|
||||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
|
||||||
thread,
|
|
||||||
projects: project ? [project] : [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const startProviderSession = (input?: {
|
const startProviderSession = (input?: {
|
||||||
readonly resumeCursor?: unknown;
|
readonly resumeCursor?: unknown;
|
||||||
readonly provider?: ProviderDriverKind;
|
readonly provider?: ProviderKind;
|
||||||
}) =>
|
}) =>
|
||||||
providerService.startSession(threadId, {
|
providerService.startSession(threadId, {
|
||||||
threadId,
|
threadId,
|
||||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||||
providerInstanceId: desiredInstanceId,
|
|
||||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||||
modelSelection: desiredModelSelection,
|
modelSelection: desiredModelSelection,
|
||||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||||
@@ -405,55 +314,42 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const bindSessionToThread = (session: ProviderSession) =>
|
const bindSessionToThread = (session: ProviderSession) =>
|
||||||
Effect.gen(function* () {
|
setThreadSession({
|
||||||
if (session.providerInstanceId === undefined) {
|
threadId,
|
||||||
return yield* new ProviderAdapterRequestError({
|
session: {
|
||||||
provider: providerErrorLabel(session.provider),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Provider session '${session.threadId}' started without a provider instance id.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
yield* setThreadSession({
|
|
||||||
threadId,
|
threadId,
|
||||||
session: {
|
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||||
threadId,
|
providerName: session.provider,
|
||||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
runtimeMode: desiredRuntimeMode,
|
||||||
providerName: session.provider,
|
// Provider turn ids are not orchestration turn ids.
|
||||||
providerInstanceId: session.providerInstanceId,
|
activeTurnId: null,
|
||||||
runtimeMode: desiredRuntimeMode,
|
lastError: session.lastError ?? null,
|
||||||
// Provider turn ids are not orchestration turn ids.
|
updatedAt: session.updatedAt,
|
||||||
activeTurnId: null,
|
},
|
||||||
lastError: session.lastError ?? null,
|
createdAt,
|
||||||
updatedAt: session.updatedAt,
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const activeSession = yield* resolveActiveSession(threadId);
|
||||||
const existingSessionThreadId =
|
const existingSessionThreadId =
|
||||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||||
if (existingSessionThreadId) {
|
if (existingSessionThreadId) {
|
||||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||||
const cwdChanged = effectiveCwd !== activeSession?.cwd;
|
const sessionModelSwitch =
|
||||||
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
|
currentProvider === undefined
|
||||||
.sessionModelSwitch;
|
? "in-session"
|
||||||
|
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||||
const modelChanged =
|
const modelChanged =
|
||||||
requestedModelSelection !== undefined &&
|
requestedModelSelection !== undefined &&
|
||||||
requestedModelSelection.model !== activeSession?.model;
|
requestedModelSelection.model !== activeSession?.model;
|
||||||
const instanceChanged =
|
|
||||||
requestedModelSelection !== undefined &&
|
|
||||||
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
|
|
||||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
|
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
|
||||||
const previousModelSelection = threadModelSelections.get(threadId);
|
const previousModelSelection = threadModelSelections.get(threadId);
|
||||||
const shouldRestartForModelSelectionChange =
|
const shouldRestartForModelSelectionChange =
|
||||||
preferredProvider === "claudeAgent" &&
|
currentProvider === "claudeAgent" &&
|
||||||
requestedModelSelection !== undefined &&
|
requestedModelSelection !== undefined &&
|
||||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!runtimeModeChanged &&
|
!runtimeModeChanged &&
|
||||||
!cwdChanged &&
|
|
||||||
!instanceChanged &&
|
|
||||||
!shouldRestartForModelChange &&
|
!shouldRestartForModelChange &&
|
||||||
!shouldRestartForModelSelectionChange
|
!shouldRestartForModelSelectionChange
|
||||||
) {
|
) {
|
||||||
@@ -466,18 +362,12 @@ const make = Effect.gen(function* () {
|
|||||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||||
threadId,
|
threadId,
|
||||||
existingSessionThreadId,
|
existingSessionThreadId,
|
||||||
currentProvider: activeSession?.provider,
|
currentProvider,
|
||||||
currentInstanceId,
|
desiredProvider: desiredModelSelection.provider,
|
||||||
desiredInstanceId,
|
|
||||||
desiredProvider: desiredModelSelection.instanceId,
|
|
||||||
currentRuntimeMode: thread.session?.runtimeMode,
|
currentRuntimeMode: thread.session?.runtimeMode,
|
||||||
desiredRuntimeMode: thread.runtimeMode,
|
desiredRuntimeMode: thread.runtimeMode,
|
||||||
runtimeModeChanged,
|
runtimeModeChanged,
|
||||||
previousCwd: activeSession?.cwd,
|
|
||||||
desiredCwd: effectiveCwd,
|
|
||||||
cwdChanged,
|
|
||||||
modelChanged,
|
modelChanged,
|
||||||
instanceChanged,
|
|
||||||
shouldRestartForModelChange,
|
shouldRestartForModelChange,
|
||||||
shouldRestartForModelSelectionChange,
|
shouldRestartForModelSelectionChange,
|
||||||
hasResumeCursor: resumeCursor !== undefined,
|
hasResumeCursor: resumeCursor !== undefined,
|
||||||
@@ -491,7 +381,6 @@ const make = Effect.gen(function* () {
|
|||||||
restartedSessionThreadId: restartedSession.threadId,
|
restartedSessionThreadId: restartedSession.threadId,
|
||||||
provider: restartedSession.provider,
|
provider: restartedSession.provider,
|
||||||
runtimeMode: restartedSession.runtimeMode,
|
runtimeMode: restartedSession.runtimeMode,
|
||||||
cwd: restartedSession.cwd,
|
|
||||||
});
|
});
|
||||||
yield* bindSessionToThread(restartedSession);
|
yield* bindSessionToThread(restartedSession);
|
||||||
return restartedSession.threadId;
|
return restartedSession.threadId;
|
||||||
@@ -534,14 +423,7 @@ const make = Effect.gen(function* () {
|
|||||||
const sessionModelSwitch =
|
const sessionModelSwitch =
|
||||||
activeSession === undefined
|
activeSession === undefined
|
||||||
? "in-session"
|
? "in-session"
|
||||||
: activeSession.providerInstanceId === undefined
|
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||||
? yield* new ProviderAdapterRequestError({
|
|
||||||
provider: providerErrorLabel(activeSession.provider),
|
|
||||||
method: "thread.turn.start",
|
|
||||||
detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,
|
|
||||||
})
|
|
||||||
: (yield* providerService.getCapabilities(activeSession.providerInstanceId))
|
|
||||||
.sessionModelSwitch;
|
|
||||||
const requestedModelSelection =
|
const requestedModelSelection =
|
||||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||||
const modelForTurn =
|
const modelForTurn =
|
||||||
@@ -597,7 +479,7 @@ const make = Effect.gen(function* () {
|
|||||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||||
if (targetBranch === oldBranch) return;
|
if (targetBranch === oldBranch) return;
|
||||||
|
|
||||||
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||||
yield* orchestrationEngine.dispatch({
|
yield* orchestrationEngine.dispatch({
|
||||||
type: "thread.meta.update",
|
type: "thread.meta.update",
|
||||||
commandId: serverCommandId("worktree-branch-rename"),
|
commandId: serverCommandId("worktree-branch-rename"),
|
||||||
@@ -605,7 +487,7 @@ const make = Effect.gen(function* () {
|
|||||||
branch: renamed.branch,
|
branch: renamed.branch,
|
||||||
worktreePath: cwd,
|
worktreePath: cwd,
|
||||||
});
|
});
|
||||||
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.catchCause((cause) =>
|
Effect.catchCause((cause) =>
|
||||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||||
@@ -692,11 +574,10 @@ const make = Effect.gen(function* () {
|
|||||||
const isFirstUserMessageTurn =
|
const isFirstUserMessageTurn =
|
||||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
||||||
if (isFirstUserMessageTurn) {
|
if (isFirstUserMessageTurn) {
|
||||||
const project = yield* resolveProject(thread.projectId);
|
|
||||||
const generationCwd =
|
const generationCwd =
|
||||||
resolveThreadWorkspaceCwd({
|
resolveThreadWorkspaceCwd({
|
||||||
thread,
|
thread,
|
||||||
projects: project ? [project] : [],
|
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
||||||
}) ?? process.cwd();
|
}) ?? process.cwd();
|
||||||
const generationInput = {
|
const generationInput = {
|
||||||
messageText: message.text,
|
messageText: message.text,
|
||||||
@@ -830,16 +711,20 @@ const make = Effect.gen(function* () {
|
|||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.catchCause((cause) =>
|
Effect.catchCause((cause) =>
|
||||||
appendProviderFailureActivity({
|
Effect.gen(function* () {
|
||||||
threadId: event.payload.threadId,
|
yield* appendProviderFailureActivity({
|
||||||
kind: "provider.approval.respond.failed",
|
threadId: event.payload.threadId,
|
||||||
summary: "Provider approval response failed",
|
kind: "provider.approval.respond.failed",
|
||||||
detail: isUnknownPendingApprovalRequestError(cause)
|
summary: "Provider approval response failed",
|
||||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
detail: isUnknownPendingApprovalRequestError(cause)
|
||||||
: Cause.pretty(cause),
|
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||||
turnId: null,
|
: Cause.pretty(cause),
|
||||||
createdAt: event.payload.createdAt,
|
turnId: null,
|
||||||
requestId: event.payload.requestId,
|
createdAt: event.payload.createdAt,
|
||||||
|
requestId: event.payload.requestId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isUnknownPendingApprovalRequestError(cause)) return;
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -909,9 +794,6 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
status: "stopped",
|
status: "stopped",
|
||||||
providerName: thread.session?.providerName ?? null,
|
providerName: thread.session?.providerName ?? null,
|
||||||
...(thread.session?.providerInstanceId !== undefined
|
|
||||||
? { providerInstanceId: thread.session.providerInstanceId }
|
|
||||||
: {}),
|
|
||||||
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: thread.session?.lastError ?? null,
|
lastError: thread.session?.lastError ?? null,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -4,16 +4,12 @@ import {
|
|||||||
CommandId,
|
CommandId,
|
||||||
MessageId,
|
MessageId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationMessage,
|
|
||||||
type OrchestrationProposedPlanId,
|
type OrchestrationProposedPlanId,
|
||||||
CheckpointRef,
|
CheckpointRef,
|
||||||
isToolLifecycleItemType,
|
isToolLifecycleItemType,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type ThreadTokenUsageSnapshot,
|
type ThreadTokenUsageSnapshot,
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationCheckpointSummary,
|
|
||||||
type OrchestrationProposedPlan,
|
|
||||||
type OrchestrationThread,
|
|
||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
type ProviderRuntimeEvent,
|
type ProviderRuntimeEvent,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -23,9 +19,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
|||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||||
|
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||||
import { isGitRepository } from "../../git/Utils.ts";
|
import { isGitRepository } from "../../git/Utils.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import {
|
import {
|
||||||
ProviderRuntimeIngestionService,
|
ProviderRuntimeIngestionService,
|
||||||
type ProviderRuntimeIngestionShape,
|
type ProviderRuntimeIngestionShape,
|
||||||
@@ -81,82 +77,6 @@ function sameId(left: string | null | undefined, right: string | null | undefine
|
|||||||
return left === right;
|
return left === right;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasAssistantMessageForTurn(
|
|
||||||
messages: ReadonlyArray<OrchestrationMessage>,
|
|
||||||
turnId: TurnId,
|
|
||||||
options?: { readonly streamingOnly?: boolean },
|
|
||||||
): boolean {
|
|
||||||
for (let index = 0; index < messages.length; index += 1) {
|
|
||||||
const message = messages[index];
|
|
||||||
if (!message) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (message.role !== "assistant" || message.turnId !== turnId) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (options?.streamingOnly === true && !message.streaming) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function findMessageById(
|
|
||||||
messages: ReadonlyArray<OrchestrationMessage>,
|
|
||||||
messageId: MessageId,
|
|
||||||
): OrchestrationMessage | undefined {
|
|
||||||
for (let index = 0; index < messages.length; index += 1) {
|
|
||||||
const message = messages[index];
|
|
||||||
if (message?.id === messageId) {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function findProposedPlanById(
|
|
||||||
proposedPlans: ReadonlyArray<
|
|
||||||
Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
|
||||||
>,
|
|
||||||
planId: string,
|
|
||||||
):
|
|
||||||
| Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
|
||||||
| undefined {
|
|
||||||
for (let index = 0; index < proposedPlans.length; index += 1) {
|
|
||||||
const proposedPlan = proposedPlans[index];
|
|
||||||
if (proposedPlan?.id === planId) {
|
|
||||||
return proposedPlan;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasCheckpointForTurn(
|
|
||||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
|
||||||
turnId: TurnId,
|
|
||||||
): boolean {
|
|
||||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
|
||||||
if (checkpoints[index]?.turnId === turnId) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function maxCheckpointTurnCount(
|
|
||||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
|
||||||
): number {
|
|
||||||
let maxTurnCount = 0;
|
|
||||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
|
||||||
const checkpoint = checkpoints[index];
|
|
||||||
if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {
|
|
||||||
maxTurnCount = checkpoint.checkpointTurnCount;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return maxTurnCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
function truncateDetail(value: string, limit = 180): string {
|
function truncateDetail(value: string, limit = 180): string {
|
||||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||||
}
|
}
|
||||||
@@ -602,7 +522,6 @@ function runtimeEventToActivities(
|
|||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
const serverSettingsService = yield* ServerSettingsService;
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
@@ -634,16 +553,20 @@ const make = Effect.gen(function* () {
|
|||||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
|
||||||
return yield* projectionSnapshotQuery
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
.getThreadDetailById(threadId)
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
if (!thread) {
|
||||||
});
|
return false;
|
||||||
|
}
|
||||||
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
|
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||||
return yield* projectionSnapshotQuery
|
thread,
|
||||||
.getThreadShellById(threadId)
|
projects: readModel.projects,
|
||||||
.pipe(Effect.map(Option.getOrUndefined));
|
});
|
||||||
|
if (!workspaceCwd) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return isGitRepository(workspaceCwd);
|
||||||
});
|
});
|
||||||
|
|
||||||
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
||||||
@@ -994,7 +917,7 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
|
||||||
yield* orchestrationEngine.dispatch({
|
yield* orchestrationEngine.dispatch({
|
||||||
type: "thread.proposed-plan.upsert",
|
type: "thread.proposed-plan.upsert",
|
||||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||||
@@ -1147,7 +1070,8 @@ const make = Effect.gen(function* () {
|
|||||||
implementationThreadId: ThreadId,
|
implementationThreadId: ThreadId,
|
||||||
implementedAt: string,
|
implementedAt: string,
|
||||||
) {
|
) {
|
||||||
const sourceThread = yield* resolveThreadDetail(sourceThreadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
|
||||||
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
||||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||||
return;
|
return;
|
||||||
@@ -1172,19 +1096,10 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const thread = yield* resolveThreadShell(event.threadId);
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
|
|
||||||
let loadedThreadDetail: OrchestrationThread | null | undefined;
|
|
||||||
const getLoadedThreadDetail = () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
if (loadedThreadDetail !== undefined) {
|
|
||||||
return loadedThreadDetail;
|
|
||||||
}
|
|
||||||
loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
|
|
||||||
return loadedThreadDetail;
|
|
||||||
});
|
|
||||||
|
|
||||||
const now = event.createdAt;
|
const now = event.createdAt;
|
||||||
const eventTurnId = toTurnId(event.turnId);
|
const eventTurnId = toTurnId(event.turnId);
|
||||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||||
@@ -1296,9 +1211,6 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
status,
|
status,
|
||||||
providerName: event.provider,
|
providerName: event.provider,
|
||||||
...(event.providerInstanceId !== undefined
|
|
||||||
? { providerInstanceId: event.providerInstanceId }
|
|
||||||
: {}),
|
|
||||||
runtimeMode: thread.session?.runtimeMode ?? "full-access",
|
runtimeMode: thread.session?.runtimeMode ?? "full-access",
|
||||||
activeTurnId: nextActiveTurnId,
|
activeTurnId: nextActiveTurnId,
|
||||||
lastError,
|
lastError,
|
||||||
@@ -1362,7 +1274,6 @@ const make = Effect.gen(function* () {
|
|||||||
? toTurnId(event.turnId)
|
? toTurnId(event.turnId)
|
||||||
: undefined;
|
: undefined;
|
||||||
if (pauseForUserTurnId) {
|
if (pauseForUserTurnId) {
|
||||||
const detailedThread = yield* getLoadedThreadDetail();
|
|
||||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||||
serverSettingsService.getSettings,
|
serverSettingsService.getSettings,
|
||||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||||
@@ -1393,11 +1304,10 @@ const make = Effect.gen(function* () {
|
|||||||
event.type === "request.opened"
|
event.type === "request.opened"
|
||||||
? "assistant-delta-finalize-on-request-opened"
|
? "assistant-delta-finalize-on-request-opened"
|
||||||
: "assistant-delta-finalize-on-user-input-requested",
|
: "assistant-delta-finalize-on-user-input-requested",
|
||||||
hasProjectedMessage:
|
hasProjectedMessage: thread.messages.some(
|
||||||
detailedThread !== null &&
|
(entry) =>
|
||||||
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
|
entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
|
||||||
streamingOnly: true,
|
),
|
||||||
}),
|
|
||||||
flushedMessageIds,
|
flushedMessageIds,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1426,19 +1336,21 @@ const make = Effect.gen(function* () {
|
|||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
if (assistantCompletion) {
|
if (assistantCompletion) {
|
||||||
const detailedThread = yield* getLoadedThreadDetail();
|
|
||||||
const messages = detailedThread?.messages ?? [];
|
|
||||||
const turnId = toTurnId(event.turnId);
|
const turnId = toTurnId(event.turnId);
|
||||||
const activeAssistantMessageId = turnId
|
const activeAssistantMessageId = turnId
|
||||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||||
: Option.none<MessageId>();
|
: Option.none<MessageId>();
|
||||||
const hasAssistantMessagesForTurn =
|
const hasAssistantMessagesForTurn =
|
||||||
turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
|
turnId !== undefined
|
||||||
|
? thread.messages.some((entry) => entry.role === "assistant" && entry.turnId === turnId)
|
||||||
|
: false;
|
||||||
const assistantMessageId = Option.getOrElse(
|
const assistantMessageId = Option.getOrElse(
|
||||||
activeAssistantMessageId,
|
activeAssistantMessageId,
|
||||||
() => assistantCompletion.messageId,
|
() => assistantCompletion.messageId,
|
||||||
);
|
);
|
||||||
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
|
const existingAssistantMessage = thread.messages.find(
|
||||||
|
(entry) => entry.id === assistantMessageId,
|
||||||
|
);
|
||||||
const shouldApplyFallbackCompletionText =
|
const shouldApplyFallbackCompletionText =
|
||||||
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
||||||
|
|
||||||
@@ -1478,11 +1390,10 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (proposedPlanCompletion) {
|
if (proposedPlanCompletion) {
|
||||||
const detailedThread = yield* getLoadedThreadDetail();
|
|
||||||
yield* finalizeBufferedProposedPlan({
|
yield* finalizeBufferedProposedPlan({
|
||||||
event,
|
event,
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
threadProposedPlans: detailedThread?.proposedPlans ?? [],
|
threadProposedPlans: thread.proposedPlans,
|
||||||
planId: proposedPlanCompletion.planId,
|
planId: proposedPlanCompletion.planId,
|
||||||
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
||||||
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
||||||
@@ -1491,9 +1402,6 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "turn.completed") {
|
if (event.type === "turn.completed") {
|
||||||
const detailedThread = yield* getLoadedThreadDetail();
|
|
||||||
const messages = detailedThread?.messages ?? [];
|
|
||||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
|
||||||
const turnId = toTurnId(event.turnId);
|
const turnId = toTurnId(event.turnId);
|
||||||
if (turnId) {
|
if (turnId) {
|
||||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
|
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
|
||||||
@@ -1508,7 +1416,9 @@ const make = Effect.gen(function* () {
|
|||||||
createdAt: now,
|
createdAt: now,
|
||||||
commandTag: "assistant-complete-finalize",
|
commandTag: "assistant-complete-finalize",
|
||||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||||
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
|
hasProjectedMessage: thread.messages.some(
|
||||||
|
(entry) => entry.id === assistantMessageId,
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
).pipe(Effect.asVoid);
|
).pipe(Effect.asVoid);
|
||||||
@@ -1518,7 +1428,7 @@ const make = Effect.gen(function* () {
|
|||||||
yield* finalizeBufferedProposedPlan({
|
yield* finalizeBufferedProposedPlan({
|
||||||
event,
|
event,
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
threadProposedPlans: proposedPlans,
|
threadProposedPlans: thread.proposedPlans,
|
||||||
planId: proposedPlanIdForTurn(thread.id, turnId),
|
planId: proposedPlanIdForTurn(thread.id, turnId),
|
||||||
turnId,
|
turnId,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -1546,9 +1456,6 @@ const make = Effect.gen(function* () {
|
|||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
status: "error",
|
status: "error",
|
||||||
providerName: event.provider,
|
providerName: event.provider,
|
||||||
...(event.providerInstanceId !== undefined
|
|
||||||
? { providerInstanceId: event.providerInstanceId }
|
|
||||||
: {}),
|
|
||||||
runtimeMode: thread.session?.runtimeMode ?? "full-access",
|
runtimeMode: thread.session?.runtimeMode ?? "full-access",
|
||||||
activeTurnId: eventTurnId ?? null,
|
activeTurnId: eventTurnId ?? null,
|
||||||
lastError: runtimeErrorMessage,
|
lastError: runtimeErrorMessage,
|
||||||
@@ -1570,24 +1477,21 @@ const make = Effect.gen(function* () {
|
|||||||
|
|
||||||
if (event.type === "turn.diff.updated") {
|
if (event.type === "turn.diff.updated") {
|
||||||
const turnId = toTurnId(event.turnId);
|
const turnId = toTurnId(event.turnId);
|
||||||
const checkpointContext = turnId
|
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||||
? yield* projectionSnapshotQuery
|
|
||||||
.getThreadCheckpointContext(thread.id)
|
|
||||||
.pipe(Effect.map(Option.getOrUndefined))
|
|
||||||
: undefined;
|
|
||||||
const workspaceCwd =
|
|
||||||
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
|
|
||||||
if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
|
|
||||||
// Skip if a checkpoint already exists for this turn. A real
|
// Skip if a checkpoint already exists for this turn. A real
|
||||||
// (non-placeholder) capture from CheckpointReactor should not
|
// (non-placeholder) capture from CheckpointReactor should not
|
||||||
// be clobbered, and dispatching a duplicate placeholder for the
|
// be clobbered, and dispatching a duplicate placeholder for the
|
||||||
// same turnId would produce an unstable checkpointTurnCount.
|
// same turnId would produce an unstable checkpointTurnCount.
|
||||||
if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
|
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
|
||||||
// Already tracked; no-op.
|
// Already tracked; no-op.
|
||||||
} else {
|
} else {
|
||||||
const assistantMessageId = MessageId.make(
|
const assistantMessageId = MessageId.make(
|
||||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||||
);
|
);
|
||||||
|
const maxTurnCount = thread.checkpoints.reduce(
|
||||||
|
(max, c) => Math.max(max, c.checkpointTurnCount),
|
||||||
|
0,
|
||||||
|
);
|
||||||
yield* orchestrationEngine.dispatch({
|
yield* orchestrationEngine.dispatch({
|
||||||
type: "thread.turn.diff.complete",
|
type: "thread.turn.diff.complete",
|
||||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||||
@@ -1598,7 +1502,7 @@ const make = Effect.gen(function* () {
|
|||||||
status: "missing",
|
status: "missing",
|
||||||
files: [],
|
files: [],
|
||||||
assistantMessageId,
|
assistantMessageId,
|
||||||
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
|
checkpointTurnCount: maxTurnCount + 1,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,11 @@
|
|||||||
*
|
*
|
||||||
* @module OrchestrationEngineService
|
* @module OrchestrationEngineService
|
||||||
*/
|
*/
|
||||||
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
|
import type {
|
||||||
|
OrchestrationCommand,
|
||||||
|
OrchestrationEvent,
|
||||||
|
OrchestrationReadModel,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
import { Context } from "effect";
|
import { Context } from "effect";
|
||||||
import type { Effect, Stream } from "effect";
|
import type { Effect, Stream } from "effect";
|
||||||
|
|
||||||
@@ -21,6 +25,13 @@ import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
|
|||||||
* OrchestrationEngineShape - Service API for orchestration command and event flow.
|
* OrchestrationEngineShape - Service API for orchestration command and event flow.
|
||||||
*/
|
*/
|
||||||
export interface OrchestrationEngineShape {
|
export interface OrchestrationEngineShape {
|
||||||
|
/**
|
||||||
|
* Read the current in-memory orchestration read model.
|
||||||
|
*
|
||||||
|
* @returns Effect containing the latest read model.
|
||||||
|
*/
|
||||||
|
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||||
*
|
*
|
||||||
@@ -59,7 +70,7 @@ export interface OrchestrationEngineShape {
|
|||||||
* ```ts
|
* ```ts
|
||||||
* const program = Effect.gen(function* () {
|
* const program = Effect.gen(function* () {
|
||||||
* const engine = yield* OrchestrationEngineService
|
* const engine = yield* OrchestrationEngineService
|
||||||
* return yield* engine.dispatch(command)
|
* return yield* engine.getReadModel()
|
||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -28,10 +28,6 @@ export interface ProjectionSnapshotCounts {
|
|||||||
readonly threadCount: number;
|
readonly threadCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProjectionSnapshotSequence {
|
|
||||||
readonly snapshotSequence: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ProjectionThreadCheckpointContext {
|
export interface ProjectionThreadCheckpointContext {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly projectId: ProjectId;
|
readonly projectId: ProjectId;
|
||||||
@@ -44,15 +40,6 @@ export interface ProjectionThreadCheckpointContext {
|
|||||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||||
*/
|
*/
|
||||||
export interface ProjectionSnapshotQueryShape {
|
export interface ProjectionSnapshotQueryShape {
|
||||||
/**
|
|
||||||
* Read the lightweight command snapshot used to bootstrap the in-memory
|
|
||||||
* orchestration engine without hydrating message/activity/checkpoint bodies.
|
|
||||||
*/
|
|
||||||
readonly getCommandReadModel: () => Effect.Effect<
|
|
||||||
OrchestrationReadModel,
|
|
||||||
ProjectionRepositoryError
|
|
||||||
>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the latest orchestration projection snapshot.
|
* Read the latest orchestration projection snapshot.
|
||||||
*
|
*
|
||||||
@@ -72,15 +59,6 @@ export interface ProjectionSnapshotQueryShape {
|
|||||||
ProjectionRepositoryError
|
ProjectionRepositoryError
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Read the latest projection snapshot sequence without hydrating read-model
|
|
||||||
* entities.
|
|
||||||
*/
|
|
||||||
readonly getSnapshotSequence: () => Effect.Effect<
|
|
||||||
ProjectionSnapshotSequence,
|
|
||||||
ProjectionRepositoryError
|
|
||||||
>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read aggregate projection counts without hydrating the full read model.
|
* Read aggregate projection counts without hydrating the full read model.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
type OrchestrationCommand,
|
type OrchestrationCommand,
|
||||||
type OrchestrationReadModel,
|
type OrchestrationReadModel,
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect } from "effect";
|
import { Effect } from "effect";
|
||||||
|
|
||||||
@@ -30,7 +29,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
title: "Project A",
|
title: "Project A",
|
||||||
workspaceRoot: "/tmp/project-a",
|
workspaceRoot: "/tmp/project-a",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
scripts: [],
|
scripts: [],
|
||||||
@@ -43,7 +42,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
title: "Project B",
|
title: "Project B",
|
||||||
workspaceRoot: "/tmp/project-b",
|
workspaceRoot: "/tmp/project-b",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
scripts: [],
|
scripts: [],
|
||||||
@@ -58,7 +57,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
projectId: ProjectId.make("project-a"),
|
projectId: ProjectId.make("project-a"),
|
||||||
title: "Thread A",
|
title: "Thread A",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -81,7 +80,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
projectId: ProjectId.make("project-b"),
|
projectId: ProjectId.make("project-b"),
|
||||||
title: "Thread B",
|
title: "Thread B",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -158,7 +157,7 @@ describe("commandInvariants", () => {
|
|||||||
projectId: ProjectId.make("project-a"),
|
projectId: ProjectId.make("project-a"),
|
||||||
title: "new",
|
title: "new",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -182,7 +181,7 @@ describe("commandInvariants", () => {
|
|||||||
projectId: ProjectId.make("project-a"),
|
projectId: ProjectId.make("project-a"),
|
||||||
title: "dup",
|
title: "dup",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
type OrchestrationCommand,
|
type OrchestrationCommand,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationReadModel,
|
type OrchestrationReadModel,
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect } from "effect";
|
import { Effect } from "effect";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
@@ -64,7 +63,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
|
|||||||
projectId: asProjectId("project-delete"),
|
projectId: asProjectId("project-delete"),
|
||||||
title: "Thread Delete 1",
|
title: "Thread Delete 1",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -94,7 +93,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
|
|||||||
projectId: asProjectId("project-delete"),
|
projectId: asProjectId("project-delete"),
|
||||||
title: "Thread Delete 2",
|
title: "Thread Delete 2",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
ProviderInstanceId,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { createModelSelection } from "@t3tools/shared/model";
|
import { createModelSelection } from "@t3tools/shared/model";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
@@ -139,7 +138,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -164,7 +163,7 @@ describe("decider project scripts", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||||
{ id: "reasoningEffort", value: "high" },
|
{ id: "reasoningEffort", value: "high" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
@@ -189,7 +188,7 @@ describe("decider project scripts", () => {
|
|||||||
expect(turnStartEvent.payload).toMatchObject({
|
expect(turnStartEvent.payload).toMatchObject({
|
||||||
threadId: ThreadId.make("thread-1"),
|
threadId: ThreadId.make("thread-1"),
|
||||||
messageId: asMessageId("message-user-1"),
|
messageId: asMessageId("message-user-1"),
|
||||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||||
{ id: "reasoningEffort", value: "high" },
|
{ id: "reasoningEffort", value: "high" },
|
||||||
{ id: "fastMode", value: true },
|
{ id: "fastMode", value: true },
|
||||||
]),
|
]),
|
||||||
@@ -240,7 +239,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
@@ -322,7 +321,7 @@ describe("decider project scripts", () => {
|
|||||||
projectId: asProjectId("project-1"),
|
projectId: asProjectId("project-1"),
|
||||||
title: "Thread",
|
title: "Thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import {
|
|||||||
CommandId,
|
CommandId,
|
||||||
EventId,
|
EventId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderDriverKind,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -58,7 +57,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -78,7 +77,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: "codex",
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -119,7 +118,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -151,7 +150,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -254,7 +253,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -320,7 +319,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -377,7 +376,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -464,7 +463,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -679,7 +678,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "demo",
|
title: "demo",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -832,7 +831,7 @@ describe("orchestration projector", () => {
|
|||||||
projectId: "project-1",
|
projectId: "project-1",
|
||||||
title: "capped",
|
title: "capped",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
provider: ProviderDriverKind.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
|
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Layer, Option } from "effect";
|
import { Effect, Layer, Option } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
@@ -28,7 +28,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
title: "Null options project",
|
title: "Null options project",
|
||||||
workspaceRoot: "/tmp/project-null-options",
|
workspaceRoot: "/tmp/project-null-options",
|
||||||
defaultModelSelection: {
|
defaultModelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
},
|
},
|
||||||
scripts: [],
|
scripts: [],
|
||||||
@@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
assert.strictEqual(
|
assert.strictEqual(
|
||||||
row.defaultModelSelection,
|
row.defaultModelSelection,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -61,7 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
projectId: ProjectId.make("project-null-options"),
|
projectId: ProjectId.make("project-null-options"),
|
||||||
});
|
});
|
||||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
|
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
|
||||||
instanceId: ProviderInstanceId.make("codex"),
|
provider: "codex",
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
projectId: ProjectId.make("project-null-options"),
|
projectId: ProjectId.make("project-null-options"),
|
||||||
title: "Null options thread",
|
title: "Null options thread",
|
||||||
modelSelection: {
|
modelSelection: {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
},
|
},
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
@@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
assert.strictEqual(
|
assert.strictEqual(
|
||||||
row.modelSelection,
|
row.modelSelection,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -119,7 +119,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
|||||||
threadId: ThreadId.make("thread-null-options"),
|
threadId: ThreadId.make("thread-null-options"),
|
||||||
});
|
});
|
||||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
|
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
|
||||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
provider: "claudeAgent",
|
||||||
model: "claude-opus-4-6",
|
model: "claude-opus-4-6",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
thread_id,
|
thread_id,
|
||||||
status,
|
status,
|
||||||
provider_name,
|
provider_name,
|
||||||
provider_instance_id,
|
|
||||||
runtime_mode,
|
runtime_mode,
|
||||||
active_turn_id,
|
active_turn_id,
|
||||||
last_error,
|
last_error,
|
||||||
@@ -33,7 +32,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
${row.threadId},
|
${row.threadId},
|
||||||
${row.status},
|
${row.status},
|
||||||
${row.providerName},
|
${row.providerName},
|
||||||
${row.providerInstanceId},
|
|
||||||
${row.runtimeMode},
|
${row.runtimeMode},
|
||||||
${row.activeTurnId},
|
${row.activeTurnId},
|
||||||
${row.lastError},
|
${row.lastError},
|
||||||
@@ -43,7 +41,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
status = excluded.status,
|
status = excluded.status,
|
||||||
provider_name = excluded.provider_name,
|
provider_name = excluded.provider_name,
|
||||||
provider_instance_id = excluded.provider_instance_id,
|
|
||||||
runtime_mode = excluded.runtime_mode,
|
runtime_mode = excluded.runtime_mode,
|
||||||
active_turn_id = excluded.active_turn_id,
|
active_turn_id = excluded.active_turn_id,
|
||||||
last_error = excluded.last_error,
|
last_error = excluded.last_error,
|
||||||
@@ -60,7 +57,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
status,
|
status,
|
||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_instance_id AS "providerInstanceId",
|
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
|||||||
INSERT INTO provider_session_runtime (
|
INSERT INTO provider_session_runtime (
|
||||||
thread_id,
|
thread_id,
|
||||||
provider_name,
|
provider_name,
|
||||||
provider_instance_id,
|
|
||||||
adapter_key,
|
adapter_key,
|
||||||
runtime_mode,
|
runtime_mode,
|
||||||
status,
|
status,
|
||||||
@@ -57,7 +56,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
|||||||
VALUES (
|
VALUES (
|
||||||
${runtime.threadId},
|
${runtime.threadId},
|
||||||
${runtime.providerName},
|
${runtime.providerName},
|
||||||
${runtime.providerInstanceId},
|
|
||||||
${runtime.adapterKey},
|
${runtime.adapterKey},
|
||||||
${runtime.runtimeMode},
|
${runtime.runtimeMode},
|
||||||
${runtime.status},
|
${runtime.status},
|
||||||
@@ -68,7 +66,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
|||||||
ON CONFLICT (thread_id)
|
ON CONFLICT (thread_id)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
provider_name = excluded.provider_name,
|
provider_name = excluded.provider_name,
|
||||||
provider_instance_id = excluded.provider_instance_id,
|
|
||||||
adapter_key = excluded.adapter_key,
|
adapter_key = excluded.adapter_key,
|
||||||
runtime_mode = excluded.runtime_mode,
|
runtime_mode = excluded.runtime_mode,
|
||||||
status = excluded.status,
|
status = excluded.status,
|
||||||
@@ -86,7 +83,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
|||||||
SELECT
|
SELECT
|
||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_instance_id AS "providerInstanceId",
|
|
||||||
adapter_key AS "adapterKey",
|
adapter_key AS "adapterKey",
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
status,
|
status,
|
||||||
@@ -106,7 +102,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
|||||||
SELECT
|
SELECT
|
||||||
thread_id AS "threadId",
|
thread_id AS "threadId",
|
||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_instance_id AS "providerInstanceId",
|
|
||||||
adapter_key AS "adapterKey",
|
adapter_key AS "adapterKey",
|
||||||
runtime_mode AS "runtimeMode",
|
runtime_mode AS "runtimeMode",
|
||||||
status,
|
status,
|
||||||
|
|||||||
@@ -39,9 +39,6 @@ import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
|||||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||||
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
|
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
|
||||||
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
|
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
|
||||||
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
|
|
||||||
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
|
|
||||||
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Migration loader with all migrations defined inline.
|
* Migration loader with all migrations defined inline.
|
||||||
@@ -80,9 +77,6 @@ export const migrationEntries = [
|
|||||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||||
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
|
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
|
||||||
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
||||||
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
|
|
||||||
[28, "ProjectionThreadSessionInstanceId", Migration0028],
|
|
||||||
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
|
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const makeMigrationLoader = (throughId?: number) =>
|
export const makeMigrationLoader = (throughId?: number) =>
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
|
|
||||||
import { runMigrations } from "../Migrations.ts";
|
|
||||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
|
||||||
|
|
||||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
|
||||||
|
|
||||||
layer("027_028_ProviderInstanceIdColumns", (it) => {
|
|
||||||
it.effect("continues when provider_session_runtime was partially migrated", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* runMigrations({ toMigrationInclusive: 26 });
|
|
||||||
yield* sql`
|
|
||||||
ALTER TABLE provider_session_runtime
|
|
||||||
ADD COLUMN provider_instance_id TEXT
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* runMigrations({ toMigrationInclusive: 28 });
|
|
||||||
|
|
||||||
const migrations = yield* sql<{
|
|
||||||
readonly migration_id: number;
|
|
||||||
readonly name: string;
|
|
||||||
}>`
|
|
||||||
SELECT migration_id, name
|
|
||||||
FROM effect_sql_migrations
|
|
||||||
WHERE migration_id IN (27, 28)
|
|
||||||
ORDER BY migration_id
|
|
||||||
`;
|
|
||||||
assert.deepStrictEqual(migrations, [
|
|
||||||
{
|
|
||||||
migration_id: 27,
|
|
||||||
name: "ProviderSessionRuntimeInstanceId",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
migration_id: 28,
|
|
||||||
name: "ProjectionThreadSessionInstanceId",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const providerSessionColumns = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA table_info(provider_session_runtime)
|
|
||||||
`;
|
|
||||||
assert.ok(providerSessionColumns.some((column) => column.name === "provider_instance_id"));
|
|
||||||
|
|
||||||
const projectionThreadSessionColumns = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA table_info(projection_thread_sessions)
|
|
||||||
`;
|
|
||||||
assert.ok(
|
|
||||||
projectionThreadSessionColumns.some((column) => column.name === "provider_instance_id"),
|
|
||||||
);
|
|
||||||
|
|
||||||
const providerSessionIndexes = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA index_list(provider_session_runtime)
|
|
||||||
`;
|
|
||||||
assert.ok(
|
|
||||||
providerSessionIndexes.some(
|
|
||||||
(index) => index.name === "idx_provider_session_runtime_instance",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const projectionThreadSessionIndexes = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA index_list(projection_thread_sessions)
|
|
||||||
`;
|
|
||||||
assert.ok(
|
|
||||||
projectionThreadSessionIndexes.some(
|
|
||||||
(index) => index.name === "idx_projection_thread_sessions_instance",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
/**
|
|
||||||
* Adds the nullable `provider_instance_id` routing column to
|
|
||||||
* `provider_session_runtime`.
|
|
||||||
*
|
|
||||||
* Slice D of the provider-array refactor splits "driver kind" from
|
|
||||||
* "configured instance". Existing rows have only the driver name in
|
|
||||||
* `provider_name`; new rows additionally carry the user-defined instance
|
|
||||||
* routing key. The column remains nullable so legacy rows can still decode;
|
|
||||||
* the persistence boundary is responsible for materializing a concrete
|
|
||||||
* instance id before any hot routing path sees the binding.
|
|
||||||
*
|
|
||||||
* The column is nullable on purpose — backfilling it during the migration
|
|
||||||
* would require knowing which configured instance "owned" each historical
|
|
||||||
* session, and that mapping is ambiguous when the user later configures
|
|
||||||
* multiple instances of the same driver. Keeping that compatibility at the
|
|
||||||
* persistence boundary keeps the fallback out of active routing code.
|
|
||||||
*/
|
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
|
|
||||||
export default Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
const columns = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA table_info(provider_session_runtime)
|
|
||||||
`;
|
|
||||||
if (!columns.some((column) => column.name === "provider_instance_id")) {
|
|
||||||
yield* sql`
|
|
||||||
ALTER TABLE provider_session_runtime
|
|
||||||
ADD COLUMN provider_instance_id TEXT
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance
|
|
||||||
ON provider_session_runtime(provider_instance_id)
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
|
|
||||||
export default Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
const columns = yield* sql<{ readonly name: string }>`
|
|
||||||
PRAGMA table_info(projection_thread_sessions)
|
|
||||||
`;
|
|
||||||
if (!columns.some((column) => column.name === "provider_instance_id")) {
|
|
||||||
yield* sql`
|
|
||||||
ALTER TABLE projection_thread_sessions
|
|
||||||
ADD COLUMN provider_instance_id TEXT
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance
|
|
||||||
ON projection_thread_sessions(provider_instance_id)
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
-73
@@ -1,73 +0,0 @@
|
|||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
|
|
||||||
import { runMigrations } from "../Migrations.ts";
|
|
||||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
|
||||||
|
|
||||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
|
||||||
|
|
||||||
layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {
|
|
||||||
it.effect("creates indexes matching thread detail ordering queries", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* runMigrations({ toMigrationInclusive: 28 });
|
|
||||||
yield* runMigrations({ toMigrationInclusive: 29 });
|
|
||||||
|
|
||||||
const activityIndexes = yield* sql<{
|
|
||||||
readonly seq: number;
|
|
||||||
readonly name: string;
|
|
||||||
readonly unique: number;
|
|
||||||
readonly origin: string;
|
|
||||||
readonly partial: number;
|
|
||||||
}>`
|
|
||||||
PRAGMA index_list(projection_thread_activities)
|
|
||||||
`;
|
|
||||||
assert.ok(
|
|
||||||
activityIndexes.some(
|
|
||||||
(index) => index.name === "idx_projection_thread_activities_thread_sequence_created_id",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const activityIndexColumns = yield* sql<{
|
|
||||||
readonly seqno: number;
|
|
||||||
readonly cid: number;
|
|
||||||
readonly name: string;
|
|
||||||
}>`
|
|
||||||
PRAGMA index_info('idx_projection_thread_activities_thread_sequence_created_id')
|
|
||||||
`;
|
|
||||||
assert.deepStrictEqual(
|
|
||||||
activityIndexColumns.map((column) => column.name),
|
|
||||||
["thread_id", "sequence", "created_at", "activity_id"],
|
|
||||||
);
|
|
||||||
|
|
||||||
const messageIndexes = yield* sql<{
|
|
||||||
readonly seq: number;
|
|
||||||
readonly name: string;
|
|
||||||
readonly unique: number;
|
|
||||||
readonly origin: string;
|
|
||||||
readonly partial: number;
|
|
||||||
}>`
|
|
||||||
PRAGMA index_list(projection_thread_messages)
|
|
||||||
`;
|
|
||||||
assert.ok(
|
|
||||||
messageIndexes.some(
|
|
||||||
(index) => index.name === "idx_projection_thread_messages_thread_created_id",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const messageIndexColumns = yield* sql<{
|
|
||||||
readonly seqno: number;
|
|
||||||
readonly cid: number;
|
|
||||||
readonly name: string;
|
|
||||||
}>`
|
|
||||||
PRAGMA index_info('idx_projection_thread_messages_thread_created_id')
|
|
||||||
`;
|
|
||||||
assert.deepStrictEqual(
|
|
||||||
messageIndexColumns.map((column) => column.name),
|
|
||||||
["thread_id", "created_at", "message_id"],
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
|
|
||||||
export default Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id
|
|
||||||
ON projection_thread_activities(thread_id, sequence, created_at, activity_id)
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id
|
|
||||||
ON projection_thread_messages(thread_id, created_at, message_id)
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
RuntimeMode,
|
RuntimeMode,
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
OrchestrationSessionStatus,
|
OrchestrationSessionStatus,
|
||||||
ProviderInstanceId,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -23,7 +22,6 @@ export const ProjectionThreadSession = Schema.Struct({
|
|||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
status: OrchestrationSessionStatus,
|
status: OrchestrationSessionStatus,
|
||||||
providerName: Schema.NullOr(Schema.String),
|
providerName: Schema.NullOr(Schema.String),
|
||||||
providerInstanceId: Schema.NullOr(ProviderInstanceId),
|
|
||||||
runtimeMode: RuntimeMode,
|
runtimeMode: RuntimeMode,
|
||||||
activeTurnId: Schema.NullOr(TurnId),
|
activeTurnId: Schema.NullOr(TurnId),
|
||||||
lastError: Schema.NullOr(Schema.String),
|
lastError: Schema.NullOr(Schema.String),
|
||||||
|
|||||||
Loaded 100 of 502 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user